From c5c11c44f725938ef7cdee292976bdd3f437389a Mon Sep 17 00:00:00 2001 From: Christian Falch Date: Wed, 25 Nov 2026 20:07:45 +0100 Subject: [PATCH 1/3] Add a C++ ABI layout check for public headers (scripts/abi-check) React Native has no check for ABI breaks: changes in the size or memory layout of public C++ types that break code compiled against an earlier release. Between 0.87 and 0.88, facebook::yoga::Style shrank from 280 to 160 bytes, which changed YogaStylableProps and BaseViewProps, and no existing check caught it. scripts/abi-check compiles the stable-API headers with clang, dumps the record, vtable and enum layouts, and compares two versions per platform (iOS, Android) and build type (Debug, Release). The baseline comes from the published Maven artifacts; the other side is a published version or a source checkout. Headers that do not compile in a published layout are skipped only through a reviewed list. --- .../__fixtures__/clang-layout-dump.txt | 117 ++++++ .../__tests__/__fixtures__/dump/Inner.h | 10 + .../__tests__/__fixtures__/dump/Outer.h | 10 + .../__tests__/__fixtures__/dump/Sample.h | 90 +++++ .../layouts/compile/react/Broken.h | 11 + .../__fixtures__/layouts/compile/react/Good.h | 18 + .../react/cxxstableapi/UmbrellaGuard.h | 8 + .../prefab/modules/jsi/include/jsi/jsi.h | 8 + .../react/cxxstableapi/UmbrellaGuard.h | 8 + .../reactnative/include/react/fabric/jsi.h | 8 + .../include/react/featureflags/Flags.h | 10 + .../include/react/renderer/core/Props.h | 10 + .../react/renderer/image/ImageFetcher.h | 10 + .../include/react/renderer/view/HostProps.h | 10 + .../android/react/renderer/view/HostProps.h | 10 + .../ios/react/renderer/view/HostProps.h | 10 + .../ReactAndroid/build.gradle.kts | 30 ++ .../react-native/ReactCommon/jsi/jsi/jsi.h | 8 + .../react/cxxstableapi/UmbrellaGuard.h | 8 + .../ReactCommon/react/featureflags/Flags.h | 10 + .../ReactCommon/react/renderer/core/Props.h | 10 + .../react/renderer/image/ImageFetcher.h | 10 + .../android/react/renderer/view/HostProps.h | 10 + .../ios/react/renderer/view/HostProps.h | 10 + .../react-native/gradle/libs.versions.toml | 6 + .../source/packages/react-native/package.json | 4 + .../__fixtures__/tiers/react/CommentedOut.h | 10 + .../__fixtures__/tiers/react/ForFrameworks.h | 10 + .../__fixtures__/tiers/react/NotAHeader.hpp | 10 + .../__fixtures__/tiers/react/Private.h | 10 + .../__fixtures__/tiers/react/PrivateFirst.h | 11 + .../__fixtures__/tiers/react/Public.h | 10 + .../__fixtures__/tiers/react/Thing+Private.h | 10 + .../__fixtures__/tiers/react/Unclassified.h | 10 + .../react/cxxstableapi/FrameworksGuard.h | 6 + .../tiers/react/cxxstableapi/UmbrellaGuard.h | 8 + .../__fixtures__/tiers/react/jni/Jni.h | 10 + .../tiers/react/nested/Indented.h | 10 + .../tiers/react/platform/android/Dup.h | 10 + .../tiers/react/platform/cxx/Dup.h | 10 + .../tiers/react/platform/ios/Dup.h | 10 + .../tiers/react/samples/InSamples.h | 10 + .../tiers/react/scripts/InScripts.h | 10 + .../__fixtures__/tiers/react/test/InTest.h | 10 + .../__tests__/__fixtures__/v1/AddedField.h | 16 + .../__tests__/__fixtures__/v1/EnumValue.h | 18 + .../__tests__/__fixtures__/v1/InlineBody.h | 22 ++ .../__tests__/__fixtures__/v1/Removed.h | 16 + .../__fixtures__/v1/ReorderedFields.h | 17 + .../__fixtures__/v1/VirtualInserted.h | 19 + .../__tests__/__fixtures__/v2/Added.h | 16 + .../__tests__/__fixtures__/v2/AddedField.h | 17 + .../__tests__/__fixtures__/v2/EnumValue.h | 18 + .../__tests__/__fixtures__/v2/InlineBody.h | 23 ++ .../__fixtures__/v2/ReorderedFields.h | 17 + .../__fixtures__/v2/VirtualInserted.h | 20 + scripts/abi-check/__tests__/args-test.js | 129 +++++++ scripts/abi-check/__tests__/artifacts-test.js | 311 ++++++++++++++++ scripts/abi-check/__tests__/check-test.js | 181 +++++++++ scripts/abi-check/__tests__/cli-test.js | 135 +++++++ .../__tests__/compareHeaderSets-test.js | 86 +++++ scripts/abi-check/__tests__/diff-test.js | 70 ++++ .../abi-check/__tests__/dumpHeaders-test.js | 274 ++++++++++++++ scripts/abi-check/__tests__/normalize-test.js | 123 +++++++ scripts/abi-check/__tests__/source-test.js | 172 +++++++++ scripts/abi-check/__tests__/tiers-test.js | 201 ++++++++++ scripts/abi-check/args.js | 111 ++++++ scripts/abi-check/artifacts.js | 291 +++++++++++++++ scripts/abi-check/ast.js | 343 ++++++++++++++++++ scripts/abi-check/check.js | 277 ++++++++++++++ scripts/abi-check/cli.js | 103 ++++++ scripts/abi-check/diff.js | 41 +++ scripts/abi-check/dump.js | 326 +++++++++++++++++ scripts/abi-check/index.js | 58 +++ scripts/abi-check/layout.js | 81 +++++ scripts/abi-check/normalize.js | 59 +++ scripts/abi-check/skipped-headers.js | 113 ++++++ scripts/abi-check/source.js | 194 ++++++++++ scripts/abi-check/tiers.js | 195 ++++++++++ 79 files changed, 4722 insertions(+) create mode 100644 scripts/abi-check/__tests__/__fixtures__/clang-layout-dump.txt create mode 100644 scripts/abi-check/__tests__/__fixtures__/dump/Inner.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/dump/Outer.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/dump/Sample.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/compile/react/Broken.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/compile/react/Good.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/compile/react/cxxstableapi/UmbrellaGuard.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/jsi/include/jsi/jsi.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/cxxstableapi/UmbrellaGuard.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/fabric/jsi.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/featureflags/Flags.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/core/Props.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/image/platform/android/react/renderer/image/ImageFetcher.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/view/HostProps.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/view/platform/android/react/renderer/view/HostProps.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/view/platform/ios/react/renderer/view/HostProps.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactAndroid/build.gradle.kts create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/jsi/jsi/jsi.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/cxxstableapi/UmbrellaGuard.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/featureflags/Flags.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/core/Props.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/image/platform/android/react/renderer/image/ImageFetcher.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/view/platform/android/react/renderer/view/HostProps.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/view/platform/ios/react/renderer/view/HostProps.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/gradle/libs.versions.toml create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/package.json create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/CommentedOut.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/ForFrameworks.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/NotAHeader.hpp create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/Private.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/PrivateFirst.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/Public.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/Thing+Private.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/Unclassified.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/cxxstableapi/FrameworksGuard.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/cxxstableapi/UmbrellaGuard.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/jni/Jni.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/nested/Indented.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/platform/android/Dup.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/platform/cxx/Dup.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/platform/ios/Dup.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/samples/InSamples.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/scripts/InScripts.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/tiers/react/test/InTest.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/v1/AddedField.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/v1/EnumValue.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/v1/InlineBody.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/v1/Removed.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/v1/ReorderedFields.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/v1/VirtualInserted.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/v2/Added.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/v2/AddedField.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/v2/EnumValue.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/v2/InlineBody.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/v2/ReorderedFields.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/v2/VirtualInserted.h create mode 100644 scripts/abi-check/__tests__/args-test.js create mode 100644 scripts/abi-check/__tests__/artifacts-test.js create mode 100644 scripts/abi-check/__tests__/check-test.js create mode 100644 scripts/abi-check/__tests__/cli-test.js create mode 100644 scripts/abi-check/__tests__/compareHeaderSets-test.js create mode 100644 scripts/abi-check/__tests__/diff-test.js create mode 100644 scripts/abi-check/__tests__/dumpHeaders-test.js create mode 100644 scripts/abi-check/__tests__/normalize-test.js create mode 100644 scripts/abi-check/__tests__/source-test.js create mode 100644 scripts/abi-check/__tests__/tiers-test.js create mode 100644 scripts/abi-check/args.js create mode 100644 scripts/abi-check/artifacts.js create mode 100644 scripts/abi-check/ast.js create mode 100644 scripts/abi-check/check.js create mode 100644 scripts/abi-check/cli.js create mode 100644 scripts/abi-check/diff.js create mode 100644 scripts/abi-check/dump.js create mode 100644 scripts/abi-check/index.js create mode 100644 scripts/abi-check/layout.js create mode 100644 scripts/abi-check/normalize.js create mode 100644 scripts/abi-check/skipped-headers.js create mode 100644 scripts/abi-check/source.js create mode 100644 scripts/abi-check/tiers.js diff --git a/scripts/abi-check/__tests__/__fixtures__/clang-layout-dump.txt b/scripts/abi-check/__tests__/__fixtures__/clang-layout-dump.txt new file mode 100644 index 000000000000..6809d4ea2a18 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/clang-layout-dump.txt @@ -0,0 +1,117 @@ + +*** Dumping AST Record Layout + 0 | struct __NSConstantString_tag + 0 | const int * isa + 8 | int flags + 16 | const char * str + 24 | long length + | [sizeof=32, dsize=32, align=8, + | nvsize=32, nvalign=8] + +*** Dumping AST Record Layout + 0 | union facebook::react::Point::(unnamed at /Users/ci/react-native-0.87.1/Headers/react/Sample.h:3:33) + 0 | int i + 0 | float f + | [sizeof=4, dsize=4, align=4, + | nvsize=4, nvalign=4] + +*** Dumping AST Record Layout + 0 | struct facebook::react::Point + 0 | int x + 8 | double y + 16 | union facebook::react::Point::(unnamed at /Users/ci/react-native-0.87.1/Headers/react/Sample.h:3:33) u + 16 | int i + 16 | float f + | [sizeof=24, dsize=24, align=8, + | nvsize=24, nvalign=8] + +*** Dumping AST Record Layout + 0 | class facebook::react::Shape + 0 | (Shape vtable pointer) + 8 | int id + | [sizeof=16, dsize=12, align=8, + | nvsize=12, nvalign=8] + +*** Dumping AST Record Layout + 0 | struct other::Outside + 0 | int a + | [sizeof=4, dsize=4, align=4, + | nvsize=4, nvalign=4] + +*** Dumping AST Record Layout + 0 | class other::Poly + 0 | (Poly vtable pointer) + | [sizeof=8, dsize=8, align=8, + | nvsize=8, nvalign=8] + +*** Dumping IRgen Record Layout +Record: CXXRecordDecl 0x784f230700 col:7 referenced class Shape definition +|-DefinitionData polymorphic has_constexpr_non_copy_move_ctor +| |-DefaultConstructor exists non_trivial constexpr needs_implicit defaulted_is_constexpr +| |-CopyConstructor simple non_trivial has_const_param needs_implicit implicit_has_const_param +| |-MoveConstructor +| |-CopyAssignment simple non_trivial has_const_param implicit_has_const_param +| |-MoveAssignment +| `-Destructor non_trivial user_declared +|-CXXRecordDecl 0x784f230818 col:7 implicit referenced class Shape +|-AccessSpecDecl 0x784f2308a8 col:15 public +|-CXXDestructorDecl 0x784f2309b0 col:31 used ~Shape 'void () noexcept' virtual +|-CXXMethodDecl 0x784f230b38 col:56 area 'double () const' virtual +|-FieldDecl 0x784f230bf8 col:74 id 'int' +`-CXXMethodDecl 0x784f230d10 col:7 implicit constexpr operator= 'Shape &(const Shape &)' inline default noexcept-unevaluated 0x784f230d10 + `-ParmVarDecl 0x784f230e40 col:7 'const Shape &' + +Layout: + NonVirtualBaseLLVMType:%"class.facebook::react::Shape.base" = type <{ ptr, i32 }> + IsZeroInitializable:1 + BitFields:[ +]> +Original map +Vtable for 'facebook::react::Shape' (5 entries). + 0 | offset_to_top (0) + 1 | facebook::react::Shape RTTI + -- (facebook::react::Shape, 0) vtable address -- + 2 | facebook::react::Shape::~Shape() [complete] + 3 | facebook::react::Shape::~Shape() [deleting] + 4 | double facebook::react::Shape::area() const + +VTable indices for 'facebook::react::Shape' (3 entries). + 0 | facebook::react::Shape::~Shape() [complete] + 1 | facebook::react::Shape::~Shape() [deleting] + 2 | double facebook::react::Shape::area() const + + +*** Dumping IRgen Record Layout +Record: CXXRecordDecl 0x784f233550 col:52 referenced class Poly definition +|-DefinitionData polymorphic has_constexpr_non_copy_move_ctor can_const_default_init +| |-DefaultConstructor exists non_trivial constexpr needs_implicit defaulted_is_constexpr +| |-CopyConstructor simple non_trivial has_const_param needs_implicit implicit_has_const_param +| |-MoveConstructor +| |-CopyAssignment simple non_trivial has_const_param implicit_has_const_param +| |-MoveAssignment +| `-Destructor non_trivial user_declared +|-CXXRecordDecl 0x784f233668 col:52 implicit referenced class Poly +|-AccessSpecDecl 0x784f2336f8 col:59 public +|-CXXDestructorDecl 0x784f2337c8 col:75 used ~Poly 'void () noexcept' virtual +`-CXXMethodDecl 0x784f233980 col:52 implicit constexpr operator= 'Poly &(const Poly &)' inline default noexcept-unevaluated 0x784f233980 + `-ParmVarDecl 0x784f233ab0 col:52 'const Poly &' + +Layout: +Original map +Vtable for 'other::Poly' (4 entries). + 0 | offset_to_top (0) + 1 | other::Poly RTTI + -- (other::Poly, 0) vtable address -- + 2 | other::Poly::~Poly() [complete] + 3 | other::Poly::~Poly() [deleting] + +VTable indices for 'other::Poly' (2 entries). + 0 | other::Poly::~Poly() [complete] + 1 | other::Poly::~Poly() [deleting] + diff --git a/scripts/abi-check/__tests__/__fixtures__/dump/Inner.h b/scripts/abi-check/__tests__/__fixtures__/dump/Inner.h new file mode 100644 index 000000000000..2f86e8d971a4 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/dump/Inner.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include "NotThere.h" diff --git a/scripts/abi-check/__tests__/__fixtures__/dump/Outer.h b/scripts/abi-check/__tests__/__fixtures__/dump/Outer.h new file mode 100644 index 000000000000..6d83aa2618bc --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/dump/Outer.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include "Inner.h" diff --git a/scripts/abi-check/__tests__/__fixtures__/dump/Sample.h b/scripts/abi-check/__tests__/__fixtures__/dump/Sample.h new file mode 100644 index 000000000000..2a5262f4b5d3 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/dump/Sample.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +namespace facebook::react { + +enum Implicit { + First, + /// Documented, so clang adds a comment node. + Second [[deprecated]], + Fifth = 4, + Sixth, +}; + +enum class Fixed : unsigned char { Low = 1, High = Low + 200 }; + +enum class Signed : int { Negative = -3, Next }; + +enum class Wide : unsigned long long { Max = 0xffffffffffffffffull }; + +struct Holder { + enum { Unnamed = 7 }; + int value; +}; + +template +struct Dependent { + enum Size { Value = sizeof(T) }; +}; + +class ProtectedDestructor { + public: + virtual void run(); + + protected: + virtual ~ProtectedDestructor(); +}; + +class NonVirtualProtectedDestructor { + public: + virtual void install(); + + protected: + ~NonVirtualProtectedDestructor(); +}; + +struct Interface { + virtual void run() = 0; +}; + +struct Overrider : Interface { + void run() override; +}; + +struct DeletedDestructor { + virtual ~DeletedDestructor() = delete; + virtual void run(); +}; + +struct Overloaded { + virtual void set(int value); + virtual void set(double value); +}; + +class PrivateVirtual { + public: + ~PrivateVirtual(); + + private: + virtual void hook(); +}; + +struct VirtualDestructorBase { + virtual ~VirtualDestructorBase(); +}; + +struct InheritsVirtualDestructor : VirtualDestructorBase {}; + +} // namespace facebook::react + +namespace other { + +enum Outside { Value }; + +} // namespace other diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/compile/react/Broken.h b/scripts/abi-check/__tests__/__fixtures__/layouts/compile/react/Broken.h new file mode 100644 index 000000000000..8115d4ddd303 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/compile/react/Broken.h @@ -0,0 +1,11 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/compile/react/Good.h b/scripts/abi-check/__tests__/__fixtures__/layouts/compile/react/Good.h new file mode 100644 index 000000000000..cb8e2839290f --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/compile/react/Good.h @@ -0,0 +1,18 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +namespace facebook::react { + +struct Good { + int value; +}; + +} // namespace facebook::react diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/compile/react/cxxstableapi/UmbrellaGuard.h b/scripts/abi-check/__tests__/__fixtures__/layouts/compile/react/cxxstableapi/UmbrellaGuard.h new file mode 100644 index 000000000000..f852921e0abf --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/compile/react/cxxstableapi/UmbrellaGuard.h @@ -0,0 +1,8 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/jsi/include/jsi/jsi.h b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/jsi/include/jsi/jsi.h new file mode 100644 index 000000000000..f852921e0abf --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/jsi/include/jsi/jsi.h @@ -0,0 +1,8 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/cxxstableapi/UmbrellaGuard.h b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/cxxstableapi/UmbrellaGuard.h new file mode 100644 index 000000000000..f852921e0abf --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/cxxstableapi/UmbrellaGuard.h @@ -0,0 +1,8 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/fabric/jsi.h b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/fabric/jsi.h new file mode 100644 index 000000000000..f852921e0abf --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/fabric/jsi.h @@ -0,0 +1,8 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/featureflags/Flags.h b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/featureflags/Flags.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/featureflags/Flags.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/core/Props.h b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/core/Props.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/core/Props.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/image/platform/android/react/renderer/image/ImageFetcher.h b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/image/platform/android/react/renderer/image/ImageFetcher.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/image/platform/android/react/renderer/image/ImageFetcher.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/view/HostProps.h b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/view/HostProps.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/view/HostProps.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/view/platform/android/react/renderer/view/HostProps.h b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/view/platform/android/react/renderer/view/HostProps.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/view/platform/android/react/renderer/view/HostProps.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/view/platform/ios/react/renderer/view/HostProps.h b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/view/platform/ios/react/renderer/view/HostProps.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-android/prefab/modules/reactnative/include/react/renderer/view/platform/ios/react/renderer/view/HostProps.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactAndroid/build.gradle.kts b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactAndroid/build.gradle.kts new file mode 100644 index 000000000000..5894e6905b11 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactAndroid/build.gradle.kts @@ -0,0 +1,30 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +val preparePrefab by + tasks.registering(PreparePrefabHeadersTask::class) { + input.set( + listOf( + PrefabPreprocessingEntry("jsi", Pair("../ReactCommon/jsi/", "")), + PrefabPreprocessingEntry( + "reactnative", + listOf( + Pair("../ReactCommon/react/", "react/"), + // folly + Pair(File(buildDir, "third-party-ndk/folly/").absolutePath, ""), + Pair( + "../ReactCommon/react/renderer/view/platform/android/", + "", + ), + Pair("../ReactCommon/jsi/jsi/jsi.h", "react/fabric/"), + Pair("src/main/jni/react/missing", ""), + ), + ), + ), + ) + outputDir.set(prefabHeadersDir) + } diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/jsi/jsi/jsi.h b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/jsi/jsi/jsi.h new file mode 100644 index 000000000000..f852921e0abf --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/jsi/jsi/jsi.h @@ -0,0 +1,8 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/cxxstableapi/UmbrellaGuard.h b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/cxxstableapi/UmbrellaGuard.h new file mode 100644 index 000000000000..f852921e0abf --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/cxxstableapi/UmbrellaGuard.h @@ -0,0 +1,8 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/featureflags/Flags.h b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/featureflags/Flags.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/featureflags/Flags.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/core/Props.h b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/core/Props.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/core/Props.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/image/platform/android/react/renderer/image/ImageFetcher.h b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/image/platform/android/react/renderer/image/ImageFetcher.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/image/platform/android/react/renderer/image/ImageFetcher.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/view/platform/android/react/renderer/view/HostProps.h b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/view/platform/android/react/renderer/view/HostProps.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/view/platform/android/react/renderer/view/HostProps.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/view/platform/ios/react/renderer/view/HostProps.h b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/view/platform/ios/react/renderer/view/HostProps.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/ReactCommon/react/renderer/view/platform/ios/react/renderer/view/HostProps.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/gradle/libs.versions.toml b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/gradle/libs.versions.toml new file mode 100644 index 000000000000..8d36e3e3dd1d --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/gradle/libs.versions.toml @@ -0,0 +1,6 @@ +[versions] +fbjni = "0.7.0" +folly = "2024.11.18.00" + +[libraries] +fbjni = { module = "com.facebook.fbjni:fbjni", version.ref = "fbjni" } diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/package.json b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/package.json new file mode 100644 index 000000000000..d892a169b039 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/source/packages/react-native/package.json @@ -0,0 +1,4 @@ +{ + "name": "react-native", + "version": "0.88.1" +} diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/CommentedOut.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/CommentedOut.h new file mode 100644 index 000000000000..f3f2c5ba5b24 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/CommentedOut.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +// #include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/ForFrameworks.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/ForFrameworks.h new file mode 100644 index 000000000000..b15816c4efe6 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/ForFrameworks.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include "react/cxxstableapi/FrameworksGuard.h" diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/NotAHeader.hpp b/scripts/abi-check/__tests__/__fixtures__/tiers/react/NotAHeader.hpp new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/NotAHeader.hpp @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/Private.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/Private.h new file mode 100644 index 000000000000..f7ee34b029de --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/Private.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/PrivateFirst.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/PrivateFirst.h new file mode 100644 index 000000000000..a17946b8e668 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/PrivateFirst.h @@ -0,0 +1,11 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/Public.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/Public.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/Public.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/Thing+Private.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/Thing+Private.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/Thing+Private.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/Unclassified.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/Unclassified.h new file mode 100644 index 000000000000..4e178ccd1773 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/Unclassified.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/cxxstableapi/FrameworksGuard.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/cxxstableapi/FrameworksGuard.h new file mode 100644 index 000000000000..22a77615600d --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/cxxstableapi/FrameworksGuard.h @@ -0,0 +1,6 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/cxxstableapi/UmbrellaGuard.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/cxxstableapi/UmbrellaGuard.h new file mode 100644 index 000000000000..cba6bc8f254e --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/cxxstableapi/UmbrellaGuard.h @@ -0,0 +1,8 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/jni/Jni.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/jni/Jni.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/jni/Jni.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/nested/Indented.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/nested/Indented.h new file mode 100644 index 000000000000..d33ce9e83b20 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/nested/Indented.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + + # include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/platform/android/Dup.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/platform/android/Dup.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/platform/android/Dup.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/platform/cxx/Dup.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/platform/cxx/Dup.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/platform/cxx/Dup.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/platform/ios/Dup.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/platform/ios/Dup.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/platform/ios/Dup.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/samples/InSamples.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/samples/InSamples.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/samples/InSamples.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/scripts/InScripts.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/scripts/InScripts.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/scripts/InScripts.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/tiers/react/test/InTest.h b/scripts/abi-check/__tests__/__fixtures__/tiers/react/test/InTest.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/tiers/react/test/InTest.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/v1/AddedField.h b/scripts/abi-check/__tests__/__fixtures__/v1/AddedField.h new file mode 100644 index 000000000000..89c999153db1 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/v1/AddedField.h @@ -0,0 +1,16 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +namespace facebook::react { + +struct AddedField { + int width; +}; + +} // namespace facebook::react diff --git a/scripts/abi-check/__tests__/__fixtures__/v1/EnumValue.h b/scripts/abi-check/__tests__/__fixtures__/v1/EnumValue.h new file mode 100644 index 000000000000..416428b2a260 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/v1/EnumValue.h @@ -0,0 +1,18 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +namespace facebook::react { + +enum class EnumValue : int { + Start = 0, + Middle = 1, + End = 2, +}; + +} // namespace facebook::react diff --git a/scripts/abi-check/__tests__/__fixtures__/v1/InlineBody.h b/scripts/abi-check/__tests__/__fixtures__/v1/InlineBody.h new file mode 100644 index 000000000000..f6d3b831861e --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/v1/InlineBody.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +namespace facebook::react { + +class InlineBody { + public: + int next() const { + return value_ + 1; + } + + private: + int value_; +}; + +} // namespace facebook::react diff --git a/scripts/abi-check/__tests__/__fixtures__/v1/Removed.h b/scripts/abi-check/__tests__/__fixtures__/v1/Removed.h new file mode 100644 index 000000000000..084c8567d401 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/v1/Removed.h @@ -0,0 +1,16 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +namespace facebook::react { + +struct Removed { + int value; +}; + +} // namespace facebook::react diff --git a/scripts/abi-check/__tests__/__fixtures__/v1/ReorderedFields.h b/scripts/abi-check/__tests__/__fixtures__/v1/ReorderedFields.h new file mode 100644 index 000000000000..f6b7049f0cf9 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/v1/ReorderedFields.h @@ -0,0 +1,17 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +namespace facebook::react { + +struct ReorderedFields { + int count; + double ratio; +}; + +} // namespace facebook::react diff --git a/scripts/abi-check/__tests__/__fixtures__/v1/VirtualInserted.h b/scripts/abi-check/__tests__/__fixtures__/v1/VirtualInserted.h new file mode 100644 index 000000000000..b1133411847f --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/v1/VirtualInserted.h @@ -0,0 +1,19 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +namespace facebook::react { + +class VirtualInserted { + public: + virtual ~VirtualInserted(); + virtual void first(); + virtual void last(); +}; + +} // namespace facebook::react diff --git a/scripts/abi-check/__tests__/__fixtures__/v2/Added.h b/scripts/abi-check/__tests__/__fixtures__/v2/Added.h new file mode 100644 index 000000000000..0899e0a528cb --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/v2/Added.h @@ -0,0 +1,16 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +namespace facebook::react { + +struct Added { + int value; +}; + +} // namespace facebook::react diff --git a/scripts/abi-check/__tests__/__fixtures__/v2/AddedField.h b/scripts/abi-check/__tests__/__fixtures__/v2/AddedField.h new file mode 100644 index 000000000000..59b8b017054a --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/v2/AddedField.h @@ -0,0 +1,17 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +namespace facebook::react { + +struct AddedField { + int width; + int height; +}; + +} // namespace facebook::react diff --git a/scripts/abi-check/__tests__/__fixtures__/v2/EnumValue.h b/scripts/abi-check/__tests__/__fixtures__/v2/EnumValue.h new file mode 100644 index 000000000000..4c0ce1c2108a --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/v2/EnumValue.h @@ -0,0 +1,18 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +namespace facebook::react { + +enum class EnumValue : int { + Start = 0, + Middle = 1, + End = 3, +}; + +} // namespace facebook::react diff --git a/scripts/abi-check/__tests__/__fixtures__/v2/InlineBody.h b/scripts/abi-check/__tests__/__fixtures__/v2/InlineBody.h new file mode 100644 index 000000000000..6e9c31e32517 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/v2/InlineBody.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +namespace facebook::react { + +class InlineBody { + public: + int next() const { + int step = 2; + return value_ + step; + } + + private: + int value_; +}; + +} // namespace facebook::react diff --git a/scripts/abi-check/__tests__/__fixtures__/v2/ReorderedFields.h b/scripts/abi-check/__tests__/__fixtures__/v2/ReorderedFields.h new file mode 100644 index 000000000000..f0d753383bd0 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/v2/ReorderedFields.h @@ -0,0 +1,17 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +namespace facebook::react { + +struct ReorderedFields { + double ratio; + int count; +}; + +} // namespace facebook::react diff --git a/scripts/abi-check/__tests__/__fixtures__/v2/VirtualInserted.h b/scripts/abi-check/__tests__/__fixtures__/v2/VirtualInserted.h new file mode 100644 index 000000000000..8ec1a562fb7e --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/v2/VirtualInserted.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +namespace facebook::react { + +class VirtualInserted { + public: + virtual ~VirtualInserted(); + virtual void first(); + virtual void middle(); + virtual void last(); +}; + +} // namespace facebook::react diff --git a/scripts/abi-check/__tests__/args-test.js b/scripts/abi-check/__tests__/args-test.js new file mode 100644 index 000000000000..cabde51b71f3 --- /dev/null +++ b/scripts/abi-check/__tests__/args-test.js @@ -0,0 +1,129 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +'use strict'; + +const {parseCliArgs} = require('../args'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const REQUIRED = [ + '--platform', + 'android', + '--build-type', + 'release', + '--base', + '0.87.1', +]; + +describe('parseCliArgs', () => { + test('compares two published versions, with the default cache', () => { + expect(parseCliArgs([...REQUIRED, '--current', '0.88.1'])).toEqual({ + kind: 'check', + json: false, + options: { + platform: 'android', + buildType: 'release', + base: '0.87.1', + current: {kind: 'version', version: '0.88.1'}, + cacheDir: path.join(os.tmpdir(), 'react-native-abi-check'), + }, + }); + }); + + test('reads a current folder as a checkout, and resolves paths', () => { + const checkout = path.relative(process.cwd(), __dirname); + + expect( + parseCliArgs([ + ...REQUIRED, + '--current', + checkout, + '--cache-dir', + 'cache', + '--json', + ]), + ).toEqual({ + kind: 'check', + json: true, + options: expect.objectContaining({ + current: {kind: 'checkout', root: __dirname}, + cacheDir: path.resolve('cache'), + }), + }); + }); + + test('reads a folder named like a version as a checkout', () => { + const parent = fs.realpathSync( + fs.mkdtempSync(path.join(os.tmpdir(), 'abi-check-args-')), + ); + fs.mkdirSync(path.join(parent, '0.88.1')); + const cwd = process.cwd(); + process.chdir(parent); + try { + expect(parseCliArgs([...REQUIRED, '--current', '0.88.1'])).toMatchObject({ + options: { + current: {kind: 'checkout', root: path.join(parent, '0.88.1')}, + }, + }); + } finally { + process.chdir(cwd); + fs.rmSync(parent, {recursive: true}); + } + }); + + test('rejects a current that is neither a folder nor a version', () => { + expect(() => + parseCliArgs([...REQUIRED, '--current', '../no-such-checkout']), + ).toThrow(/--current/); + }); + + test('reads a prerelease version as a version', () => { + expect( + parseCliArgs([...REQUIRED, '--current', '0.89.0-rc.1']), + ).toMatchObject({ + options: {current: {kind: 'version', version: '0.89.0-rc.1'}}, + }); + }); + + test('asks for help', () => { + expect(parseCliArgs(['--help'])).toEqual({kind: 'help'}); + }); + + test.each([ + [['--platform', 'windows', '--build-type', 'release'], /--platform/], + [['--platform', 'ios', '--build-type', 'profile'], /--build-type/], + [ + ['--platform', 'ios', '--build-type', 'debug', '--base', '0.87.1'], + /--current/, + ], + [ + ['--platform', 'ios', '--build-type', 'debug', '--current', '0.88.1'], + /--base/, + ], + [ + [ + '--platform', + 'ios', + '--build-type', + 'debug', + '--base', + '../react-native', + '--current', + '0.88.1', + ], + /--base/, + ], + [[...REQUIRED, '--current', '0.88.1', '--verbose'], /verbose/], + ])('rejects %j', (argv, message) => { + expect(() => parseCliArgs(argv)).toThrow(message); + }); +}); diff --git a/scripts/abi-check/__tests__/artifacts-test.js b/scripts/abi-check/__tests__/artifacts-test.js new file mode 100644 index 000000000000..15610b472c7f --- /dev/null +++ b/scripts/abi-check/__tests__/artifacts-test.js @@ -0,0 +1,311 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +'use strict'; + +const { + checkArchiveEntries, + fbjniVersionFromCatalog, + fbjniVersionFromPom, + publishedArtifactUrls, + publishedLayout, +} = require('../artifacts'); +const {execFileSync} = require('node:child_process'); +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const LAYOUTS_DIR = path.join(__dirname, '__fixtures__', 'layouts'); +const MAVEN = 'https://repo1.maven.org/maven2'; +const ARTIFACTS = `${MAVEN}/com/facebook/react/react-native-artifacts/0.88.1`; + +describe('publishedArtifactUrls', () => { + test.each([['debug'], ['release']])( + 'names the iOS %s core, which has the headers, and dependencies headers', + buildType => { + expect( + publishedArtifactUrls( + '0.88.1', + 'ios', + buildType === 'debug' ? 'debug' : 'release', + ), + ).toEqual([ + `${ARTIFACTS}/react-native-artifacts-0.88.1-reactnative-core-${buildType}.tar.gz`, + `${ARTIFACTS}/react-native-artifacts-0.88.1-reactnative-dependencies-headers-${buildType}.tar.gz`, + ]); + }, + ); + + test.each([['debug'], ['release']])('names the Android %s AAR', buildType => { + expect( + publishedArtifactUrls( + '0.88.1', + 'android', + buildType === 'debug' ? 'debug' : 'release', + ), + ).toEqual([ + `${MAVEN}/com/facebook/react/react-android/0.88.1/react-android-0.88.1-${buildType}.aar`, + ]); + }); +}); + +describe('fbjni version', () => { + test('reads the fbjni dependency of the react-android POM', () => { + const pom = ` + + com.facebook.yoga + proguard-annotations + 1.19.0 + + + com.facebook.fbjni + fbjni + 0.7.0 + compile + `; + + expect(fbjniVersionFromPom(pom)).toBe('0.7.0'); + expect(() => fbjniVersionFromPom('')).toThrow(/fbjni/); + }); + + test('reads the fbjni version of the Gradle version catalog', () => { + const catalog = fs.readFileSync( + path.join( + LAYOUTS_DIR, + 'source/packages/react-native/gradle/libs.versions.toml', + ), + 'utf8', + ); + + expect(fbjniVersionFromCatalog(catalog)).toBe('0.7.0'); + expect(() => fbjniVersionFromCatalog('[versions]\n')).toThrow(/fbjni/); + }); +}); + +describe('publishedLayout', () => { + let cacheDir = ''; + let sourceDir = ''; + + beforeEach(() => { + cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), 'abi-check-cache-')); + sourceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'abi-check-archives-')); + }); + + afterEach(() => { + fs.rmSync(cacheDir, {recursive: true}); + fs.rmSync(sourceDir, {recursive: true}); + }); + + /** Packs the iOS fixture as the two published iOS archives. */ + function packIos(dir: string, version: string, buildType: string) { + const prefix = `react-native-artifacts-${version}`; + const react = fs.mkdtempSync(path.join(os.tmpdir(), 'abi-check-core-')); + const reactHeaders = path.join( + react, + 'React.xcframework/ios-arm64/React.framework/Headers', + ); + fs.mkdirSync(reactHeaders, {recursive: true}); + fs.writeFileSync(path.join(reactHeaders, 'RCTDefines.h'), '#pragma once\n'); + execFileSync('tar', [ + '-czf', + path.join(dir, `${prefix}-reactnative-core-${buildType}.tar.gz`), + '-C', + path.join(LAYOUTS_DIR, 'maven-ios'), + 'ReactNativeHeaders.xcframework', + '-C', + react, + 'React.xcframework', + ]); + fs.rmSync(react, {recursive: true}); + const deps = fs.mkdtempSync(path.join(os.tmpdir(), 'abi-check-deps-')); + const depsHeaders = path.join( + deps, + 'packages/react-native/third-party', + 'ReactNativeDependenciesHeaders.xcframework/ios-arm64/Headers/folly', + ); + fs.mkdirSync(depsHeaders, {recursive: true}); + fs.writeFileSync(path.join(depsHeaders, 'Folly.h'), '#pragma once\n'); + execFileSync('tar', [ + '-czf', + path.join( + dir, + `${prefix}-reactnative-dependencies-headers-${buildType}.tar.gz`, + ), + '-C', + deps, + 'packages', + ]); + fs.rmSync(deps, {recursive: true}); + } + + const IOS_HEADERS = [ + 'React/RCTDefines.h', + 'folly/Folly.h', + 'react/cxxstableapi/UmbrellaGuard.h', + 'react/featureflags/Flags.h', + 'react/renderer/core/Props.h', + 'react/renderer/view/HostProps.h', + ]; + + test('uses the archives in the cache without downloading them', async () => { + packIos(cacheDir, '0.88.1', 'release'); + const download = jest.fn(() => + Promise.reject(new Error('downloaded a cached archive')), + ); + + const layout = await publishedLayout( + {version: '0.88.1', platform: 'ios', buildType: 'release', cacheDir}, + download, + ); + + expect(download).not.toHaveBeenCalled(); + expect([...layout.headers.keys()].sort()).toEqual(IOS_HEADERS); + expect(layout.frameworkDirs).toHaveLength(1); + expect(layout.headers.get('React/RCTDefines.h')).toBe( + path.join( + layout.frameworkDirs[0], + 'React.framework/Headers/RCTDefines.h', + ), + ); + expect(layout.includeDirs).toHaveLength(2); + for (const [includePath, file] of layout.headers) { + if (!includePath.startsWith('React/')) { + expect(file).toBe( + path.join( + layout.includeDirs[includePath.startsWith('folly/') ? 1 : 0], + includePath, + ), + ); + } + } + }); + + /** Writes the Maven `.sha1` file of each archive in `dir`. */ + function writeChecksums(dir: string) { + for (const name of fs.readdirSync(dir)) { + const sha1 = crypto + .createHash('sha1') + .update(fs.readFileSync(path.join(dir, name))) + .digest('hex'); + fs.writeFileSync(path.join(dir, `${name}.sha1`), sha1); + } + } + + /** Downloads from `sourceDir`, by the file name of the URL. */ + const downloadFromSourceDir = () => + jest.fn((url: string, destination: string) => { + fs.copyFileSync(path.join(sourceDir, path.basename(url)), destination); + return Promise.resolve(); + }); + + test('downloads the archives that are not in the cache', async () => { + packIos(sourceDir, '0.88.1', 'debug'); + writeChecksums(sourceDir); + const download = downloadFromSourceDir(); + + const layout = await publishedLayout( + {version: '0.88.1', platform: 'ios', buildType: 'debug', cacheDir}, + download, + ); + await publishedLayout( + {version: '0.88.1', platform: 'ios', buildType: 'debug', cacheDir}, + download, + ); + + const urls = publishedArtifactUrls('0.88.1', 'ios', 'debug'); + expect(download.mock.calls.map(([url]) => url).sort()).toEqual( + [...urls, ...urls.map(url => `${url}.sha1`)].sort(), + ); + expect( + urls.every(url => fs.existsSync(path.join(cacheDir, path.basename(url)))), + ).toBe(true); + expect([...layout.headers.keys()].sort()).toEqual(IOS_HEADERS); + }); + + test('deletes a download whose SHA-1 does not match and fails', async () => { + packIos(sourceDir, '0.88.1', 'debug'); + writeChecksums(sourceDir); + const [core] = publishedArtifactUrls('0.88.1', 'ios', 'debug'); + fs.writeFileSync( + path.join(sourceDir, `${path.basename(core)}.sha1`), + '0000000000000000000000000000000000000000 core.tar.gz\n', + ); + + await expect( + publishedLayout( + {version: '0.88.1', platform: 'ios', buildType: 'debug', cacheDir}, + downloadFromSourceDir(), + ), + ).rejects.toThrow(/SHA-1/); + expect( + fs.readdirSync(cacheDir).filter(name => name.includes('-core-')), + ).toEqual([]); + }); + + test.each([['../Escape.h'], ['Headers/../../Escape.h'], ['/etc/Escape.h']])( + 'rejects the archive path %s, which is outside the archive folder', + entry => { + expect(() => + checkArchiveEntries('core.tar.gz', ['Headers/Ok.h', entry]), + ).toThrow(entry); + }, + ); + + test('accepts archive paths with dots in names', () => { + expect(() => + checkArchiveEntries('core.tar.gz', ['Headers/a..b.h', './Headers/c.h']), + ).not.toThrow(); + }); + + test('keeps the case of include paths that the file system merges', async () => { + // One folder per header, so that the AAR has both `React/` and `react/` + // where the file system has one of them. + for (const header of ['react/renderer/Props.h', 'React/RCTDefines.h']) { + const aar = fs.mkdtempSync(path.join(os.tmpdir(), 'abi-check-aar-')); + const file = path.join(aar, 'prefab/modules/reactnative/include', header); + fs.mkdirSync(path.dirname(file), {recursive: true}); + fs.writeFileSync(file, '#pragma once\n'); + fs.writeFileSync(path.join(aar, 'classes.jar'), ''); + execFileSync( + 'zip', + ['-qr', path.join(cacheDir, 'react-android-0.88.1-release.aar'), '.'], + {cwd: aar}, + ); + fs.rmSync(aar, {recursive: true}); + } + fs.writeFileSync( + path.join(cacheDir, 'react-android-0.88.1.pom'), + 'fbjni0.7.0', + ); + const fbjni = fs.mkdtempSync(path.join(os.tmpdir(), 'abi-check-fbjni-')); + const fbjniInclude = path.join(fbjni, 'prefab/modules/fbjni/include/fbjni'); + fs.mkdirSync(fbjniInclude, {recursive: true}); + fs.writeFileSync(path.join(fbjniInclude, 'fbjni.h'), '#pragma once\n'); + execFileSync('zip', ['-qr', path.join(cacheDir, 'fbjni-0.7.0.aar'), '.'], { + cwd: fbjni, + }); + fs.rmSync(fbjni, {recursive: true}); + + const layout = await publishedLayout( + {version: '0.88.1', platform: 'android', buildType: 'release', cacheDir}, + () => Promise.reject(new Error('downloaded a cached archive')), + ); + + expect([...layout.headers.keys()].sort()).toEqual([ + 'React/RCTDefines.h', + 'fbjni/fbjni.h', + 'react/renderer/Props.h', + ]); + expect( + layout.includeDirs.map(dir => path.basename(path.dirname(dir))), + ).toEqual(['reactnative', 'fbjni']); + }); +}); diff --git a/scripts/abi-check/__tests__/check-test.js b/scripts/abi-check/__tests__/check-test.js new file mode 100644 index 000000000000..81e0fa9c326e --- /dev/null +++ b/scripts/abi-check/__tests__/check-test.js @@ -0,0 +1,181 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +'use strict'; + +import type {SkippedHeader} from '../skipped-headers'; + +const { + NAMESPACE_PATTERN, + compareLayouts, + headersToCompare, + sideVersion, + skippedHeadersFor, +} = require('../check'); +const {SKIPPED_HEADERS} = require('../skipped-headers'); +const path = require('node:path'); + +const CLANG = process.env.CLANG ?? 'clang++'; +const CLANG_TIMEOUT_MS = 60_000; +const TIERS_DIR = path.join(__dirname, '__fixtures__', 'tiers', 'react'); +const PUBLIC = path.join(TIERS_DIR, 'Public.h'); +const UNCLASSIFIED = path.join(TIERS_DIR, 'Unclassified.h'); +const COMPILE_DIR = path.join(__dirname, '__fixtures__', 'layouts', 'compile'); + +describe('compareLayouts', () => { + beforeAll(() => { + // Fake timers are enabled globally; clang runs in real child processes. + jest.useRealTimers(); + }); + + // The same headers on both sides; react/Broken.h does not compile. + const layout = { + includeDirs: [COMPILE_DIR], + frameworkDirs: [], + headers: new Map( + ['react/Good.h', 'react/Broken.h'].map(header => [ + header, + path.join(COMPILE_DIR, header), + ]), + ), + }; + const compare = (skipped: ReadonlySet) => + compareLayouts(layout, layout, 'ios', {clang: CLANG}, skipped); + + test( + 'drops a skipped header from both sides', + async () => { + const result = await compare(new Set(['react/Broken.h'])); + + expect(result.skippedHeaders).toEqual(['react/Broken.h']); + expect(result.headerCounts).toEqual({base: 1, current: 1}); + expect(result.keyCounts).toEqual({base: 1, current: 1}); + expect(result.breaks).toEqual([]); + }, + CLANG_TIMEOUT_MS, + ); + + test( + 'fails with the name of a header that does not compile and is not skipped', + async () => { + await expect(compare(new Set())).rejects.toThrow(/react\/Broken\.h/); + }, + CLANG_TIMEOUT_MS, + ); +}); + +describe('skippedHeadersFor', () => { + const entries: ReadonlyArray = [ + {platform: 'ios', header: 'react/Always.h', reason: 'missing include'}, + { + platform: 'ios', + header: 'react/Scoped.h', + reason: 'prefab layout', + versions: ['0.87.1'], + }, + {platform: 'android', header: 'react/Android.h', reason: 'missing include'}, + ]; + + test.each([ + ['the base version matches', ['0.87.1', '0.88.1']], + ['the current version matches', ['0.88.0', '0.87.1']], + ])('applies a scoped entry when %s', (_, versions) => { + expect(skippedHeadersFor(entries, 'ios', versions)).toEqual( + new Set(['react/Always.h', 'react/Scoped.h']), + ); + }); + + test('leaves out a scoped entry when neither version matches', () => { + expect(skippedHeadersFor(entries, 'ios', ['0.88.0', '0.88.1'])).toEqual( + new Set(['react/Always.h']), + ); + }); + + test("ignores the other platform's entries", () => { + expect(skippedHeadersFor(entries, 'android', ['0.87.1', '0.88.1'])).toEqual( + new Set(['react/Android.h']), + ); + }); +}); + +describe('sideVersion', () => { + test('is the version of a published side', () => { + expect(sideVersion({kind: 'version', version: '0.88.0'})).toBe('0.88.0'); + }); + + test("is the react-native package's version of a checkout", () => { + expect( + sideVersion({ + kind: 'checkout', + root: path.join(__dirname, '__fixtures__', 'layouts', 'source'), + }), + ).toBe('0.88.1'); + }); +}); + +describe('SKIPPED_HEADERS', () => { + test('lists each header once per platform, with a reason', () => { + const keys = SKIPPED_HEADERS.map( + ({platform, header}) => `${platform} ${header}`, + ); + + expect(new Set(keys).size).toBe(keys.length); + for (const {platform, header, reason, versions} of SKIPPED_HEADERS) { + expect(['ios', 'android']).toContain(platform); + expect(header).toMatch(/^[\w-]+\/[\w/+-]+\.h$/); + expect(reason).not.toBe(''); + for (const version of versions ?? []) { + expect(version).toMatch(/^\d+\.\d+\.\d+(?:-[\w.]+)?$/); + } + } + }); +}); + +describe('NAMESPACE_PATTERN', () => { + test.each([ + ['facebook::react::Props', true], + ['facebook::yoga::Style', true], + ['facebook::jsi::Runtime', true], + ['facebook::jni::JObject', false], + ['folly::dynamic', false], + ])('%s matches: %s', (name, matches) => { + expect(NAMESPACE_PATTERN.test(name)).toBe(matches); + }); +}); + +describe('headersToCompare', () => { + test('dumps each stable API header of either side that the side has', () => { + const base = { + includeDirs: ['/base'], + frameworkDirs: [], + headers: new Map([ + ['react/Kept.h', PUBLIC], + ['react/Demoted.h', PUBLIC], + ['react/Removed.h', PUBLIC], + ['react/Internal.h', UNCLASSIFIED], + ]), + }; + const current = { + includeDirs: ['/current'], + frameworkDirs: [], + headers: new Map([ + ['react/Kept.h', PUBLIC], + ['react/Demoted.h', UNCLASSIFIED], + ['react/Added.h', PUBLIC], + ['react/Internal.h', UNCLASSIFIED], + ]), + }; + + expect(headersToCompare(base, current, 'ios')).toEqual({ + base: ['react/Demoted.h', 'react/Kept.h', 'react/Removed.h'], + current: ['react/Added.h', 'react/Demoted.h', 'react/Kept.h'], + }); + }); +}); diff --git a/scripts/abi-check/__tests__/cli-test.js b/scripts/abi-check/__tests__/cli-test.js new file mode 100644 index 000000000000..c961ade003e2 --- /dev/null +++ b/scripts/abi-check/__tests__/cli-test.js @@ -0,0 +1,135 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +'use strict'; + +import type {CheckOptions, CheckResult} from '../check'; + +const {runCli} = require('../cli'); + +const ARGS = [ + '--platform', + 'android', + '--build-type', + 'release', + '--base', + '0.88.0', + '--current', + '0.88.1', +]; + +const NO_BREAKS: CheckResult = { + breaks: [], + additions: ['L facebook::react::Added'], + headerCounts: {base: 2, current: 3}, + keyCounts: {base: 10, current: 11}, + skippedHeaders: ['react/Skipped.h'], +}; + +const WITH_BREAKS: CheckResult = { + ...NO_BREAKS, + breaks: [{key: 'L facebook::yoga::Style', change: 'changed'}], +}; + +/** Runs the CLI with `checkAbi` answering `result`; collects its output. */ +async function run( + argv: ReadonlyArray, + result: CheckResult | Error = NO_BREAKS, +): Promise<{ + code: number, + stdout: string, + stderr: string, + checked: Array, +}> { + let stdout = ''; + let stderr = ''; + const checked: Array = []; + const code = await runCli(argv, { + checkAbi: options => { + checked.push(options); + return result instanceof Error + ? Promise.reject(result) + : Promise.resolve(result); + }, + stdout: text => { + stdout += text; + }, + stderr: text => { + stderr += text; + }, + }); + return {code, stdout, stderr, checked}; +} + +describe('runCli', () => { + test.each([ + ['a bad platform', ['--platform', 'windows'], /--platform/], + ['a bad build type', ['--build-type', 'profile'], /--build-type/], + ['a bad base version', ['--base', 'latest'], /--base/], + ])('exits with 2 for %s', async (_, override, message) => { + const argv = [...ARGS]; + argv[argv.indexOf(override[0]) + 1] = override[1]; + + const {code, stderr, checked} = await run(argv); + + expect(code).toBe(2); + expect(stderr).toMatch(message); + expect(stderr).toContain('Usage:'); + expect(checked).toEqual([]); + }); + + test('exits with 2 for missing arguments', async () => { + const {code, stderr} = await run(['--platform', 'ios']); + + expect(code).toBe(2); + expect(stderr).toContain('Usage:'); + }); + + test('exits with 2 and the message when the check fails', async () => { + const {code, stderr} = await run( + ARGS, + new Error('clang++ could not compile react/Broken.h'), + ); + + expect(code).toBe(2); + expect(stderr).toContain('react/Broken.h'); + }); + + test('exits with 1 and lists the breaks', async () => { + const {code, stdout} = await run(ARGS, WITH_BREAKS); + + expect(code).toBe(1); + expect(stdout).toContain('changed L facebook::yoga::Style'); + expect(stdout).toContain('react/Skipped.h'); + }); + + test('exits with 0 without breaks', async () => { + const {code, stdout} = await run(ARGS); + + expect(code).toBe(0); + expect(stdout).toMatch(/^No ABI breaks/); + }); + + test('prints the result as JSON', async () => { + const {code, stdout} = await run([...ARGS, '--json'], WITH_BREAKS); + + expect(code).toBe(1); + expect(JSON.parse(stdout)).toEqual(WITH_BREAKS); + }); + + test('documents the exit codes in the help', async () => { + const {code, stdout} = await run(['--help']); + + expect(code).toBe(0); + expect(stdout).toMatch(/0\s.*no ABI breaks/i); + expect(stdout).toMatch(/1\s.*ABI breaks/); + expect(stdout).toMatch(/2\s.*(arguments|error)/); + }); +}); diff --git a/scripts/abi-check/__tests__/compareHeaderSets-test.js b/scripts/abi-check/__tests__/compareHeaderSets-test.js new file mode 100644 index 000000000000..54ee6cee05d7 --- /dev/null +++ b/scripts/abi-check/__tests__/compareHeaderSets-test.js @@ -0,0 +1,86 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +'use strict'; + +import type {DumpOptions} from '../dump'; +import type {AbiBreak} from '../index'; + +const {compareHeaderSets} = require('../index'); +const {spawnSync} = require('node:child_process'); +const fs = require('node:fs'); +const path = require('node:path'); + +const CLANG = process.env.CLANG ?? 'clang++'; +const CLANG_TIMEOUT_MS = 60_000; + +function headerSet(version: 'v1' | 'v2'): DumpOptions { + const dir = path.join(__dirname, '__fixtures__', version); + return { + headers: fs + .readdirSync(dir) + .filter(file => file.endsWith('.h')) + .sort() + .map(file => path.join(dir, file)), + includeDirs: [dir], + clang: CLANG, + namespacePattern: /facebook::react::/, + }; +} + +function byKey(a: AbiBreak, b: AbiBreak): number { + return a.key.localeCompare(b.key); +} + +describe('compareHeaderSets', () => { + beforeAll(() => { + // Fake timers are enabled globally; clang runs in real child processes. + jest.useRealTimers(); + + const probe = spawnSync(CLANG, ['--version'], {encoding: 'utf8'}); + if (probe.error != null || probe.status !== 0) { + throw new Error( + `These tests run clang, but \`${CLANG} --version\` failed: ` + + `${String(probe.error ?? probe.stderr)}. ` + + 'Install clang or set CLANG to the clang++ executable.', + ); + } + }); + + test( + 'reports exactly the ABI breaks and additions between v1 and v2', + async () => { + const {breaks, additions} = await compareHeaderSets( + headerSet('v1'), + headerSet('v2'), + ); + + expect([...breaks].sort(byKey)).toEqual([ + {key: 'E facebook::react::EnumValue', change: 'changed'}, + {key: 'L facebook::react::AddedField', change: 'changed'}, + {key: 'L facebook::react::Removed', change: 'removed'}, + {key: 'L facebook::react::ReorderedFields', change: 'changed'}, + {key: 'V facebook::react::VirtualInserted', change: 'changed'}, + ]); + expect(additions).toEqual(['L facebook::react::Added']); + }, + CLANG_TIMEOUT_MS, + ); + + test( + 'reports nothing when a header set is compared with itself', + async () => { + expect(await compareHeaderSets(headerSet('v1'), headerSet('v1'))).toEqual( + {breaks: [], additions: []}, + ); + }, + CLANG_TIMEOUT_MS, + ); +}); diff --git a/scripts/abi-check/__tests__/diff-test.js b/scripts/abi-check/__tests__/diff-test.js new file mode 100644 index 000000000000..3a6ca298adef --- /dev/null +++ b/scripts/abi-check/__tests__/diff-test.js @@ -0,0 +1,70 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +'use strict'; + +const {diffLayouts} = require('../diff'); + +describe('diffLayouts', () => { + test('reports nothing for identical maps', () => { + const layouts = new Map([ + ['L facebook::react::Point', '0 | int x'], + ['V facebook::react::Shape', '2 | double area() const'], + ]); + + expect(diffLayouts(layouts, new Map(layouts))).toEqual({ + changed: [], + removed: [], + added: [], + }); + }); + + test('separates changed, removed and added keys', () => { + const base = new Map([ + ['L facebook::react::Point', '0 | int x'], + ['V facebook::react::Shape', '2 | double area() const'], + ['E facebook::react::Color', 'Red = 0'], + ['L facebook::react::Gone', '0 | int x'], + ]); + const current = new Map([ + ['L facebook::react::Point', '0 | double x'], + ['V facebook::react::Shape', '2 | double perimeter() const'], + ['E facebook::react::Color', 'Red = 0'], + ['L facebook::react::New', '0 | int x'], + ]); + + expect(diffLayouts(base, current)).toEqual({ + changed: ['L facebook::react::Point', 'V facebook::react::Shape'], + removed: ['L facebook::react::Gone'], + added: ['L facebook::react::New'], + }); + }); + + test('sorts the keys in each list', () => { + const base = new Map([ + ['L facebook::react::Zeta', '0 | int x'], + ['L facebook::react::Alpha', '0 | int x'], + ['L facebook::react::Omega', '0 | int x'], + ['L facebook::react::Beta', '0 | int x'], + ]); + const current = new Map([ + ['L facebook::react::Zeta', '0 | long x'], + ['L facebook::react::Alpha', '0 | long x'], + ['L facebook::react::Yankee', '0 | int x'], + ['L facebook::react::Charlie', '0 | int x'], + ]); + + expect(diffLayouts(base, current)).toEqual({ + changed: ['L facebook::react::Alpha', 'L facebook::react::Zeta'], + removed: ['L facebook::react::Beta', 'L facebook::react::Omega'], + added: ['L facebook::react::Charlie', 'L facebook::react::Yankee'], + }); + }); +}); diff --git a/scripts/abi-check/__tests__/dumpHeaders-test.js b/scripts/abi-check/__tests__/dumpHeaders-test.js new file mode 100644 index 000000000000..12da1e3a00b5 --- /dev/null +++ b/scripts/abi-check/__tests__/dumpHeaders-test.js @@ -0,0 +1,274 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +'use strict'; + +import type {BuildType, DumpOptions} from '../dump'; +import type {LayoutMap} from '../normalize'; + +const {compileFlags, dumpHeaders} = require('../dump'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const CLANG = process.env.CLANG ?? 'clang++'; +const CLANG_TIMEOUT_MS = 60_000; +const FIXTURE_DIR = path.join(__dirname, '__fixtures__', 'dump'); + +function dumpSample(): Promise { + return dumpHeaders({ + headers: [path.join(FIXTURE_DIR, 'Sample.h')], + includeDirs: [FIXTURE_DIR], + clang: CLANG, + namespacePattern: /facebook::react::/, + }); +} + +describe('dumpHeaders', () => { + beforeAll(() => { + // Fake timers are enabled globally; clang runs in real child processes. + jest.useRealTimers(); + }); + + test( + 'keys the enumerator values of each named, non-dependent enum', + async () => { + const enums = [...(await dumpSample())].filter(([key]) => + key.startsWith('E '), + ); + + expect(enums.sort()).toEqual([ + ['E facebook::react::Fixed', ': unsigned char\nLow = 1\nHigh = 201'], + [ + 'E facebook::react::Implicit', + 'First = 0\nSecond = 1\nFifth = 4\nSixth = 5', + ], + ['E facebook::react::Signed', ': int\nNegative = -3\nNext = -2'], + [ + 'E facebook::react::Wide', + ': unsigned long long\nMax = 18446744073709551615', + ], + ]); + }, + CLANG_TIMEOUT_MS, + ); + + test( + 'dumps the vtable of a class whose destructor is not public', + async () => { + const vtable = (await dumpSample()).get( + 'V facebook::react::ProtectedDestructor', + ); + + expect(vtable).toContain( + 'void facebook::react::ProtectedDestructor::run()', + ); + }, + CLANG_TIMEOUT_MS, + ); + + test( + 'rejects with the clang error when the headers do not compile', + async () => { + await expect( + dumpHeaders({ + headers: [path.join(FIXTURE_DIR, 'Missing.h')], + includeDirs: [], + clang: CLANG, + namespacePattern: /facebook::react::/, + }), + ).rejects.toThrow(/Missing\.h/); + }, + CLANG_TIMEOUT_MS, + ); + + test( + 'dumps the vtable of every polymorphic class', + async () => { + const keys = [...(await dumpSample()).keys()]; + + expect(keys).toEqual( + expect.arrayContaining( + [ + 'ProtectedDestructor', + 'NonVirtualProtectedDestructor', + 'Interface', + 'Overrider', + 'DeletedDestructor', + 'Overloaded', + 'PrivateVirtual', + 'VirtualDestructorBase', + 'InheritsVirtualDestructor', + ].map(name => `V facebook::react::${name}`), + ), + ); + }, + CLANG_TIMEOUT_MS, + ); + + test( + 'names the included header that failed to compile first in the error', + async () => { + const dump = dumpHeaders({ + headers: ['Outer.h', 'Sample.h'].map(header => + path.join(FIXTURE_DIR, header), + ), + includeDirs: [], + clang: CLANG, + namespacePattern: /facebook::react::/, + }); + + const message = await dump.then( + () => '', + (error: Error) => error.message, + ); + const [summary] = message.split('\n'); + expect(summary).toContain(path.join(FIXTURE_DIR, 'Outer.h')); + expect(summary).not.toContain('Sample.h'); + expect(message).toContain('NotThere.h'); + }, + CLANG_TIMEOUT_MS, + ); + + test( + 'includes headers whose paths contain quotes and backslashes', + async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'abi-check-')); + const headers = [ + ['Quote"d.h', 'Quoted'], + ['Back\\slash.h', 'Backslashed'], + ].map(([file, type]) => { + const header = path.join(dir, file); + fs.writeFileSync( + header, + `namespace facebook::react { struct ${type} { int value; }; }\n`, + ); + return header; + }); + + try { + const layouts = await dumpHeaders({ + headers, + includeDirs: [], + clang: CLANG, + namespacePattern: /facebook::react::/, + }); + expect([...layouts.keys()].sort()).toEqual([ + 'L facebook::react::Backslashed', + 'L facebook::react::Quoted', + ]); + } finally { + fs.rmSync(dir, {recursive: true}); + } + }, + CLANG_TIMEOUT_MS, + ); +}); + +describe('compileFlags', () => { + const options: DumpOptions = { + headers: [], + includeDirs: ['/include'], + namespacePattern: /facebook::react::/, + }; + const buildTypes: Array<[BuildType, Array]> = [ + ['debug', ['-DDEBUG=1', '-DREACT_NATIVE_DEBUG=1']], + ['release', ['-DNDEBUG=1', '-DREACT_NATIVE_PRODUCTION=1']], + ]; + + test.each(buildTypes)( + 'compiles iOS %s as Objective-C++', + (buildType, buildDefines) => { + expect( + compileFlags({...options, platform: 'ios', buildType, sysroot: '/sdk'}), + ).toEqual([ + '-x', + 'objective-c++', + '-std=c++20', + '--target=arm64-apple-ios15.1', + '-isysroot', + '/sdk', + '-I/include', + '-DFOLLY_NO_CONFIG=1', + '-DFOLLY_MOBILE=1', + '-DFOLLY_USE_LIBCPP=1', + '-DFOLLY_CFG_NO_COROUTINES=1', + '-DFOLLY_HAVE_CLOCK_GETTIME=1', + ...buildDefines, + '-Wno-everything', + '-fno-color-diagnostics', + ]); + }, + ); + + test.each(buildTypes)( + 'compiles Android %s as C++', + (buildType, buildDefines) => { + expect( + compileFlags({ + ...options, + platform: 'android', + buildType, + sysroot: '/ndk/sysroot', + }), + ).toEqual([ + '-x', + 'c++', + '-std=c++20', + '--target=aarch64-linux-android24', + '--sysroot', + '/ndk/sysroot', + '-fexceptions', + '-frtti', + '-I/include', + '-DFOLLY_NO_CONFIG=1', + '-DFOLLY_HAVE_CLOCK_GETTIME=1', + '-DFOLLY_USE_LIBCPP=1', + '-DFOLLY_CFG_NO_COROUTINES=1', + '-DFOLLY_MOBILE=1', + '-DFOLLY_HAVE_RECVMMSG=1', + '-DFOLLY_HAVE_PTHREAD=1', + '-DFOLLY_HAVE_XSI_STRERROR_R=1', + '-DRN_SERIALIZABLE_STATE', + '-DANDROID=1', + '-DHERMES_V1_ENABLED=1', + '-DLOG_TAG="ReactNative"', + ...buildDefines, + '-Wno-everything', + '-fno-color-diagnostics', + ]); + }, + ); + + test('compiles for the host as C++ debug without a platform', () => { + expect(compileFlags(options)).toEqual([ + '-x', + 'c++', + '-std=c++20', + '-I/include', + '-DDEBUG=1', + '-DREACT_NATIVE_DEBUG=1', + '-Wno-everything', + '-fno-color-diagnostics', + ]); + }); + + test('searches the framework dirs after the include dirs', () => { + expect( + compileFlags({...options, frameworkDirs: ['/frameworks']}).slice(3, 5), + ).toEqual(['-I/include', '-F/frameworks']); + }); + + test('requires a sysroot for Android', () => { + expect(() => + compileFlags({...options, platform: 'android', buildType: 'release'}), + ).toThrow(/sysroot/); + }); +}); diff --git a/scripts/abi-check/__tests__/normalize-test.js b/scripts/abi-check/__tests__/normalize-test.js new file mode 100644 index 000000000000..a12495924b0e --- /dev/null +++ b/scripts/abi-check/__tests__/normalize-test.js @@ -0,0 +1,123 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +'use strict'; + +const {normalizeDump} = require('../normalize'); +const fs = require('node:fs'); +const path = require('node:path'); + +const DUMP_HEADERS_ROOT = '/Users/ci/react-native-0.87.1/Headers'; +const rawDump = fs.readFileSync( + path.join(__dirname, '__fixtures__', 'clang-layout-dump.txt'), + 'utf8', +); +const reactOnly = {namespacePattern: /facebook::react::/}; + +describe('normalizeDump', () => { + test('keys record layouts with L and vtables with V by qualified type name', () => { + const keys = [...normalizeDump(rawDump, reactOnly).keys()]; + + expect(keys).toEqual( + expect.arrayContaining([ + 'L facebook::react::Point', + 'L facebook::react::Shape', + 'V facebook::react::Shape', + ]), + ); + for (const key of keys) { + expect(key).toMatch(/^[LV] facebook::react::/); + } + }); + + test('keeps only types that match the namespace pattern', () => { + const keys = [ + ...normalizeDump(rawDump, {namespacePattern: /other::/}).keys(), + ]; + + expect(keys.sort()).toEqual([ + 'L other::Outside', + 'L other::Poly', + 'V other::Poly', + ]); + }); + + test('keeps the fields and size of a record layout', () => { + const shape = normalizeDump(rawDump, reactOnly).get( + 'L facebook::react::Shape', + ); + + expect(shape).toContain('(Shape vtable pointer)'); + expect(shape).toContain('int id'); + expect(shape).toContain('sizeof=16'); + }); + + test('keeps the entries of a vtable', () => { + const vtable = normalizeDump(rawDump, reactOnly).get( + 'V facebook::react::Shape', + ); + + expect(vtable).toContain('facebook::react::Shape::~Shape() [deleting]'); + expect(vtable).toContain('double facebook::react::Shape::area() const'); + }); + + test('strips absolute header paths from keys and values', () => { + const normalized = normalizeDump(rawDump, reactOnly); + const movedDump = rawDump.replaceAll( + DUMP_HEADERS_ROOT, + '/home/runner/work/react-native-0.88.0/Headers', + ); + + for (const [key, value] of normalized) { + expect(key).not.toContain(DUMP_HEADERS_ROOT); + expect(value).not.toContain(DUMP_HEADERS_ROOT); + } + expect(normalizeDump(movedDump, reactOnly)).toEqual(normalized); + }); + + test('strips hex addresses, which differ between clang runs', () => { + const normalized = normalizeDump(rawDump, reactOnly); + const otherRunDump = rawDump.replace(/0x[0-9a-f]+/g, '0xdeadbeef00'); + + for (const value of normalized.values()) { + expect(value).not.toMatch(/0x[0-9a-f]{6,}/); + } + expect(normalizeDump(otherRunDump, reactOnly)).toEqual(normalized); + }); + + test('ignores source positions and IRgen blocks', () => { + const normalized = normalizeDump(rawDump, reactOnly); + const editedHeaderDump = rawDump + .replace( + /\.h:(\d+):(\d+)/g, + (_, line, column) => `.h:${Number(line) + 10}:${Number(column) + 2}`, + ) + .replace(/col:(\d+)/g, (_, column) => `col:${Number(column) + 2}`); + + expect(editedHeaderDump).not.toEqual(rawDump); + expect(normalizeDump(editedHeaderDump, reactOnly)).toEqual(normalized); + for (const value of normalized.values()) { + expect(value).not.toMatch( + /IRgen|CXXRecordDecl|CGRecordLayout|LLVMType|\.h:\d+:\d+|col:\d+/, + ); + } + }); + + test('names unnamed nested records (unnamed) inside their parent only', () => { + const normalized = normalizeDump(rawDump, reactOnly); + + expect(normalized.get('L facebook::react::Point')).toContain( + 'union facebook::react::Point::(unnamed) u', + ); + for (const key of normalized.keys()) { + expect(key).not.toContain('unnamed'); + } + }); +}); diff --git a/scripts/abi-check/__tests__/source-test.js b/scripts/abi-check/__tests__/source-test.js new file mode 100644 index 000000000000..f4504e212e10 --- /dev/null +++ b/scripts/abi-check/__tests__/source-test.js @@ -0,0 +1,172 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +'use strict'; + +const { + androidSourceLayout, + iosSourceLayout, + prefabHeaderRules, +} = require('../source'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const LAYOUTS_DIR = path.join(__dirname, '__fixtures__', 'layouts'); +const PACKAGE_DIR = path.join(LAYOUTS_DIR, 'source/packages/react-native'); + +/** The files under `dir`, by their paths below it. */ +function filesUnder(dir: string): Array { + return fs + .readdirSync(dir, {recursive: true, encoding: 'utf8'}) + .filter(entry => fs.statSync(path.join(dir, entry)).isFile()) + .map(entry => entry.split(path.sep).join('/')) + .sort(); +} + +describe('prefabHeaderRules', () => { + test('reads the source folders of each prefab module', () => { + const script = fs.readFileSync( + path.join(PACKAGE_DIR, 'ReactAndroid/build.gradle.kts'), + 'utf8', + ); + + expect(prefabHeaderRules(script)).toEqual([ + {module: 'jsi', from: '../ReactCommon/jsi/', prefix: ''}, + {module: 'reactnative', from: '../ReactCommon/react/', prefix: 'react/'}, + { + module: 'reactnative', + from: '../ReactCommon/react/renderer/view/platform/android/', + prefix: '', + }, + { + module: 'reactnative', + from: '../ReactCommon/jsi/jsi/jsi.h', + prefix: 'react/fabric/', + }, + {module: 'reactnative', from: 'src/main/jni/react/missing', prefix: ''}, + ]); + }); + + test('rejects a rule it cannot read', () => { + expect(() => + prefabHeaderRules( + 'PrefabPreprocessingEntry("jsi", Pair(jsiHeaders, ""))', + ), + ).toThrow(/Pair\(jsiHeaders, ""\)/); + }); + + test('rejects a script without prefab rules', () => { + expect(() => prefabHeaderRules('android {}')).toThrow(/prefab/); + }); +}); + +describe('source layouts', () => { + let outDir = ''; + + beforeEach(() => { + outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'abi-check-source-')); + }); + + afterEach(() => { + fs.rmSync(outDir, {recursive: true}); + }); + + test('lays out Android headers as the prefab modules do', () => { + const mavenModules = path.join(LAYOUTS_DIR, 'maven-android/prefab/modules'); + + const layout = androidSourceLayout(PACKAGE_DIR, outDir); + + expect(layout.includeDirs).toEqual( + ['jsi', 'reactnative'].map(module => path.join(outDir, module)), + ); + expect([...layout.headers.keys()].sort()).toEqual( + [ + ...filesUnder(path.join(mavenModules, 'jsi/include')), + ...filesUnder(path.join(mavenModules, 'reactnative/include')), + ].sort(), + ); + expect(filesUnder(path.join(outDir, 'reactnative'))).toEqual( + filesUnder(path.join(mavenModules, 'reactnative/include')), + ); + expect( + fs.readFileSync( + layout.headers.get('react/renderer/view/HostProps.h') ?? '', + 'utf8', + ), + ).toBe( + fs.readFileSync( + path.join( + PACKAGE_DIR, + 'ReactCommon/react/renderer/view/platform/android/react/renderer/view/HostProps.h', + ), + 'utf8', + ), + ); + }); + + test('lays out iOS headers as the headers spec places them', () => { + const headers = + 'maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers'; + const entries = [ + ...filesUnder(path.join(LAYOUTS_DIR, headers)).map(relPath => ({ + relPath, + naturalPath: relPath, + source: path.join( + 'ReactCommon', + relPath === 'react/renderer/view/HostProps.h' + ? 'react/renderer/view/platform/ios/react/renderer/view/HostProps.h' + : relPath, + ), + })), + { + relPath: 'CoreModules/RCTRedirected.h', + naturalPath: 'CoreModules/RCTRedirected.h', + source: 'React/CoreModules/RCTRedirected.h', + redirectTo: 'React/RCTRedirected.h', + }, + ]; + + const react = [ + { + relPath: 'RCTDefines.h', + naturalPath: 'React/RCTDefines.h', + source: 'ReactCommon/jsi/jsi/jsi.h', + }, + ]; + + const layout = iosSourceLayout(PACKAGE_DIR, outDir, { + reactNativeHeaders: entries, + react, + }); + + expect(layout.includeDirs).toEqual([path.join(outDir, 'Headers')]); + expect(layout.frameworkDirs).toEqual([path.join(outDir, 'Frameworks')]); + expect(layout.headers.get('React/RCTDefines.h')).toBe( + path.join(outDir, 'Frameworks/React.framework/Headers/RCTDefines.h'), + ); + expect([...layout.headers.keys()].sort()).toEqual([ + 'CoreModules/RCTRedirected.h', + 'React/RCTDefines.h', + ...filesUnder(path.join(LAYOUTS_DIR, headers)), + ]); + expect(filesUnder(layout.includeDirs[0])).toEqual( + [...layout.headers.keys()] + .filter(header => !header.startsWith('React/')) + .sort(), + ); + expect( + fs.readFileSync( + layout.headers.get('CoreModules/RCTRedirected.h') ?? '', + 'utf8', + ), + ).toContain('#import '); + }); +}); diff --git a/scripts/abi-check/__tests__/tiers-test.js b/scripts/abi-check/__tests__/tiers-test.js new file mode 100644 index 000000000000..19d53b58efc8 --- /dev/null +++ b/scripts/abi-check/__tests__/tiers-test.js @@ -0,0 +1,201 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +'use strict'; + +const { + collectStableApiHeaders, + excludePatterns, + stableApiHeaders, +} = require('../tiers'); +const fs = require('node:fs'); +const path = require('node:path'); + +const CXX_API_DIR = path.join(__dirname, '..', '..', 'cxx-api'); +const LAYOUTS_DIR = path.join(__dirname, '__fixtures__', 'layouts'); +const SOURCE_REACT_COMMON = path.join( + LAYOUTS_DIR, + 'source', + 'packages', + 'react-native', + 'ReactCommon', +); +// Under scripts/, which the iOS list excludes when it is part of the path +// below the header root. +const headerRoot = path.join(__dirname, '__fixtures__', 'tiers'); + +function inRoot(headers: Array): Array { + return headers.map(header => path.join(headerRoot, header)); +} + +function quotedListItems(text: string): Array { + return [...text.matchAll(/'([^']*)'|"([^"]*)"/g)].map( + ([, single, double]) => single ?? double, + ); +} + +/** The exclude_patterns list that follows `heading` in config.yml. */ +function configExcludePatterns(heading: string): Array { + const config = fs.readFileSync(path.join(CXX_API_DIR, 'config.yml'), 'utf8'); + const section = config.slice(config.indexOf(heading)); + const list = section.match(/^( *)exclude_patterns:\n((?:\1 +- .*\n)+)/m); + return quotedListItems(list?.[2] ?? ''); +} + +describe('collectStableApiHeaders', () => { + test('returns the public and for-frameworks headers for iOS, sorted', () => { + expect(collectStableApiHeaders(headerRoot, 'ios')).toEqual( + inRoot([ + 'react/ForFrameworks.h', + 'react/Public.h', + 'react/nested/Indented.h', + 'react/platform/ios/Dup.h', + ]), + ); + }); + + test('returns the public and for-frameworks headers for Android, sorted', () => { + expect(collectStableApiHeaders(headerRoot, 'android')).toEqual( + inRoot([ + 'react/ForFrameworks.h', + 'react/Public.h', + 'react/Thing+Private.h', + 'react/jni/Jni.h', + 'react/nested/Indented.h', + 'react/platform/android/Dup.h', + 'react/scripts/InScripts.h', + ]), + ); + }); + + test('accepts a relative header root and returns absolute paths', () => { + const relativeRoot = path.relative(process.cwd(), headerRoot); + + expect(collectStableApiHeaders(relativeRoot, 'ios')).toEqual( + collectStableApiHeaders(headerRoot, 'ios'), + ); + }); +}); + +describe('excludePatterns', () => { + const main = fs.readFileSync( + path.join(CXX_API_DIR, 'parser', '__main__.py'), + 'utf8', + ); + const templatePatterns = quotedListItems( + main.match(/^_TEMPLATE_EXCLUDE_PATTERNS = \[(.*)\]$/m)?.[1] ?? '', + ); + const globalPatterns = configExcludePatterns('exclude_patterns:'); + + test.each([ + ['ios', 'ReactApple'], + ['android', 'ReactAndroid'], + ])('matches the cxx-api %s view, %s', (platform, view) => { + const expected = [ + ...templatePatterns, + ...globalPatterns, + ...configExcludePatterns(`\n ${view}:\n`), + ]; + + expect(templatePatterns).not.toEqual([]); + expect(globalPatterns).not.toEqual([]); + expect(excludePatterns(platform === 'ios' ? 'ios' : 'android')).toEqual([ + ...new Set(expected), + ]); + }); +}); + +/** Each header under `dir`, by `prefix` and its path below `dir`. */ +function headersUnder(dir: string, prefix: string = ''): Map { + return new Map( + fs + .readdirSync(dir, {recursive: true, encoding: 'utf8'}) + .filter(entry => entry.endsWith('.h')) + .map(entry => [ + prefix + entry.split(path.sep).join('/'), + path.join(dir, entry), + ]), + ); +} + +describe('stableApiHeaders', () => { + const sourceHeaders = (platform: string) => + // The prefab and pod rules: ReactCommon/react/ as react/, and the + // platform's folder at the include root. + new Map([ + ...headersUnder(path.join(SOURCE_REACT_COMMON, 'react'), 'react/'), + ...headersUnder( + path.join( + SOURCE_REACT_COMMON, + 'react/renderer/view/platform', + platform, + ), + ), + ]); + + const fetcher = + 'react/renderer/image/platform/android/react/renderer/image/ImageFetcher.h'; + + test.each([ + [ + 'android', + 'maven-android/prefab/modules/reactnative/include', + [ + 'react/renderer/core/Props.h', + fetcher, + 'react/renderer/view/HostProps.h', + ], + ], + [ + 'ios', + 'maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers', + ['react/renderer/core/Props.h', 'react/renderer/view/HostProps.h'], + ], + ])( + 'selects the same %s include paths from the source tree and from Maven', + (platform, mavenRoot, expected) => { + const os = platform === 'ios' ? 'ios' : 'android'; + + expect(stableApiHeaders(sourceHeaders(os), os)).toEqual(expected); + expect( + stableApiHeaders(headersUnder(path.join(LAYOUTS_DIR, mavenRoot)), os), + ).toEqual(expected); + }, + ); + + test('keeps a header that is only in a platform folder', () => { + const headers = headersUnder( + path.join(SOURCE_REACT_COMMON, 'react'), + 'react/', + ); + + expect(stableApiHeaders(headers, 'android')).toContain(fetcher); + }); + + test('drops the platform folder copy of a header at the include root', () => { + const copy = + 'react/renderer/view/platform/android/react/renderer/view/HostProps.h'; + const headers = sourceHeaders('android'); + + expect(headers.has(copy)).toBe(true); + expect(headers.has('react/renderer/view/HostProps.h')).toBe(true); + expect(stableApiHeaders(headers, 'android')).not.toContain(copy); + }); + + test('excludes a source-tree pattern below a ReactCommon header root', () => { + expect(collectStableApiHeaders(SOURCE_REACT_COMMON, 'android')).toEqual( + [ + 'react/renderer/core/Props.h', + 'react/renderer/image/platform/android/react/renderer/image/ImageFetcher.h', + 'react/renderer/view/platform/android/react/renderer/view/HostProps.h', + ].map(header => path.join(SOURCE_REACT_COMMON, header)), + ); + }); +}); diff --git a/scripts/abi-check/args.js b/scripts/abi-check/args.js new file mode 100644 index 000000000000..cf18a60a4625 --- /dev/null +++ b/scripts/abi-check/args.js @@ -0,0 +1,111 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +import type {CheckOptions, Side} from './check'; + +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const {parseArgs} = require('node:util'); + +export type CliCommand = + {kind: 'help'} | {kind: 'check', options: CheckOptions, json: boolean}; + +const VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/; + +const USAGE = ` + Usage: node scripts/abi-check/cli.js --platform ios|android + --build-type debug|release --base + --current | + [--cache-dir ] [--json] + + Compares the C++ ABI of React Native's stable API headers in a published + version with another published version or a checkout of this repository. + Prints the types whose layout, vtable or enumerator values changed or that + were removed. + + Options: + --platform ios or android. + --build-type debug or release. + --base The published version to compare with, such as 0.88.0. + --current The root folder of a checkout, if the folder exists, or + else a published version. + --cache-dir Where downloaded artifacts are kept. Defaults to + react-native-abi-check in the temporary folder. + --json Prints the result as JSON. + + Exit status: + 0 No ABI breaks. + 1 ABI breaks. + 2 Bad arguments, or a tool error such as a failed download or a header + that does not compile. +`; + +function parseSide(current: string): Side { + const root = path.resolve(current); + if (fs.existsSync(root) && fs.statSync(root).isDirectory()) { + return {kind: 'checkout', root}; + } + if (VERSION.test(current)) { + return {kind: 'version', version: current}; + } + throw new Error( + `--current must be a published version or a checkout folder: ${current}`, + ); +} + +function parseCliArgs(argv: ReadonlyArray): CliCommand { + const {values} = parseArgs({ + args: [...argv], + options: { + platform: {type: 'string'}, + 'build-type': {type: 'string'}, + base: {type: 'string'}, + current: {type: 'string'}, + 'cache-dir': {type: 'string'}, + json: {type: 'boolean'}, + help: {type: 'boolean'}, + }, + }); + if (values.help === true) { + return {kind: 'help'}; + } + + const {platform, 'build-type': buildType, base, current} = values; + if (platform !== 'ios' && platform !== 'android') { + throw new Error('--platform must be ios or android.'); + } + if (buildType !== 'debug' && buildType !== 'release') { + throw new Error('--build-type must be debug or release.'); + } + if (base == null || !VERSION.test(base)) { + throw new Error('--base must be a published version, such as 0.88.0.'); + } + if (current == null) { + throw new Error( + '--current must be a published version or the root of a checkout.', + ); + } + return { + kind: 'check', + json: values.json === true, + options: { + platform, + buildType, + base, + current: parseSide(current), + cacheDir: path.resolve( + values['cache-dir'] ?? path.join(os.tmpdir(), 'react-native-abi-check'), + ), + }, + }; +} + +module.exports = {USAGE, parseCliArgs}; diff --git a/scripts/abi-check/artifacts.js b/scripts/abi-check/artifacts.js new file mode 100644 index 000000000000..1c7551f04306 --- /dev/null +++ b/scripts/abi-check/artifacts.js @@ -0,0 +1,291 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +import type {BuildType, Platform} from './dump'; +import type {HeaderLayout} from './layout'; + +const { + download: downloadWithRetries, +} = require('../../packages/react-native/scripts/spm/download-spm-artifacts'); +const {layoutFromEntries, mergeLayouts} = require('./layout'); +const {execFileSync} = require('node:child_process'); +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const path = require('node:path'); + +export type Download = (url: string, destination: string) => Promise; + +function downloadArtifact(url: string, destination: string): Promise { + // Without a progress callback, it writes its progress to stdout, which the + // CLI keeps for the result. + return downloadWithRetries( + url, + destination, + (name, bytes, total, speed, done) => { + if (done) { + console.error(`Downloaded ${name}`); + } + }, + ); +} + +export type PublishedVersion = { + version: string, + platform: Platform, + buildType: BuildType, + /** Where downloaded archives and their extracted headers are kept. */ + cacheDir: string, +}; + +const MAVEN_REPOSITORY = 'https://repo1.maven.org/maven2'; + +const XCFRAMEWORK_HEADERS = + /^(?:.*\/)?[^/]+\.xcframework\/ios-arm64\/Headers\//; +const XCFRAMEWORK_FRAMEWORK = + /^((?:.*\/)?[^/]+\.xcframework\/ios-arm64)\/([^/]+)\.framework\/Headers\/(.+)$/; +const PREFAB_HEADERS = /^prefab\/modules\/[^/]+\/include\//; + +function mavenUrl( + group: string, + artifact: string, + version: string, + suffix: string, +): string { + return ( + `${MAVEN_REPOSITORY}/${group.replaceAll('.', '/')}/${artifact}/` + + `${version}/${artifact}-${version}${suffix}` + ); +} + +/** + * The archives that ship the React Native headers of `version`. On iOS: the + * core, with the ReactNativeHeaders xcframework and React.framework, whose + * headers some ReactNativeHeaders include, and the + * ReactNativeDependenciesHeaders xcframework. On Android: the react-android + * AAR, whose prefab modules hold the headers. + */ +function publishedArtifactUrls( + version: string, + platform: Platform, + buildType: BuildType, +): Array { + if (platform === 'ios') { + return ['reactnative-core', 'reactnative-dependencies-headers'].map(name => + mavenUrl( + 'com.facebook.react', + 'react-native-artifacts', + version, + `-${name}-${buildType}.tar.gz`, + ), + ); + } + return [ + mavenUrl( + 'com.facebook.react', + 'react-android', + version, + `-${buildType}.aar`, + ), + ]; +} + +function fbjniVersionFromPom(pom: string): string { + const version = pom.match( + /fbjni<\/artifactId>\s*([^<]+)<\/version>/, + )?.[1]; + if (version == null) { + throw new Error('The react-android POM has no fbjni dependency.'); + } + return version.trim(); +} + +function fbjniVersionFromCatalog(catalog: string): string { + const version = catalog.match(/^fbjni\s*=\s*"([^"]+)"/m)?.[1]; + if (version == null) { + throw new Error('The Gradle version catalog has no fbjni version.'); + } + return version; +} + +async function fetchCached( + url: string, + cacheDir: string, + download: Download, +): Promise { + const archive = path.join(cacheDir, path.basename(url)); + if (fs.existsSync(archive)) { + return archive; + } + fs.mkdirSync(cacheDir, {recursive: true}); + // The archive gets its cache name only when its SHA-1 matches the one that + // Maven lists, so that the cache holds only verified archives. + const unverified = `${archive}.unverified`; + const checksumFile = `${archive}.sha1`; + try { + await download(url, unverified); + await download(`${url}.sha1`, checksumFile); + const expected = fs + .readFileSync(checksumFile, 'utf8') + .trim() + .split(/\s+/)[0] + .toLowerCase(); + const hash = crypto.createHash('sha1'); + for await (const chunk of fs.createReadStream(unverified)) { + hash.update(chunk); + } + const actual = hash.digest('hex'); + if (actual !== expected) { + throw new Error( + `The SHA-1 of ${url} is ${actual}, but Maven lists ${expected}. ` + + 'The download was deleted.', + ); + } + fs.renameSync(unverified, archive); + } finally { + fs.rmSync(unverified, {force: true}); + fs.rmSync(checksumFile, {force: true}); + } + return archive; +} + +function listFiles(command: string, args: Array): Array { + return execFileSync(command, args, { + encoding: 'utf8', + maxBuffer: 64 * 1024 * 1024, + }) + .split('\n') + .map(entry => entry.replace(/^\.\//, '')) + .filter(entry => entry !== '' && !entry.endsWith('/')); +} + +/** Throws if an entry of `archive` is absolute or goes up with `..`. */ +function checkArchiveEntries( + archive: string, + entries: ReadonlyArray, +): void { + const unsafe = entries.find( + entry => entry.startsWith('/') || entry.split('/').includes('..'), + ); + if (unsafe != null) { + throw new Error(`${archive} has a path outside its folder: ${unsafe}`); + } +} + +/** Extracts the headers of `archive` to `dir` and returns their paths. */ +function extractHeaders(archive: string, dir: string): Array { + if (archive.endsWith('.aar')) { + // The AAR also holds the native libraries, hundreds of megabytes. + const headers = 'prefab/modules/*/include/*'; + const entries = listFiles('unzip', ['-Z1', archive, headers]); + checkArchiveEntries(archive, entries); + execFileSync('unzip', ['-q', '-o', archive, headers, '-d', dir]); + return entries; + } + const entries = listFiles('tar', ['-tzf', archive]); + checkArchiveEntries(archive, entries); + execFileSync('tar', ['-xzf', archive, '-C', dir]); + return entries; +} + +/** + * The layout of the headers in `archive`, extracted next to it once. The + * archive's own paths are the include paths, so their case is kept on a + * case-insensitive file system. A framework's headers are included as + * `` through the `-F` directories. + */ +function archiveLayout(archive: string, headerRoot: RegExp): HeaderLayout { + const dir = `${archive}-headers`; + // Written last, so that an interrupted extraction is done again. + const entriesFile = path.join(dir, '.entries.json'); + if (!fs.existsSync(entriesFile)) { + fs.rmSync(dir, {recursive: true, force: true}); + fs.mkdirSync(dir, {recursive: true}); + fs.writeFileSync(entriesFile, JSON.stringify(extractHeaders(archive, dir))); + } + const entries: Array = JSON.parse( + fs.readFileSync(entriesFile, 'utf8'), + ); + const frameworkSlices: Set = new Set(); + const frameworkHeaders: Map = new Map(); + for (const entry of entries) { + const match = entry.match(XCFRAMEWORK_FRAMEWORK); + if (match != null && entry.endsWith('.h')) { + const [, slice, framework, header] = match; + frameworkSlices.add(slice); + frameworkHeaders.set(`${framework}/${header}`, path.join(dir, entry)); + } + } + return mergeLayouts([ + layoutFromEntries(dir, entries, headerRoot), + { + includeDirs: [], + frameworkDirs: [...frameworkSlices] + .sort() + .map(slice => path.join(dir, slice)), + headers: frameworkHeaders, + }, + ]); +} + +/** The headers of the fbjni AAR, which ReactAndroid's JNI headers include. */ +async function fbjniLayout( + version: string, + cacheDir: string, + download: Download = downloadArtifact, +): Promise { + const url = mavenUrl('com.facebook.fbjni', 'fbjni', version, '.aar'); + return archiveLayout( + await fetchCached(url, cacheDir, download), + PREFAB_HEADERS, + ); +} + +/** + * The headers that React Native `version` published on Maven for `platform` + * and `buildType`, downloaded to the cache unless they are there. On Android + * they include the headers of the fbjni version that react-android uses. + */ +async function publishedLayout( + {version, platform, buildType, cacheDir}: PublishedVersion, + download: Download = downloadArtifact, +): Promise { + const archives = await Promise.all( + publishedArtifactUrls(version, platform, buildType).map(url => + fetchCached(url, cacheDir, download), + ), + ); + if (platform === 'ios') { + return mergeLayouts( + archives.map(archive => archiveLayout(archive, XCFRAMEWORK_HEADERS)), + ); + } + const pom = await fetchCached( + mavenUrl('com.facebook.react', 'react-android', version, '.pom'), + cacheDir, + download, + ); + return mergeLayouts([ + ...archives.map(archive => archiveLayout(archive, PREFAB_HEADERS)), + await fbjniLayout( + fbjniVersionFromPom(fs.readFileSync(pom, 'utf8')), + cacheDir, + download, + ), + ]); +} + +module.exports = { + checkArchiveEntries, + fbjniLayout, + fbjniVersionFromCatalog, + fbjniVersionFromPom, + publishedArtifactUrls, + publishedLayout, +}; diff --git a/scripts/abi-check/ast.js b/scripts/abi-check/ast.js new file mode 100644 index 000000000000..14573e73cbce --- /dev/null +++ b/scripts/abi-check/ast.js @@ -0,0 +1,343 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +import type {LayoutMap} from './normalize'; + +/** Reads one line of clang's text AST dump at a time. */ +export type AstCollector = { + onLine: (line: string) => void, + finish: () => T, +}; + +export type Method = { + name: string, + /** The function type as written, for example `void (int) const`. */ + type: string, + virtual: boolean, + deleted: boolean, +}; + +export type ClassMembers = { + /** The namespace that encloses the class, for example `facebook::react`. */ + namespace: string, + /** Methods declared in the class, without constructors and destructors. */ + methods: Array, + /** Names that using-declarations bring into the class. */ + usingNames: Array, + hasVirtualDestructor: boolean, + hasDeletedDestructor: boolean, +}; + +const NODE = /^([\s|`-]*)(\S+)(.*)$/; +const SOURCE_LOCATION = / at [^()]*?:\d+:\d+\)/; + +function parseNode(line: string): {depth: number, kind: string, rest: string} { + const [, prefix = '', kind = '', rest = ''] = line.match(NODE) ?? []; + return {depth: prefix.length, kind, rest}; +} + +const ENUM_CONSTANT = / (\w+) '([^']+)'(?::'[^']*')?$/; +const CONSTANT_VALUE = /^ Int (-?\d+)$/; + +type Enumerator = { + name: string, + depth: number, + value: ?bigint, + // The next line of the initializer's ImplicitCastExpr -> ConstantExpr -> + // value chain, which only constant initializers have. + expected: ?{depth: number, node: 'expression' | 'value'}, +}; + +type EnumBlock = { + name: ?string, + underlyingType: ?string, + enumerators: Array, + dependent: boolean, +}; + +function formatEnum({underlyingType, enumerators}: EnumBlock): string { + const lines = underlyingType != null ? [`: ${underlyingType}`] : []; + let nextValue = BigInt(0); + for (const enumerator of enumerators) { + const value = enumerator.value ?? nextValue; + lines.push(`${enumerator.name} = ${value.toString()}`); + nextValue = value + BigInt(1); + } + return lines.join('\n'); +} + +/** + * Collects `E ` entries with the enumerator values of each enum whose + * name matches `namespacePattern`. An enumerator without an initializer is one + * more than the previous one. Enums whose values depend on a template + * parameter, and unnamed enums, are left out. + */ +function createEnumCollector( + namespacePattern: RegExp, +): AstCollector { + const enums: LayoutMap = new Map(); + let block: ?EnumBlock = null; + + const finishBlock = () => { + const finished = block; + block = null; + const name = finished?.name; + if ( + finished != null && + name != null && + !finished.dependent && + !SOURCE_LOCATION.test(name) && + name.search(namespacePattern) !== -1 && + !enums.has(`E ${name}`) + ) { + enums.set(`E ${name}`, formatEnum(finished)); + } + }; + + const onLine = (line: string) => { + const {depth, kind, rest} = parseNode(line); + if (kind === 'EnumDecl') { + finishBlock(); + block = { + name: null, + underlyingType: rest.match(/'([^']+)'/)?.[1], + enumerators: [], + dependent: false, + }; + return; + } + const current = block; + if (current == null) { + return; + } + + const constant = + kind === 'EnumConstantDecl' ? rest.match(ENUM_CONSTANT) : null; + if (constant != null) { + if (current.name == null) { + current.name = constant[2]; + } + current.enumerators.push({ + name: constant[1], + depth, + value: null, + expected: {depth: depth + 2, node: 'expression'}, + }); + return; + } + + const enumerator = current.enumerators[current.enumerators.length - 1]; + const expected = enumerator?.expected; + if (enumerator == null || expected == null) { + return; + } + if (depth <= enumerator.depth) { + enumerator.expected = null; + return; + } + if (depth !== expected.depth) { + return; + } + if (expected.node === 'value') { + const value = kind === 'value:' ? rest.match(CONSTANT_VALUE)?.[1] : null; + if (value != null) { + enumerator.value = BigInt(value); + } else { + current.dependent = true; + } + enumerator.expected = null; + return; + } + // An initializer comes before the attributes and doc comment. + if (kind === 'ImplicitCastExpr') { + enumerator.expected = {depth: depth + 2, node: 'expression'}; + } else if (kind === 'ConstantExpr') { + enumerator.expected = {depth: depth + 2, node: 'value'}; + } else if (!kind.endsWith('Attr') && !kind.endsWith('Comment')) { + current.dependent = true; + enumerator.expected = null; + } + }; + + return { + onLine, + finish: () => { + finishBlock(); + return enums; + }, + }; +} + +const NAMESPACE_NAME = /(?:col|line):[\d:]+ (\w+)(?: inline| nested)*$/; +const RECORD_DEFINITION = / (?:class|struct|union) (\w+) definition\b/; +const METHOD = + /^ 0x\w+ (?:prev 0x\w+ )?(?:parent 0x\w+ )?<.*?> (?:col|line):[\d:]+ (?:(?:used|referenced|implicit|invalid|constexpr|consteval) )*(.+?) '([^']*)'(?::'[^']*')?(.*)$/; +const MEMBER_NAME = /^(?:~?[A-Za-z_]\w*|operator\b.+)$/; + +type Scope = { + depth: number, + /** Null inside functions, templates and unnamed records. */ + qualifiedName: ?string, + namespace: ?string, + members: ?ClassMembers, +}; + +type PendingMethod = { + depth: number, + members: ClassMembers, + method: Method, + destructor: boolean, +}; + +function qualify(scope: ?string, name: ?string): ?string { + if (scope == null || name == null) { + return null; + } + return scope === '' ? name : `${scope}::${name}`; +} + +/** + * Collects the methods of each class whose qualified name matches + * `namespacePattern`. Classes inside functions and templates are left out. + */ +function createClassCollector( + namespacePattern: RegExp, +): AstCollector> { + const classes: Map = new Map(); + const scopes: Array = [ + {depth: -1, qualifiedName: '', namespace: '', members: null}, + ]; + let pending: ?PendingMethod = null; + + const finishMethod = () => { + const finished = pending; + pending = null; + if (finished == null) { + return; + } + const {members, method} = finished; + if (!finished.destructor) { + members.methods.push(method); + } else if (method.deleted) { + members.hasDeletedDestructor = true; + } else if (method.virtual) { + members.hasVirtualDestructor = true; + } + }; + + const onLine = (line: string) => { + const {depth, kind, rest} = parseNode(line); + if (pending != null) { + if (depth <= pending.depth) { + finishMethod(); + } else if ( + kind === 'Overrides:' || + kind === 'OverrideAttr' || + kind === 'FinalAttr' + ) { + pending.method.virtual = true; + } + } + if (kind === 'TranslationUnitDecl' || kind === 'LinkageSpecDecl') { + return; + } + + while (scopes[scopes.length - 1].depth >= depth) { + scopes.pop(); + } + const scope = scopes[scopes.length - 1]; + const opaque: Scope = { + depth, + qualifiedName: null, + namespace: null, + members: null, + }; + + if (kind === 'NamespaceDecl') { + const name = rest.match(NAMESPACE_NAME)?.[1] ?? '(anonymous namespace)'; + const qualifiedName = qualify(scope.qualifiedName, name); + scopes.push({ + depth, + qualifiedName, + namespace: qualifiedName, + members: null, + }); + return; + } + + const record = + kind === 'CXXRecordDecl' ? rest.match(RECORD_DEFINITION) : null; + if (record != null) { + const qualifiedName = qualify(scope.qualifiedName, record[1]); + const {namespace} = scope; + let members: ?ClassMembers = null; + if ( + qualifiedName != null && + namespace != null && + qualifiedName.search(namespacePattern) !== -1 && + !classes.has(qualifiedName) + ) { + members = { + namespace, + methods: [], + usingNames: [], + hasVirtualDestructor: false, + hasDeletedDestructor: false, + }; + classes.set(qualifiedName, members); + } + scopes.push({depth, qualifiedName, namespace, members}); + return; + } + + scopes.push(opaque); + const members = scope.members; + if (members == null) { + return; + } + if (kind === 'UsingDecl') { + members.usingNames.push(rest.slice(rest.lastIndexOf('::') + 2)); + return; + } + const isDestructor = kind === 'CXXDestructorDecl'; + if ( + !isDestructor && + kind !== 'CXXMethodDecl' && + kind !== 'CXXConversionDecl' + ) { + return; + } + const [, name, type, flags] = rest.match(METHOD) ?? []; + if (name == null || !MEMBER_NAME.test(name)) { + return; + } + pending = { + depth, + members, + destructor: isDestructor, + method: { + name, + type, + virtual: /\bvirtual\b/.test(flags), + deleted: /\bdelete\b/.test(flags), + }, + }; + }; + + return { + onLine, + finish: () => { + finishMethod(); + return classes; + }, + }; +} + +module.exports = {createClassCollector, createEnumCollector}; diff --git a/scripts/abi-check/check.js b/scripts/abi-check/check.js new file mode 100644 index 000000000000..9bb5186875e1 --- /dev/null +++ b/scripts/abi-check/check.js @@ -0,0 +1,277 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +import type {BuildType, Platform} from './dump'; +import type {AbiReport} from './index'; +import type {HeaderLayout} from './layout'; +import type {SkippedHeader} from './skipped-headers'; + +const { + fbjniLayout, + fbjniVersionFromCatalog, + publishedLayout, +} = require('./artifacts'); +const {dumpHeaders} = require('./dump'); +const {abiReport} = require('./index'); +const {mergeLayouts} = require('./layout'); +const {SKIPPED_HEADERS} = require('./skipped-headers'); +const {androidSourceLayout, iosSourceLayout} = require('./source'); +const {stableApiHeaders} = require('./tiers'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +export type Side = + {kind: 'version', version: string} | {kind: 'checkout', root: string}; + +export type CheckOptions = { + platform: Platform, + buildType: BuildType, + /** The published version to compare against. */ + base: string, + current: Side, + /** Where downloaded artifacts and their extracted headers are kept. */ + cacheDir: string, +}; + +export type CheckResult = { + ...AbiReport, + /** The number of headers each side was dumped with. */ + headerCounts: {base: number, current: number}, + /** The number of layouts, vtables and enums each side dumped. */ + keyCounts: {base: number, current: number}, + /** The stable API headers left out by the skip list. */ + skippedHeaders: Array, +}; + +/** The clang settings of a dump, other than its headers and search paths. */ +export type DumpSettings = { + platform?: Platform, + buildType?: BuildType, + clang?: string, + sysroot?: string, +}; + +const NAMESPACE_PATTERN: RegExp = /^facebook::(?:react|yoga|jsi)::/; + +/** + * The stable API headers of either layout, each side with those it has. A + * header that only one side declares stable is still dumped on both, so + * that a change of tier alone does not report its types as removed or added. + */ +function headersToCompare( + base: HeaderLayout, + current: HeaderLayout, + platform: Platform, +): {base: Array, current: Array} { + const union = new Set([ + ...stableApiHeaders(base.headers, platform), + ...stableApiHeaders(current.headers, platform), + ]); + const withHeadersOf = (layout: HeaderLayout) => + [...union].filter(header => layout.headers.has(header)).sort(); + return {base: withHeadersOf(base), current: withHeadersOf(current)}; +} + +async function currentLayout( + {current, platform, buildType, cacheDir}: CheckOptions, + base: HeaderLayout, + outDir: string, +): Promise { + if (current.kind === 'version') { + return publishedLayout({ + version: current.version, + platform, + buildType, + cacheDir, + }); + } + const packageDir = path.join(current.root, 'packages', 'react-native'); + const source = + platform === 'ios' + ? // The headers spec comes from this repository's prebuild scripts, + // whatever the checkout's version: another version is laid out by + // today's rules, which can differ from those that built its artifacts. + iosSourceLayout(packageDir, outDir) + : mergeLayouts([ + androidSourceLayout(packageDir, outDir), + await fbjniLayout( + fbjniVersionFromCatalog( + fs.readFileSync( + path.join(packageDir, 'gradle', 'libs.versions.toml'), + 'utf8', + ), + ), + cacheDir, + ), + ]); + // The source tree has no third-party, codegen or Hermes headers. Clang + // finds them in the base artifacts, after the headers of the source tree. + return { + includeDirs: [...source.includeDirs, ...base.includeDirs], + frameworkDirs: [...source.frameworkDirs, ...base.frameworkDirs], + headers: source.headers, + }; +} + +/** + * The NDK's clang and sysroot: from ANDROID_NDK_HOME, else the newest NDK + * of the Android SDK. + */ +function androidToolchain(): {clang: string, sysroot: string} { + const sdk = + process.env.ANDROID_HOME ?? + process.env.ANDROID_SDK_ROOT ?? + path.join(os.homedir(), 'Library', 'Android', 'sdk'); + const ndks = path.join(sdk, 'ndk'); + const newestNdk = fs.existsSync(ndks) + ? fs + .readdirSync(ndks) + .sort((a, b) => a.localeCompare(b, undefined, {numeric: true})) + .at(-1) + : null; + const ndk = + process.env.ANDROID_NDK_HOME ?? + (newestNdk != null ? path.join(ndks, newestNdk) : null); + if (ndk == null) { + throw new Error( + `Android needs the NDK. Set ANDROID_NDK_HOME, or install an NDK in ${ndks}.`, + ); + } + const host = process.platform === 'darwin' ? 'darwin' : 'linux'; + const toolchain = path.join( + ndk, + 'toolchains', + 'llvm', + 'prebuilt', + `${host}-x86_64`, + ); + return { + clang: path.join(toolchain, 'bin', 'clang++'), + sysroot: path.join(toolchain, 'sysroot'), + }; +} + +/** + * The headers that `entries` skip for `platform` when comparing `versions`, + * the base and the current version. + */ +function skippedHeadersFor( + entries: ReadonlyArray, + platform: Platform, + versions: ReadonlyArray, +): Set { + return new Set( + entries + .filter( + entry => + entry.platform === platform && + (entry.versions == null || + entry.versions.some(version => versions.includes(version))), + ) + .map(entry => entry.header), + ); +} + +/** The published version, or the version of a checkout's package.json. */ +function sideVersion(side: Side): string { + if (side.kind === 'version') { + return side.version; + } + const packageJson = path.join( + side.root, + 'packages', + 'react-native', + 'package.json', + ); + return String(JSON.parse(fs.readFileSync(packageJson, 'utf8')).version); +} + +/** + * Dumps the stable API headers of both layouts, without the `skipped` + * headers, and compares them. Rejects with the name of any other header that + * does not compile. + */ +async function compareLayouts( + base: HeaderLayout, + current: HeaderLayout, + platform: Platform, + settings: DumpSettings, + skipped: ReadonlySet, +): Promise { + const headers = headersToCompare(base, current, platform); + const kept = (layoutHeaders: Array) => + layoutHeaders.filter(header => !skipped.has(header)); + const dump = (layout: HeaderLayout, layoutHeaders: Array) => + dumpHeaders({ + ...settings, + headers: layoutHeaders, + includeDirs: layout.includeDirs, + frameworkDirs: layout.frameworkDirs, + namespacePattern: NAMESPACE_PATTERN, + }); + const baseHeaders = kept(headers.base); + const currentHeaders = kept(headers.current); + const [baseLayouts, currentLayouts] = await Promise.all([ + dump(base, baseHeaders), + dump(current, currentHeaders), + ]); + return { + ...abiReport(baseLayouts, currentLayouts), + headerCounts: {base: baseHeaders.length, current: currentHeaders.length}, + keyCounts: {base: baseLayouts.size, current: currentLayouts.size}, + skippedHeaders: [...new Set([...headers.base, ...headers.current])] + .filter(header => skipped.has(header)) + .sort(), + }; +} + +/** + * Compares the C++ ABI of the stable API headers of a published version with + * that of another published version or a checkout. + */ +async function checkAbi(options: CheckOptions): Promise { + const {platform, buildType, cacheDir} = options; + const base = await publishedLayout({ + version: options.base, + platform, + buildType, + cacheDir, + }); + const outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'abi-check-source-')); + try { + const current = await currentLayout(options, base, outDir); + return await compareLayouts( + base, + current, + platform, + { + platform, + buildType, + ...(platform === 'android' ? androidToolchain() : {}), + }, + skippedHeadersFor(SKIPPED_HEADERS, platform, [ + options.base, + sideVersion(options.current), + ]), + ); + } finally { + fs.rmSync(outDir, {recursive: true, force: true}); + } +} + +module.exports = { + NAMESPACE_PATTERN, + checkAbi, + compareLayouts, + headersToCompare, + sideVersion, + skippedHeadersFor, +}; diff --git a/scripts/abi-check/cli.js b/scripts/abi-check/cli.js new file mode 100644 index 000000000000..9c3411c4046d --- /dev/null +++ b/scripts/abi-check/cli.js @@ -0,0 +1,103 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +// This file runs before Babel is registered, so its types are comments. +/*:: import type {CheckOptions, CheckResult} from './check'; */ + +if (require.main === module) { + require('../shared/babelRegister').registerForScript(); +} + +const {USAGE, parseCliArgs} = require('./args'); + +/*:: +export type CliIO = { + checkAbi: (options: CheckOptions) => Promise, + stdout: (text: string) => unknown, + stderr: (text: string) => unknown, +}; +*/ + +function describeResult( + { + breaks, + additions, + headerCounts, + keyCounts, + skippedHeaders, + } /*: CheckResult */, + {platform, buildType, base, current} /*: CheckOptions */, +) /*: string */ { + const currentName = + current.kind === 'version' ? current.version : current.root; + const scope = `the ${platform} ${buildType} stable API, ${base} to ${currentName}`; + return [ + breaks.length === 0 + ? `No ABI breaks in ${scope}.` + : `${breaks.length} ABI breaks in ${scope}:`, + ...breaks.map(({key, change}) => ` ${change.padEnd(8)} ${key}`), + `Added: ${additions.length} layouts, vtables or enums.`, + `Compared ${keyCounts.base} layouts, vtables and enums from ` + + `${headerCounts.base} headers of ${base} with ${keyCounts.current} ` + + `from ${headerCounts.current} headers of ${currentName}.`, + `Skipped ${skippedHeaders.length} headers listed in skipped-headers.js` + + (skippedHeaders.length > 0 ? `: ${skippedHeaders.join(', ')}.` : '.'), + ].join('\n'); +} + +/** + * Runs the CLI with `argv` and returns its exit status: 0 without ABI + * breaks, 1 with breaks, 2 for bad arguments or a tool error. + */ +async function runCli( + argv /*: ReadonlyArray */, + {checkAbi, stdout, stderr} /*: CliIO */, +) /*: Promise */ { + let command; + try { + command = parseCliArgs(argv); + } catch (error) { + stderr(`${error.message}\n${USAGE}\n`); + return 2; + } + if (command.kind === 'help') { + stdout(`${USAGE}\n`); + return 0; + } + + const {options, json} = command; + let result; + try { + result = await checkAbi(options); + } catch (error) { + stderr(`${error.message}\n`); + return 2; + } + stdout( + `${json ? JSON.stringify(result, null, 2) : describeResult(result, options)}\n`, + ); + return result.breaks.length > 0 ? 1 : 0; +} + +module.exports = {runCli}; + +if (require.main === module) { + // The iOS prebuild's header code logs its progress to stdout, which is + // kept for the result. + // $FlowFixMe[cannot-write] + console.log = console.error; + void runCli(process.argv.slice(2), { + checkAbi: require('./check').checkAbi, + stdout: text => process.stdout.write(text), + stderr: text => process.stderr.write(text), + }).then(code => { + process.exitCode = code; + }); +} diff --git a/scripts/abi-check/diff.js b/scripts/abi-check/diff.js new file mode 100644 index 000000000000..48f8bf71c56d --- /dev/null +++ b/scripts/abi-check/diff.js @@ -0,0 +1,41 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +import type {LayoutMap} from './normalize'; + +export type LayoutDiff = { + changed: Array, + removed: Array, + added: Array, +}; + +/** + * Compares two normalized layout maps. Each list holds sorted keys. `changed` + * and `removed` are ABI breaks; `added` is not. + */ +function diffLayouts(base: LayoutMap, current: LayoutMap): LayoutDiff { + const changed = []; + const removed = []; + for (const [key, value] of base) { + if (!current.has(key)) { + removed.push(key); + } else if (current.get(key) !== value) { + changed.push(key); + } + } + const added = [...current.keys()].filter(key => !base.has(key)); + return { + changed: changed.sort(), + removed: removed.sort(), + added: added.sort(), + }; +} + +module.exports = {diffLayouts}; diff --git a/scripts/abi-check/dump.js b/scripts/abi-check/dump.js new file mode 100644 index 000000000000..023f495b8d71 --- /dev/null +++ b/scripts/abi-check/dump.js @@ -0,0 +1,326 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +import type {ClassMembers} from './ast'; +import type {LayoutMap} from './normalize'; + +const {createClassCollector, createEnumCollector} = require('./ast'); +const {normalizeDump} = require('./normalize'); +const {execFileSync, spawn} = require('node:child_process'); +const readline = require('node:readline'); + +export type Platform = 'ios' | 'android'; +export type BuildType = 'debug' | 'release'; + +export type DumpOptions = { + /** + * The headers to include in the translation unit: absolute paths, or + * include paths that clang finds in `includeDirs`. + */ + headers: ReadonlyArray, + includeDirs: ReadonlyArray, + /** The `-F` directories, searched for ``. */ + frameworkDirs?: ReadonlyArray, + /** + * Platform whose compile flags to use. Each platform and build type is a + * separate ABI. Defaults to the host, with no platform flags. + */ + platform?: Platform, + /** Selects the debug or release defines. Defaults to debug. */ + buildType?: BuildType, + /** Clang target triple. Defaults to the platform's target, else the host. */ + target?: string, + /** SDK or NDK sysroot. On iOS, defaults to the iphoneos SDK from xcrun. */ + sysroot?: string, + defines?: ReadonlyArray, + /** Path or name of the clang++ executable. Defaults to `clang++`. */ + clang?: string, + namespacePattern: RegExp, +}; + +type Language = 'c++' | 'objective-c++'; + +type PlatformFlags = { + language: Language, + target: string, + sysrootFlag: string, + defaultSysroot: () => string, + flags: Array, + defines: Array, +}; + +// The flags of React Native's own builds: the prebuilt iOS frameworks, and on +// Android ReactCommon/cmake-utils/react-native-flags.cmake and +// ReactAndroid/cmake-utils/folly-flags.cmake. +const PLATFORMS: {readonly [platform: Platform]: PlatformFlags} = { + ios: { + // Platform headers such as RCTTurboModuleManager.h are Objective-C++. + language: 'objective-c++', + target: 'arm64-apple-ios15.1', + sysrootFlag: '-isysroot', + defaultSysroot: () => + execFileSync('xcrun', ['--sdk', 'iphoneos', '--show-sdk-path'], { + encoding: 'utf8', + }).trim(), + flags: [], + defines: [ + 'FOLLY_NO_CONFIG=1', + 'FOLLY_MOBILE=1', + 'FOLLY_USE_LIBCPP=1', + 'FOLLY_CFG_NO_COROUTINES=1', + 'FOLLY_HAVE_CLOCK_GETTIME=1', + ], + }, + android: { + language: 'c++', + target: 'aarch64-linux-android24', + sysrootFlag: '--sysroot', + defaultSysroot: () => { + throw new Error( + 'Android needs `sysroot`, the NDK sysroot at ' + + '/toolchains/llvm/prebuilt//sysroot. Without it, clang ' + + 'compiles against the host C++ library, whose layouts differ.', + ); + }, + flags: ['-fexceptions', '-frtti'], + defines: [ + 'FOLLY_NO_CONFIG=1', + 'FOLLY_HAVE_CLOCK_GETTIME=1', + 'FOLLY_USE_LIBCPP=1', + 'FOLLY_CFG_NO_COROUTINES=1', + 'FOLLY_MOBILE=1', + 'FOLLY_HAVE_RECVMMSG=1', + 'FOLLY_HAVE_PTHREAD=1', + 'FOLLY_HAVE_XSI_STRERROR_R=1', + 'RN_SERIALIZABLE_STATE', + 'ANDROID=1', + 'HERMES_V1_ENABLED=1', + 'LOG_TAG="ReactNative"', + ], + }, +}; + +const LAYOUT_FLAGS = [ + '-Xclang', + '-fdump-record-layouts-complete', + '-Xclang', + '-fdump-vtable-layouts', +]; + +const POLYMORPHIC_LAYOUT = + /^\s*0 \|\s+\([^()\n]+ vtable pointer\)|\(primary virtual base/m; + +function language(options: DumpOptions): Language { + return options.platform != null + ? PLATFORMS[options.platform].language + : 'c++'; +} + +// Keep in sync with the debug and release variants in +// scripts/cxx-api/config.yml. +const BUILD_TYPE_DEFINES: {readonly [buildType: BuildType]: Array} = { + debug: ['DEBUG=1', 'REACT_NATIVE_DEBUG=1'], + release: ['NDEBUG=1', 'REACT_NATIVE_PRODUCTION=1'], +}; + +/** The clang arguments, other than the dump flags, for `options`. */ +function compileFlags(options: DumpOptions): Array { + const platform = + options.platform != null ? PLATFORMS[options.platform] : null; + const target = options.target ?? platform?.target; + const sysroot = options.sysroot ?? platform?.defaultSysroot(); + const defines = [ + ...(platform?.defines ?? []), + ...BUILD_TYPE_DEFINES[options.buildType ?? 'debug'], + ...(options.defines ?? []), + ]; + + return [ + '-x', + language(options), + '-std=c++20', + ...(target != null ? [`--target=${target}`] : []), + ...(sysroot != null ? [platform?.sysrootFlag ?? '--sysroot', sysroot] : []), + ...(platform?.flags ?? []), + ...options.includeDirs.map(dir => `-I${dir}`), + ...(options.frameworkDirs ?? []).map(dir => `-F${dir}`), + ...defines.map(define => `-D${define}`), + '-Wno-everything', + '-fno-color-diagnostics', + ]; +} + +/** One line of a generated translation unit, and what it is for. */ +type SourceLine = {label: string, code: string}; + +function includeLine(header: string, options: DumpOptions): SourceLine { + // Clang does not unescape `#include "..."`, so a quote cannot be written + // there. An absolute path in `<...>` is found the same way. + if (/[>\n]/.test(header)) { + throw new Error(`Cannot include a header path with ">": ${header}`); + } + // Objective-C headers rely on #import instead of include guards, and a + // header that is both #included and #imported is read twice. + const directive = + language(options) === 'objective-c++' ? '#import' : '#include'; + return {label: header, code: `${directive} <${header}>`}; +} + +const MEMBER_POINTER_ALIAS: SourceLine = { + label: 'the vtable probes', + code: 'template using abi_check_member_pointer = Signature Class::*;', +}; + +/** + * Clang dumps a vtable only when code generation needs its layout, so each + * polymorphic class gets a function that does. Taking the address of a + * virtual method needs no virtual destructor; the cast picks an overload, + * with the type as written, so it goes in the class's namespace. A class that + * declares no virtual method is deleted through its, maybe inherited, virtual + * destructor. + */ +function vtableProbe( + className: string, + members: ?ClassMembers, + index: number, +): ?SourceLine { + const type = `::${className}`; + const probe = `abi_check_vtable_${index}`; + const methods = members?.methods ?? []; + const usingNames = members?.usingNames ?? []; + const isOverloaded = (name: string) => + [...methods.map(method => method.name), ...usingNames].filter( + other => other === name, + ).length > 1; + const virtuals = methods.filter(method => method.virtual && !method.deleted); + const unique = virtuals.find(method => !isOverloaded(method.name)); + + let code; + if (unique != null) { + code = `auto ${probe}() { return &${type}::${unique.name}; }`; + } else if (virtuals.length > 0 && members?.hasVirtualDestructor !== true) { + const [{name, type: signature}] = virtuals; + code = + `auto ${probe}() { return static_cast<::abi_check_member_pointer<` + + `${signature}, ${type}>>(&${type}::${name}); }`; + } else if (members?.hasDeletedDestructor !== true) { + code = `void ${probe}(${type} *p) { delete p; }`; + } else { + return null; + } + const namespace = members?.namespace ?? ''; + return { + label: `the vtable probe for ${className}`, + code: namespace === '' ? code : `namespace ${namespace} { ${code} }`, + }; +} + +/** + * Compiles `lines` from stdin and calls `onLine` for each line of stdout. + * Rejects with the parts of `lines` that clang reported errors in. + */ +function runClang( + clang: string, + args: Array, + lines: Array, + onLine: (line: string) => void, +): Promise { + return new Promise((resolve, reject) => { + const child = spawn(clang, [...args, '-']); + const stderrChunks: Array = []; + child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk)); + readline.createInterface({input: child.stdout}).on('line', onLine); + // Clang can exit before it reads all of stdin; its exit code reports why. + child.stdin.on('error', () => {}); + child.on('error', reject); + child.on('close', code => { + if (code === 0) { + resolve(); + return; + } + const stderr = Buffer.concat(stderrChunks).toString(); + const failed = new Set( + [...stderr.matchAll(/:(\d+):/g)] + .map(([, line]) => lines[Number(line) - 1]?.label) + .filter(Boolean), + ); + const what = + failed.size > 0 ? [...failed].join(', ') : 'the translation unit'; + reject(new Error(`${clang} could not compile ${what}:\n${stderr}`)); + }); + child.stdin.end(lines.map(line => `${line.code}\n`).join('')); + }); +} + +async function dumpLayouts( + clang: string, + args: Array, + lines: Array, +): Promise { + const output: Array = []; + await runClang(clang, args, lines, line => { + output.push(line); + }); + return output.join('\n'); +} + +/** + * Compiles a translation unit that includes `headers` and returns the + * normalized record layouts, vtables and enumerator values of every type + * whose name matches `namespacePattern`. + */ +async function dumpHeaders(options: DumpOptions): Promise { + const clang = options.clang ?? 'clang++'; + const flags = compileFlags(options); + const {namespacePattern} = options; + const includes = options.headers.map(header => includeLine(header, options)); + + const enumCollector = createEnumCollector(namespacePattern); + const classCollector = createClassCollector(namespacePattern); + const [recordDump] = await Promise.all([ + dumpLayouts(clang, [...flags, '-fsyntax-only', ...LAYOUT_FLAGS], includes), + runClang( + clang, + [...flags, '-fsyntax-only', '-Xclang', '-ast-dump'], + includes, + line => { + enumCollector.onLine(line); + classCollector.onLine(line); + }, + ), + ]); + + // Template specializations and unnamed types cannot be spelled from their + // dumped names. Access control is off so that probes may use private methods. + const classes = classCollector.finish(); + const probes = [...normalizeDump(recordDump, {namespacePattern})] + .filter( + ([key, layout]) => + key.startsWith('L ') && + !/[<(]/.test(key) && + POLYMORPHIC_LAYOUT.test(layout), + ) + .flatMap(([key], index) => { + const className = key.slice(2); + return vtableProbe(className, classes.get(className), index) ?? []; + }); + const layoutDump = await dumpLayouts( + clang, + [...flags, '-fno-access-control', '-c', '-o', '/dev/null', ...LAYOUT_FLAGS], + [...includes, MEMBER_POINTER_ALIAS, ...probes], + ); + + return new Map([ + ...normalizeDump(layoutDump, {namespacePattern}), + ...enumCollector.finish(), + ]); +} + +module.exports = {compileFlags, dumpHeaders}; diff --git a/scripts/abi-check/index.js b/scripts/abi-check/index.js new file mode 100644 index 000000000000..7c85c6aeffc7 --- /dev/null +++ b/scripts/abi-check/index.js @@ -0,0 +1,58 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +import type {DumpOptions} from './dump'; +import type {LayoutMap} from './normalize'; + +const {diffLayouts} = require('./diff'); +const {dumpHeaders} = require('./dump'); + +export type AbiBreak = { + key: string, + change: 'changed' | 'removed', +}; + +export type AbiReport = { + breaks: Array, + additions: Array, +}; + +/** + * Reports the types whose layout, vtable or enumerator values changed or + * that were removed. Added types are reported separately because they do not + * break the ABI. + */ +function abiReport( + baseLayouts: LayoutMap, + currentLayouts: LayoutMap, +): AbiReport { + const {changed, removed, added} = diffLayouts(baseLayouts, currentLayouts); + return { + breaks: [ + ...changed.map((key): AbiBreak => ({key, change: 'changed'})), + ...removed.map((key): AbiBreak => ({key, change: 'removed'})), + ], + additions: added, + }; +} + +/** Dumps both header sets and compares them with `abiReport`. */ +async function compareHeaderSets( + base: DumpOptions, + current: DumpOptions, +): Promise { + const [baseLayouts, currentLayouts] = await Promise.all([ + dumpHeaders(base), + dumpHeaders(current), + ]); + return abiReport(baseLayouts, currentLayouts); +} + +module.exports = {abiReport, compareHeaderSets}; diff --git a/scripts/abi-check/layout.js b/scripts/abi-check/layout.js new file mode 100644 index 000000000000..fd79a93d523b --- /dev/null +++ b/scripts/abi-check/layout.js @@ -0,0 +1,81 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +const path = require('node:path'); + +/** + * The headers that one side of a comparison ships, and how clang finds them. + */ +export type HeaderLayout = { + /** The `-I` directories, in search order. */ + readonly includeDirs: ReadonlyArray, + /** The `-F` directories, in search order. */ + readonly frameworkDirs: ReadonlyArray, + /** + * Each header by its include path, the path written in `#include <...>`. + * A header's include path is its identity in every layout. + */ + readonly headers: ReadonlyMap, +}; + +/** + * The layout of the headers in `entries`, the archive paths of the files + * extracted to `dir`. Each distinct match of `headerRoot` at the start of an + * entry is an include directory, in sorted order. The archive paths keep + * their case where a case-insensitive file system merges folders such as + * `React/` and `react/`. + */ +function layoutFromEntries( + dir: string, + entries: ReadonlyArray, + headerRoot: RegExp, +): HeaderLayout { + const roots: Map> = new Map(); + for (const entry of entries) { + const root = entry.match(headerRoot)?.[0]; + if (root != null && entry.endsWith('.h')) { + roots.set(root, [...(roots.get(root) ?? []), entry]); + } + } + return mergeLayouts( + [...roots.keys()].sort().map(root => ({ + includeDirs: [path.join(dir, root)], + frameworkDirs: [], + headers: new Map( + (roots.get(root) ?? []).map(entry => [ + entry.slice(root.length), + path.join(dir, entry), + ]), + ), + })), + ); +} + +/** + * Searches the layouts in order. A header in more than one layout is the one + * clang finds first. + */ +function mergeLayouts(layouts: ReadonlyArray): HeaderLayout { + const headers: Map = new Map(); + for (const layout of layouts) { + for (const [includePath, file] of layout.headers) { + if (!headers.has(includePath)) { + headers.set(includePath, file); + } + } + } + return { + includeDirs: layouts.flatMap(layout => layout.includeDirs), + frameworkDirs: layouts.flatMap(layout => layout.frameworkDirs), + headers, + }; +} + +module.exports = {layoutFromEntries, mergeLayouts}; diff --git a/scripts/abi-check/normalize.js b/scripts/abi-check/normalize.js new file mode 100644 index 000000000000..1c46232b586e --- /dev/null +++ b/scripts/abi-check/normalize.js @@ -0,0 +1,59 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +export type LayoutMap = Map; + +const RECORD_LAYOUT = + /^\*\*\* Dumping AST Record Layout\n([\s\S]*?nvalign=\d+\])/gm; +const VTABLE = + /^Vtable for '([^']+)' \(\d+ entries\)\.\n[\s\S]*?(?=\n\n|(?![\s\S]))/gm; +const SOURCE_LOCATION = /\(([^()]*?) at [^()]*?:\d+:\d+\)/g; +const HEX_ADDRESS = /0x[0-9a-f]{6,}/g; + +function stripVolatile(text: string): string { + return text.replace(SOURCE_LOCATION, '($1)').replace(HEX_ADDRESS, '0x'); +} + +/** + * Splits a clang layout dump into one block per type whose name matches + * `namespacePattern`. Keys are `L ` (record layout) and `V ` + * (vtable). Source locations and hex addresses are stripped from keys and + * values, so dumps of the same headers from different locations compare equal. + */ +function normalizeDump( + raw: string, + options: {namespacePattern: RegExp}, +): LayoutMap { + const layouts: LayoutMap = new Map(); + const add = (kind: 'L' | 'V', name: string, block: string) => { + // Unnamed records and lambdas are named by source location; they are + // covered by the layout of the record that contains them. + if (name.search(SOURCE_LOCATION) !== -1) { + return; + } + const key = `${kind} ${name}`; + if (name.search(options.namespacePattern) !== -1 && !layouts.has(key)) { + layouts.set(key, stripVolatile(block)); + } + }; + + for (const [, block] of raw.matchAll(RECORD_LAYOUT)) { + const name = block + .slice(0, block.indexOf('\n')) + .replace(/^\s*0 \|\s*(?:struct |class |union )?/, ''); + add('L', name, block); + } + for (const [block, name] of raw.matchAll(VTABLE)) { + add('V', name, block); + } + return layouts; +} + +module.exports = {normalizeDump}; diff --git a/scripts/abi-check/skipped-headers.js b/scripts/abi-check/skipped-headers.js new file mode 100644 index 000000000000..981da7c2da0e --- /dev/null +++ b/scripts/abi-check/skipped-headers.js @@ -0,0 +1,113 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +import type {Platform} from './dump'; + +export type SkippedHeader = { + platform: Platform, + /** The include path, as written in `#include <...>`. */ + header: string, + /** Why the header does not compile in a published layout. */ + reason: string, + /** + * The release versions the entry applies to: it applies when the base or + * the current version is one of them. Without it, it applies to all. + */ + versions?: ReadonlyArray, +}; + +const FLATTENED = 'iOS prebuild flattens subfolders (headers.js basename rule)'; +const ANDROID_ONLY = 'Android-only header shipped in iOS package'; +const MISSING_INCLUDE = 'missing include'; +const PREFAB_0_87 = + '0.87.1 prefab layout: text/platform/android is not on the include root'; +const IMAGEMANAGER_PREFAB = + 'prefab layout: imagemanager/platform/cxx, not platform/android, is on the include root'; + +/** + * Stable API headers that do not compile in a published layout. The ABI + * check drops them from both sides; any other header that does not compile + * fails the check. An entry without `versions` skips its header in every + * comparison, also with versions where it compiles. Remove an entry when its + * cause is fixed in every version the check compares with. + */ +const SKIPPED_HEADERS: ReadonlyArray = [ + ...[ + 'AnimatedModule.h', + 'AnimationDriver.h', + 'DecayAnimationDriver.h', + 'FrameAnimationDriver.h', + 'InterpolationAnimatedNode.h', + 'NativeAnimatedNodesManager.h', + 'NativeAnimatedNodesManagerProvider.h', + 'PropsAnimatedNode.h', + 'RoundAnimatedNode.h', + 'SpringAnimationDriver.h', + ].map((name): SkippedHeader => ({ + platform: 'ios', + header: `react/renderer/animated/${name}`, + reason: FLATTENED, + })), + { + platform: 'ios', + header: 'react/renderer/mounting/StubViewTree.h', + reason: FLATTENED, + }, + { + platform: 'ios', + header: 'react/renderer/mounting/stubs.h', + reason: FLATTENED, + }, + ...[ + 'AndroidTextInputComponentDescriptor.h', + 'AndroidTextInputProps.h', + 'AndroidTextInputShadowNode.h', + ].map((name): SkippedHeader => ({ + platform: 'ios', + header: `react/renderer/components/textinput/${name}`, + reason: ANDROID_ONLY, + })), + { + platform: 'ios', + header: 'react/renderer/components/iostextinput/propsConversions.h', + reason: MISSING_INCLUDE, + }, + { + platform: 'ios', + header: 'react/renderer/scheduler/InspectorData.h', + reason: MISSING_INCLUDE, + }, + ...[ + 'ParagraphComponentDescriptor.h', + 'ParagraphProps.h', + 'ParagraphShadowNode.h', + 'SelectableParagraphComponentDescriptor.h', + 'SelectableParagraphShadowNode.h', + 'stateConversions.h', + ].map((name): SkippedHeader => ({ + platform: 'android', + header: `react/renderer/components/text/${name}`, + reason: PREFAB_0_87, + versions: ['0.87.1'], + })), + ...['ImageFetcher.h', 'conversions.h'].map((name): SkippedHeader => ({ + platform: 'android', + header: `react/renderer/imagemanager/platform/android/react/renderer/imagemanager/${name}`, + reason: IMAGEMANAGER_PREFAB, + })), + { + platform: 'android', + header: 'react/renderer/scheduler/InspectorData.h', + reason: MISSING_INCLUDE, + versions: ['0.87.1'], + }, +]; + +module.exports = {SKIPPED_HEADERS}; diff --git a/scripts/abi-check/source.js b/scripts/abi-check/source.js new file mode 100644 index 000000000000..84481e47466b --- /dev/null +++ b/scripts/abi-check/source.js @@ -0,0 +1,194 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +import type {SpecEntry} from '../../packages/react-native/scripts/ios-prebuild/headers-spec'; +import type {HeaderLayout} from './layout'; + +const { + computeSpecPlan, +} = require('../../packages/react-native/scripts/ios-prebuild/headers-compose'); +const {mergeLayouts} = require('./layout'); +const fs = require('node:fs'); +const path = require('node:path'); + +/** + * One rule of ReactAndroid's preparePrefab task: the headers below `from`, a + * path relative to ReactAndroid, go to `prefix` in the prefab `module`. + */ +export type PrefabHeaderRule = {module: string, from: string, prefix: string}; + +const SOURCE_PAIR = /^Pair\(\s*"([^"]*)"\s*,\s*"([^"]*)"\s*,?\s*\)/; +const BUILD_DIR_PAIR = + /^Pair\(\s*File\(buildDir,\s*"[^"]*"\)\.absolutePath\s*,\s*"[^"]*"\s*,?\s*\)/; + +/** + * Reads the prefab header rules from ReactAndroid's build.gradle.kts. The + * rules that copy from the build folder, for the third-party and codegen + * headers, are left out: the source tree does not have those headers. + */ +function prefabHeaderRules(gradleScript: string): Array { + const entries = gradleScript.split('PrefabPreprocessingEntry(').slice(1); + if (entries.length === 0) { + throw new Error( + 'Found no prefab modules (PrefabPreprocessingEntry) in build.gradle.kts.', + ); + } + return entries.flatMap(entry => { + const module = entry.match(/^\s*"([^"]+)"/)?.[1]; + if (module == null) { + throw new Error(`Cannot read the prefab module name in: ${entry}`); + } + return entry + .split(/(?=\bPair\()/) + .slice(1) + .flatMap(pair => { + const source = pair.match(SOURCE_PAIR); + if (source != null) { + return [{module, from: source[1], prefix: source[2]}]; + } + if (BUILD_DIR_PAIR.test(pair)) { + return []; + } + throw new Error( + `Cannot read the prefab header rule ${pair.slice(0, pair.indexOf(')') + 1)}`, + ); + }); + }); +} + +/** The `.h` files that a prefab rule copies from `from`, by their new paths. */ +function prefabRuleHeaders( + from: string, + prefix: string, +): Array<[string, string]> { + if (!fs.existsSync(from)) { + return []; + } + const [dir, relativePaths] = fs.statSync(from).isDirectory() + ? [from, fs.readdirSync(from, {recursive: true, encoding: 'utf8'})] + : [path.dirname(from), [path.basename(from)]]; + return relativePaths + .filter(relativePath => relativePath.endsWith('.h')) + .map(relativePath => [ + path.posix.join(prefix, relativePath.split(path.sep).join('/')), + path.join(dir, relativePath), + ]); +} + +function copyHeaders( + dir: string, + sources: ReadonlyMap, +): HeaderLayout { + const headers: Map = new Map(); + for (const [includePath, source] of sources) { + const destination = path.join(dir, includePath); + fs.mkdirSync(path.dirname(destination), {recursive: true}); + fs.copyFileSync(source, destination); + headers.set(includePath, destination); + } + return {includeDirs: [dir], frameworkDirs: [], headers}; +} + +/** + * Copies the headers of the React Native package at `packageDir` to `outDir` + * as the react-android AAR's prefab modules ship them, one folder per module. + * A later rule replaces a header that an earlier rule copied, as in Gradle. + */ +function androidSourceLayout(packageDir: string, outDir: string): HeaderLayout { + const reactAndroid = path.join(packageDir, 'ReactAndroid'); + const rules = prefabHeaderRules( + fs.readFileSync(path.join(reactAndroid, 'build.gradle.kts'), 'utf8'), + ); + const modules: Map> = new Map(); + for (const {module, from, prefix} of rules) { + const headers = modules.get(module) ?? new Map(); + modules.set(module, headers); + for (const [includePath, file] of prefabRuleHeaders( + path.resolve(reactAndroid, from), + prefix, + )) { + headers.set(includePath, file); + } + } + return mergeLayouts( + [...modules] + .sort(([a], [b]) => a.localeCompare(b)) + .map(([module, headers]) => + copyHeaders(path.join(outDir, module), headers), + ), + ); +} + +/** The parts of the iOS prebuild's headers spec that the check lays out. */ +export type IosHeadersPlan = { + readonly react: ReadonlyArray>, + readonly reactNativeHeaders: ReadonlyArray>, + ... +}; + +/** Writes each entry below `dir`, as a copy or as a redirect to its home. */ +function writeSpecEntries( + dir: string, + entries: ReadonlyArray>, + packageDir: string, +): Map { + const headers: Map = new Map(); + for (const {relPath, source, redirectTo} of entries) { + const destination = path.join(dir, relPath); + fs.mkdirSync(path.dirname(destination), {recursive: true}); + if (redirectTo != null) { + fs.writeFileSync(destination, `#import <${redirectTo}>\n`); + } else { + fs.copyFileSync(path.join(packageDir, source), destination); + } + headers.set(relPath, destination); + } + return headers; +} + +/** + * Writes the headers of the React Native package at `packageDir` to `outDir` + * as the iOS core ships them: ReactNativeHeaders in `Headers`, and + * React.framework, whose headers are included as ``, in + * `Frameworks`. `plan` defaults to the headers spec of the iOS prebuild. + */ +function iosSourceLayout( + packageDir: string, + outDir: string, + plan: IosHeadersPlan = computeSpecPlan(packageDir), +): HeaderLayout { + const headersDir = path.join(outDir, 'Headers'); + const frameworksDir = path.join(outDir, 'Frameworks'); + const reactHeaders = writeSpecEntries( + path.join(frameworksDir, 'React.framework', 'Headers'), + plan.react, + packageDir, + ); + return mergeLayouts([ + { + includeDirs: [headersDir], + frameworkDirs: [frameworksDir], + headers: writeSpecEntries( + headersDir, + plan.reactNativeHeaders, + packageDir, + ), + }, + { + includeDirs: [], + frameworkDirs: [], + headers: new Map( + [...reactHeaders].map(([header, file]) => [`React/${header}`, file]), + ), + }, + ]); +} + +module.exports = {androidSourceLayout, iosSourceLayout, prefabHeaderRules}; diff --git a/scripts/abi-check/tiers.js b/scripts/abi-check/tiers.js new file mode 100644 index 000000000000..7583772f3b79 --- /dev/null +++ b/scripts/abi-check/tiers.js @@ -0,0 +1,195 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +import type {Platform} from './dump'; + +const fs = require('node:fs'); +const path = require('node:path'); + +// Keep in sync with scripts/cxx-api/parser/tiers.py. +const GUARD = + /^\s*#\s*include\s*[<"]react\/cxxstableapi\/(Private|Frameworks|Umbrella)Guard\.h[>"]/m; +const GUARD_DIR = '/react/cxxstableapi/'; +const STABLE_API_GUARDS = new Set(['Frameworks', 'Umbrella']); + +// Keep in sync with _TEMPLATE_EXCLUDE_PATTERNS in +// scripts/cxx-api/parser/__main__.py and with scripts/cxx-api/config.yml: the +// top-level list, then the ReactApple or ReactAndroid view's list. +const TEMPLATE_EXCLUDE_PATTERNS = ['*/tests/*', '*/samples/*']; +const GLOBAL_EXCLUDE_PATTERNS = [ + '*/ReactCommon/react/nativemodule/fantomtestspecificmethods/*', + '*/ReactCommon/react/nativemodule/featureflags/*', + '*/ReactCommon/react/featureflags/*', + '*/test_utils/*', + '*/test/*', + '*/test_helper/*', + '*/stubs/*', + '*/metainternal/*', +]; +const PLATFORM_EXCLUDE_PATTERNS: { + readonly [platform: Platform]: Array, +} = { + ios: [ + '*/jni/*', + '*/platform/cxx/*', + '*/platform/windows/*', + '*/platform/macos/*', + '*/platform/android/*', + '*+Private.h', + '*+Internal.h', + '*/scripts/*', + '*/templates/*', + '*/components/progressbar/android/*', + '*/components/switch/androidswitch/*', + ], + android: [ + '*/ReactAndroid/src/main/jni/react/featureflags/*', + '*/components/switch/iosswitch/*', + '*/components/inputaccessory/*', + '*/platform/cxx/*', + '*/platform/windows/*', + '*/platform/macos/*', + '*/platform/ios/*', + ], +}; + +// The source folders that the iOS and Android builds ship as include roots. +// The headers below them keep their paths in `#include <...>`. +const SOURCE_INCLUDE_ROOTS = ['*/ReactCommon/', '*/ReactAndroid/src/main/jni/']; + +/** + * The fnmatch patterns of the headers that the C++ API snapshot of `platform` + * leaves out. The C++ API snapshot matches them against source-tree paths. + */ +function excludePatterns(platform: Platform): Array { + return [ + ...new Set([ + ...TEMPLATE_EXCLUDE_PATTERNS, + ...GLOBAL_EXCLUDE_PATTERNS, + ...PLATFORM_EXCLUDE_PATTERNS[platform], + ]), + ]; +} + +/** Python's `fnmatch.fnmatchcase`, without `[...]` sets, which no list uses. */ +function fnmatchRegExp(pattern: string): RegExp { + if (pattern.includes('[')) { + throw new Error(`Unsupported exclude pattern: ${pattern}`); + } + const source = pattern + .split('') + .map(char => + char === '*' + ? '.*' + : char === '?' + ? '.' + : char.replace(/[.+^${}()|\]\\/]/, '\\$&'), + ) + .join(''); + return new RegExp(`^${source}$`, 's'); +} + +/** + * `pattern` as matched against `/` and an include path. A pattern that starts + * with a source include root, such as the one for ReactCommon's feature + * flags, matches from the include root instead. + */ +function includePathPattern(pattern: string): RegExp { + const root = SOURCE_INCLUDE_ROOTS.find(prefix => pattern.startsWith(prefix)); + return fnmatchRegExp( + root != null ? `/${pattern.slice(root.length)}` : pattern, + ); +} + +const PLATFORM_FOLDER_COPY = /^(?:.*\/)?platform\/[^/]+\/(.+)$/; + +function walkHeaders(dir: string): Array { + return fs.readdirSync(dir).flatMap(name => { + const entryPath = path.join(dir, name); + // lstat, so that symlinked directories are not followed, like os.walk. + if (fs.lstatSync(entryPath).isDirectory()) { + return walkHeaders(entryPath); + } + return name.endsWith('.h') ? [entryPath] : []; + }); +} + +/** + * Whether `file`, at `pathInRoot` below a header root, declares the public or + * for-frameworks tier with the first `react/cxxstableapi/*Guard.h` it + * includes, and no `excluded` pattern matches `/` and `pathInRoot`. + */ +function isStableApiHeader( + pathInRoot: string, + file: string, + excluded: ReadonlyArray, +): boolean { + const rooted = `/${pathInRoot}`; + if ( + rooted.includes(GUARD_DIR) || + excluded.some(pattern => pattern.test(rooted)) + ) { + return false; + } + const guard = fs.readFileSync(file, 'utf8').match(GUARD)?.[1]; + return guard != null && STABLE_API_GUARDS.has(guard); +} + +/** + * Returns the include paths, sorted, of the `headers` in the public or + * for-frameworks tier of the C++ stable API, without those that the C++ API + * snapshot of `platform` excludes. `headers` maps each include path, the path + * written in `#include <...>`, to its file. + * + * The verdict depends only on the include path and the file, so a header gets + * the same verdict from the source tree and from a Maven artifact. A header at + * `.../platform//` is left out when `` is also in + * `headers`: the prefab modules copy platform folders whole, and also put one + * platform's folder at the include root, where code includes it from. A + * header that is only in a platform folder stays. + */ +function stableApiHeaders( + headers: ReadonlyMap, + platform: Platform, +): Array { + const excluded = excludePatterns(platform).map(includePathPattern); + return [...headers] + .filter( + ([includePath, file]) => + !headers.has(includePath.match(PLATFORM_FOLDER_COPY)?.[1] ?? '') && + isStableApiHeader(includePath, file, excluded), + ) + .map(([includePath]) => includePath) + .sort(); +} + +/** + * Returns the absolute paths, sorted, of the headers in the source tree under + * `headerRoot` that are in the public or for-frameworks tier of the C++ + * stable API, without those that the C++ API snapshot of `platform` excludes. + */ +function collectStableApiHeaders( + headerRoot: string, + platform: Platform, +): Array { + const root = path.resolve(headerRoot); + const excluded = excludePatterns(platform).map(includePathPattern); + return walkHeaders(root) + .filter(header => + isStableApiHeader( + path.relative(root, header).split(path.sep).join('/'), + header, + excluded, + ), + ) + .sort(); +} + +module.exports = {collectStableApiHeaders, excludePatterns, stableApiHeaders}; From 5f45978ff0e2078d41522a37c17ca11d4a062967 Mon Sep 17 00:00:00 2001 From: Christian Falch Date: Thu, 26 Nov 2026 18:32:41 +0100 Subject: [PATCH 2/3] Add technical docs for scripts/abi-check Describes what the C++ ABI check finds, how to run it, each stage of the check, its known limits and the skip list, and links it from the docs index under Testing > C++. --- __docs__/README.md | 1 + scripts/abi-check/__docs__/README.md | 174 +++++++++++++++++++++++++++ 2 files changed, 175 insertions(+) create mode 100644 scripts/abi-check/__docs__/README.md diff --git a/__docs__/README.md b/__docs__/README.md index 4ff46942ed26..002f0034bb1e 100644 --- a/__docs__/README.md +++ b/__docs__/README.md @@ -90,6 +90,7 @@ TODO: Explain the different components of React Native at a high level. - Android - iOS - C++ + - [C++ ABI check](../scripts/abi-check/__docs__/README.md) - JavaScript - Flow - TypeScript diff --git a/scripts/abi-check/__docs__/README.md b/scripts/abi-check/__docs__/README.md new file mode 100644 index 000000000000..31c54e4a2e59 --- /dev/null +++ b/scripts/abi-check/__docs__/README.md @@ -0,0 +1,174 @@ +# C++ ABI check + +[🏠 Home](../../../__docs__/README.md) + +The scripts in `scripts/abi-check/` find ABI breaks in the C++ stable API of +React Native. An ABI break is a change in the size or the memory layout of a +public type, in the order of its virtual methods, or in the values of its +enumerators. Code that was compiled against the earlier release then reads the +wrong memory or calls the wrong function, even though it still compiles against +the new headers. + +The API snapshots in `scripts/cxx-api` and `scripts/js-api` record declarations, +not layouts, so they do not find these changes. For example, between 0.87 and +0.88 `facebook::yoga::Style` shrank from 280 to 160 bytes. This changed the +layout of `YogaStylableProps` and `BaseViewProps`, and no existing check +reported it. + +The check compiles the stable API headers of two versions with clang, dumps the +layouts of their types, and compares the dumps. The base is always a version +published on Maven. The other side is another published version or a checkout of +this repository. + +## 🚀 Usage + +```bash +node scripts/abi-check/cli.js --platform ios --build-type release \ + --base 0.88.0 --current . +``` + +| Flag | Value | +| -------------- | ------------------------------------------------------------------------------------------------------------------- | +| `--platform` | `ios` or `android`. | +| `--build-type` | `debug` or `release`. | +| `--base` | The published version to compare with, such as `0.88.0`. | +| `--current` | The root folder of a checkout, if that folder exists. Otherwise a published version. | +| `--cache-dir` | Where downloaded artifacts are kept. The default is `react-native-abi-check` in the temporary folder of the system. | +| `--json` | Prints the result as JSON instead of text. | + +Each platform and build type is a separate ABI, so one run checks one pair. + +The exit status is: + +- `0`: no ABI breaks. +- `1`: one or more ABI breaks. The output lists each changed or removed type. +- `2`: bad arguments, or a tool error, such as a failed download or a header + that does not compile. + +Requirements: + +- iOS needs Xcode. The check finds the `iphoneos` SDK with `xcrun`. +- Android needs the Android NDK. The check uses `ANDROID_NDK_HOME`. Otherwise it + uses the newest NDK in the `ndk` folder of the Android SDK, from + `ANDROID_HOME`, `ANDROID_SDK_ROOT` or `~/Library/Android/sdk`. + +To run the unit tests: + +```bash +yarn jest --no-cache -i scripts/abi-check +``` + +## 📐 Design + +A run has these stages: select the headers, lay out each side, dump the layouts +with clang, and compare the dumps. + +### Header selection (`tiers.js`) + +A header is in the stable API when the first `react/cxxstableapi/*Guard.h` it +includes is `UmbrellaGuard.h` or `FrameworksGuard.h`. This rule is a copy of the +one in `scripts/cxx-api/parser/tiers.py`. The check then removes the headers +that the C++ API snapshot excludes for the platform. The exclude patterns are a +copy of `_TEMPLATE_EXCLUDE_PATTERNS` in `scripts/cxx-api/parser/__main__.py` and +of the lists in `scripts/cxx-api/config.yml`. Keep all three in sync. + +A header is identified by its include path, the path written in +`#include <...>`. So a header gets the same verdict in the source tree and in a +published artifact. + +### Header layouts (`layout.js`) + +A header layout is the data that clang needs for one side: the `-I` folders, the +`-F` folders, and a map from include path to file. When two layouts are merged, +a header that is in both comes from the first, as clang finds it. + +### Published baseline (`artifacts.js`) + +The check downloads the headers of a published version from Maven Central: + +- iOS: the `reactnative-core` and `reactnative-dependencies-headers` tarballs of + `react-native-artifacts`, for the build type. +- Android: the `react-android` AAR, whose prefab modules hold the headers, and + the `fbjni` AAR at the version that the `react-android` POM names. + +Each archive is kept in the cache folder. It gets its cache name only after its +SHA-1 matches the checksum that Maven lists. The headers are extracted next to +the archive once. + +### Checkout side (`source.js`) + +For a checkout, the check builds the layout that the published artifacts would +have: + +- iOS: it writes the headers as the iOS prebuild spec plans them. It always uses + the prebuild scripts of this repository, whatever the version of the checkout. +- Android: it copies the headers by the prefab rules in + `ReactAndroid/build.gradle.kts`. It adds the `fbjni` headers at the version in + the Gradle version catalog. + +A checkout has no third-party, codegen or Hermes headers. Clang finds them in +the base artifacts, after the headers of the checkout. + +### Dumping (`dump.js`) + +The check compiles one translation unit per side with the flags of React +Native's own builds for the platform and build type. Clang dumps: + +- the record layout of each type: size, alignment, and field offsets, +- the vtable of each polymorphic class. Clang lays out a vtable only when the + translation unit uses it, so a second run adds code that uses each one, +- the enumerator values of each enum. + +Only types in `facebook::react`, `facebook::yoga` and `facebook::jsi` are kept. + +### Comparison (`check.js`, `diff.js`) + +Both sides are dumped with the union of their stable API headers. A header that +only one side marks as stable is still dumped on both sides, so a change of tier +alone is not reported. Each side dumps only the headers that it has. + +A type whose dump changed or that was removed is an ABI break. A type that was +added is not a break. The result counts added types but does not list them. + +### Skip list (`skipped-headers.js`) + +Some stable API headers do not compile in a published layout. The skip list +names each one with its platform and a reason. An entry can also name the +versions it applies to. It then applies when the base or the current version is +one of them. Without versions, it applies to all comparisons. + +The check removes the skipped headers from both sides and prints their names. +Any other header that does not compile stops the run with exit status `2`. + +To add an entry, add the header, the platform and the reason to +`SKIPPED_HEADERS`. Give `versions` when only some releases are affected. To +remove an entry, make sure that its cause is fixed in every version the check +compares with, then delete it. + +## ⚠️ Known limits + +- The check does not run in CI yet. +- It does not check exported symbols, or the Java and Kotlin API. +- Some published iOS headers do not compile alone, because the prebuilt package + flattens their subfolders. These headers are on the skip list. PR + [#60295](https://github.com/react/react-native/pull/60295) fixes the cause. + +## 🔗 Relationship with other systems + +### Part of + +- Testing / C++ in the [root documentation](../../../__docs__/README.md). + +### Used by this + +- `packages/react-native/scripts/spm/download-spm-artifacts`: downloads the + Maven artifacts, with retries. +- [iOS prebuild](../../../packages/react-native/scripts/ios-prebuild/__docs__/README.md): + its headers spec gives the header layout of an iOS checkout. +- `scripts/cxx-api`: `parser/tiers.py` holds the stable API rule, and + `parser/__main__.py` and `config.yml` hold the exclude patterns. `tiers.js` + copies all three. + +### Uses this + +- Nothing yet. A CI workflow is a planned follow-up. From 271ccf9208b3d26d501bdfdb907bf90d0bdb6c0b Mon Sep 17 00:00:00 2001 From: Christian Falch Date: Thu, 26 Nov 2026 19:28:57 +0100 Subject: [PATCH 3/3] Commit the abi-check iOS fixtures and keep fixtures out of clang-format The *.xcframework rule in .gitignore hid the Maven iOS fixture headers, so the tests that read them failed in CI. clang-format also rewrote fixture headers that are written as test input, one of them misformatted on purpose. --- .clang-format-ignore | 1 + .gitignore | 1 + .../Headers/react/cxxstableapi/UmbrellaGuard.h | 8 ++++++++ .../ios-arm64/Headers/react/featureflags/Flags.h | 10 ++++++++++ .../ios-arm64/Headers/react/renderer/core/Props.h | 10 ++++++++++ .../ios-arm64/Headers/react/renderer/view/HostProps.h | 10 ++++++++++ 6 files changed, 40 insertions(+) create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/cxxstableapi/UmbrellaGuard.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/featureflags/Flags.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/renderer/core/Props.h create mode 100644 scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/renderer/view/HostProps.h diff --git a/.clang-format-ignore b/.clang-format-ignore index 8d232f8c190b..23906b65869d 100644 --- a/.clang-format-ignore +++ b/.clang-format-ignore @@ -7,3 +7,4 @@ packages/react-native/ReactAndroid/src/main/jni/third-party/** packages/react-native/ReactCommon/**/platform/windows/third-party/** packages/react-native/ReactCommon/jsi/jsi/** packages/react-native/ReactCommon/yoga/** +scripts/abi-check/__tests__/__fixtures__/** diff --git a/.gitignore b/.gitignore index d1e403fa6aa7..f1daaeebb551 100644 --- a/.gitignore +++ b/.gitignore @@ -155,6 +155,7 @@ vendor/ /packages/react-native/third-party/ fix_*.patch *.xcframework +!/scripts/abi-check/__tests__/__fixtures__/**/*.xcframework # Visual Studio Code (config dir - if present, this merges user defined # workspace settings on top of react-native.code-workspace) diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/cxxstableapi/UmbrellaGuard.h b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/cxxstableapi/UmbrellaGuard.h new file mode 100644 index 000000000000..f852921e0abf --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/cxxstableapi/UmbrellaGuard.h @@ -0,0 +1,8 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/featureflags/Flags.h b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/featureflags/Flags.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/featureflags/Flags.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/renderer/core/Props.h b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/renderer/core/Props.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/renderer/core/Props.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include diff --git a/scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/renderer/view/HostProps.h b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/renderer/view/HostProps.h new file mode 100644 index 000000000000..ad5bc9882416 --- /dev/null +++ b/scripts/abi-check/__tests__/__fixtures__/layouts/maven-ios/ReactNativeHeaders.xcframework/ios-arm64/Headers/react/renderer/view/HostProps.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include