### Setup MiniReact Benchmark Environment Source: https://github.com/facebook/hermes/blob/static_h/benchmarks/MiniReact/no-objects/README.md Installs dependencies for the flow-bundler and configures the build environment for the MiniReact benchmark. Ensure you are in the correct directory before running. ```bash (cd ~/builds; cmake -S ~/fbsource/xplat/static_h/benchmarks/ -B benchmarksdebug -G Ninja -DHERMES_BUILD=~/builds/shdebug -DHERMES_SRC=~/fbsource/xplat/static_h) && (cd ~/fbsource/xplat/static_h/benchmarks/build-helpers/flow-bundler; yarn install) ``` -------------------------------- ### Implement C++ Extension Installation Source: https://github.com/facebook/hermes/blob/static_h/API/hermes/extensions/contrib/README.md Implement the C++ function to register native helpers and call the JavaScript setup function. ```cpp /* * 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 "YourExtension.h" #include "../Intrinsics.h" // If you need intrinsics namespace facebook { namespace hermes { void installYourExtension(jsi::Runtime &rt, jsi::Object &extensions) { // Create native helpers object if needed jsi::Object nativeHelpers = jsi::Object(rt); // Add native functions (optional) nativeHelpers.setProperty(rt, "myNativeFunc", jsi::Function::createFromHostFunction(rt, jsi::PropNameID::forAscii(rt, "myNativeFunc"), 1, // argument count [](jsi::Runtime &rt, const jsi::Value &, const jsi::Value *args, size_t count) -> jsi::Value { // Implementation return jsi::Value::undefined(); })); // Get and call the setup function jsi::Function setup = extensions.getPropertyAsFunction(rt, "YourExtension"); setup.call(rt, nativeHelpers); } } // namespace hermes } // namespace facebook ``` -------------------------------- ### Install and Run lit via Setuptools Source: https://github.com/facebook/hermes/blob/static_h/external/llvh/utils/lit/README.txt Install lit using setuptools and then run the test suite. This verifies that lit functions correctly when installed as a package. ```shell python utils/lit/setup.py install lit --path /path/to/your/llvm/build/bin utils/lit/tests ``` -------------------------------- ### Install Dependencies and Build ES5 Widgets Source: https://github.com/facebook/hermes/blob/static_h/benchmarks/widgets/original/es5/README.md Run these commands to install project dependencies and then build the ES5 widgets.js file. ```bash npm install npm run build ``` -------------------------------- ### Install Hermes executable Source: https://github.com/facebook/hermes/blob/static_h/tools/hermes/CMakeLists.txt Installs the 'hermes' executable to the 'bin' directory in the runtime destination. ```cmake install(TARGETS hermes RUNTIME DESTINATION bin ) ``` -------------------------------- ### Interact with SQLite Database using sqlite.js Source: https://github.com/facebook/hermes/blob/static_h/examples/ffi/README.md Example of using libsqlite3 via FFI to open a database, execute a query, and print results. Requires libsqlite3 installation. Run with 'shermes -typed -exec sqlite.js -lsqlite3'. ```javascript const sqlite3 = require('sqlite3'); const db = new sqlite3.Database(':memory:'); db.serialize(() => { db.run('CREATE TABLE users (id INT, name TEXT)'); db.run("INSERT INTO users VALUES (1, 'Alice')"); db.run("INSERT INTO users VALUES (2, 'Bob')"); db.each('SELECT * FROM users', (err, row) => { console.log(row); }); }); db.close(); ``` -------------------------------- ### Install AsmJit Library and Headers Source: https://github.com/facebook/hermes/blob/static_h/external/asmjit/asmjit/CMakeLists.txt Configures the installation of the AsmJit library, export files, and public headers. This is skipped if ASMJIT_NO_INSTALL is set. ```cmake if (NOT ASMJIT_NO_INSTALL) install(TARGETS asmjit EXPORT asmjit-config RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") install(EXPORT asmjit-config NAMESPACE asmjit:: DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/asmjit") foreach(_src_file ${ASMJIT_SRC_LIST}) if ("${_src_file}" MATCHES "\.h$" AND NOT "${_src_file}" MATCHES "_p\.h$") get_filename_component (_src_dir ${_src_file} PATH) install(FILES "${ASMJIT_DIR}/src/${_src_file}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${_src_dir}") endif() endforeach() endif() ``` -------------------------------- ### Install Hermes VM Executable Source: https://github.com/facebook/hermes/blob/static_h/tools/hvm/CMakeLists.txt Installs the 'hvm' target to the 'bin' directory at runtime. ```cmake install(TARGETS hvm RUNTIME DESTINATION bin ) ``` -------------------------------- ### Install babel-plugin-syntax-hermes-parser with npm Source: https://github.com/facebook/hermes/blob/static_h/tools/hermes-parser/js/babel-plugin-syntax-hermes-parser/README.md Install the plugin as a development dependency using npm. ```sh npm install --save-dev babel-plugin-syntax-hermes-parser ``` -------------------------------- ### Install npm packages for hcdp Source: https://github.com/facebook/hermes/blob/static_h/tools/hcdp/README.md Run this command to install the necessary npm packages before executing the hcdp tool. ```bash npm install ``` -------------------------------- ### Install babel-plugin-syntax-hermes-parser with yarn Source: https://github.com/facebook/hermes/blob/static_h/tools/hermes-parser/js/babel-plugin-syntax-hermes-parser/README.md Install the plugin as a development dependency using yarn. ```sh yarn add babel-plugin-syntax-hermes-parser --dev ``` -------------------------------- ### Install and Run Tests Source: https://github.com/facebook/hermes/blob/static_h/tools/hermes-parser/js/CLAUDE.md Install project dependencies and run Jest tests. Supports running tests with an optional pattern. ```bash yarn install # first time only yarn test [] ``` -------------------------------- ### Context Notes Example for a Step Source: https://github.com/facebook/hermes/blob/static_h/doc/plans/ir-type/progress.md Provides an example of the format for context notes after a step is completed or blocked. It includes sections for files, decisions, actions taken, issues encountered, and notes for the next step. ```markdown ### Step 11: Port util binding - **Files**: created `foo.c`, modified `bar.c`. - **Decisions**: -- Decision 1 concise explanation -- Decision 2 concise explanation - **What was done**: ... - **Issues**: ... - **Notes for next step**: ... ``` -------------------------------- ### Installing TypeContextRAII at Module Creation Source: https://github.com/facebook/hermes/blob/static_h/doc/plans/ir-type/ir-type-v2-implementation.md Demonstrates how to install the TypeContextRAII guard at the beginning of a module's lifetime to cover all subsequent Type operations. ```cpp // At Module creation: TypeContextRAII guard(module->getTypeContext()); // All Type operations for the lifetime of the Module are now covered. ``` -------------------------------- ### Setting up ARM32 Execution on ARM64 Linux Source: https://github.com/facebook/hermes/blob/static_h/doc/CrossCompilation.md Install necessary libraries for running ARM32 binaries on an ARM64 Linux host. ```bash # Add architecture dpkg --add-architecture armhf # Update sudo apt update # For running sudo apt install libc6:armhf libstdc++6:armhf ``` -------------------------------- ### Install npm Dependencies Source: https://github.com/facebook/hermes/blob/static_h/benchmarks/build-helpers/flow-bundler/README.md Install the necessary npm dependencies before using the Flow Bundler. Use either yarn or npm for installation. ```bash yarn install ``` ```bash npm install ``` -------------------------------- ### Install Hermes CDP Tool Source: https://github.com/facebook/hermes/blob/static_h/tools/hcdp/CMakeLists.txt Installs the hcdp tool executable to the bin directory. ```cmake install(TARGETS hcdp RUNTIME DESTINATION bin ) ``` -------------------------------- ### Start Fuzzing Source: https://github.com/facebook/hermes/blob/static_h/tools/fuzzers/fuzzilli/README.md Execute Fuzzilli with the Hermes profile, pointing to the location of the built binary. Ensure $BINARY_LOCATION is correctly set. ```shell cd $FUZZILLI_LOCATION swift run FuzzilliCli --profile=hermes $BINARY_LOCATION ``` -------------------------------- ### Hermes ESLint Parser Options Example Source: https://github.com/facebook/hermes/blob/static_h/tools/hermes-parser/js/hermes-eslint/README.md Example of providing parser options for hermes-eslint in a legacy ESLint configuration. ```json { "parser": "hermes-eslint", "parserOptions": { "sourceType": "module" } } ``` -------------------------------- ### Setting up ARM32 Compilation on ARM64 Linux Source: https://github.com/facebook/hermes/blob/static_h/doc/CrossCompilation.md Install necessary packages for compiling ARM32 binaries on an ARM64 Linux host, including C/C++ compilers and libraries. ```bash # Add architecture dpkg --add-architecture armhf # Update sudo apt update # For compiling sudo apt install gcc-arm-linux-gnueabihf g++-arm-linux-gnueabihf binutils-arm-linux-gnueabihf libc6:armhf libstdc++6:armhf ``` -------------------------------- ### Install and Activate Emscripten Toolchain Source: https://github.com/facebook/hermes/blob/static_h/doc/Emscripten.md Installs the latest Emscripten SDK and activates it for use. Ensure you are in the directory where you downloaded emsdk. ```shell ./emsdk install latest ./emsdk activate latest ``` -------------------------------- ### Benchmark Results Output Source: https://github.com/facebook/hermes/blob/static_h/benchmarks/bench-runner/README.md Example output from the bench-runner script, showing benchmark names and their total execution times. ```text Ran each benchmark 1 times Runtime: hermes General Stats: Benchmark total (time) -------------------------------------------------------- v8-crypto 552.0 s +- 0.0% v8-deltablue 787.0 s +- 0.0% v8-raytrace 163.0 s +- 0.0% v8-regexp 329.0 s +- 0.0% v8-richards 854.0 s +- 0.0% v8-splay 139.0 s +- 0.0% ``` -------------------------------- ### Install Hermes Debugger Tool Source: https://github.com/facebook/hermes/blob/static_h/tools/hdb/CMakeLists.txt Install the 'hdb' target to the 'bin' directory at runtime. ```cmake install(TARGETS hdb RUNTIME DESTINATION bin ) ``` -------------------------------- ### Install Dependencies with Yarn Source: https://github.com/facebook/hermes/blob/static_h/API/hermes/cdp/tools/hermes-inspector-msggen/README.md Installs the necessary development dependencies for the hermes-inspector-msggen package. This command should be run as a dev dependency. ```bash yarn add --dev @babel/cli @babel/core @babel/preset-env @babel/preset-flow jest @react-native/hermes-inspector-msggen ``` -------------------------------- ### Type Interning Example Source: https://github.com/facebook/hermes/blob/static_h/doc/plans/ir-type/ir-type-v2-implementation.md Demonstrates the interning process for creating an array type, showing how existing types are reused via a hash table lookup. ```cpp createArray(elemType): key = {kind: Array, elemType.id_} if internTable_.count(key): return Type(internTable_[key]) id = entries_.size() entries_.push_back({TypeKind::Array, {.array = {elemType}}}) internTable_[key] = id return Type(id) ``` -------------------------------- ### Configuration Struct Fields Source: https://github.com/facebook/hermes/blob/static_h/public/hermes/Public/README.md Example of fields generated for a configuration struct, including their types, names, and default values. ```cpp size_t Bar_ = 0; std::string Baz_ = "Hello"; ``` -------------------------------- ### Install Hermes Public Header Files Source: https://github.com/facebook/hermes/blob/static_h/public/hermes/Public/CMakeLists.txt Installs the header files for the Hermes public library to the include directory. This ensures the library's headers are accessible. ```cmake install(DIRECTORY "${PROJECT_SOURCE_DIR}/public/hermes/Public" DESTINATION include/hermes FILES_MATCHING PATTERN "*.h") install(DIRECTORY "${HERMES_COMMON_DIR}/public/hermes/Public" DESTINATION include/hermes FILES_MATCHING PATTERN "*.h") ``` -------------------------------- ### Run JavaScript with Hermes CLI Source: https://github.com/facebook/hermes/blob/static_h/README.md Example of executing a simple JavaScript snippet using the built Hermes CLI. The script prints 'Hello World'. ```shell echo "'use strict'; function hello() { print('Hello World'); } hello();" | ./bin/hermes ``` -------------------------------- ### Shermes Execution Command Source: https://github.com/facebook/hermes/blob/static_h/tools/test-runner/DESIGN.md Example of the command used to run compiled bytecode with Shermes. ```bash -Xes6-proxy -Xhermes-internal-test-methods -Xmicrotask-queue ``` -------------------------------- ### Require Module Example Source: https://github.com/facebook/hermes/blob/static_h/doc/Modules.md Demonstrates how to require another module using the 'require' function provided by the Hermes runtime. The argument must be an absolute path relative to the ZIP file or input directory root. ```javascript const Foo = require('/subdir/foo.js'); Foo.doSmth(); ``` -------------------------------- ### Register Extension in ContribExtensions.cpp Source: https://github.com/facebook/hermes/blob/static_h/API/hermes/extensions/contrib/README.md Include your extension's header and call its installation function within the `installContribExtensions` function. ```cpp #include "ContribExtensions.h" #include "ContribDummy.h" #include "YourExtension.h" // Add this void installContribExtensions(jsi::Runtime &rt, jsi::Object &extensions) { installContribDummy(rt, extensions); installYourExtension(rt, extensions); // Add this } ``` -------------------------------- ### Setup Profiles for Hermes Source: https://github.com/facebook/hermes/blob/static_h/tools/fuzzers/fuzzilli/README.md Move the Swift profile files into the Fuzzilli Sources directory. Ensure the FUZZILLI_LOCATION environment variable is set correctly. ```shell mv profile/*.swift $FUZZILLI_LOCATION/Sources/FuzzilliCli/Profiles/ ``` -------------------------------- ### Example Metadata JSON File Source: https://github.com/facebook/hermes/blob/static_h/doc/Modules.md This JSON file defines module segments and their resolutions. Segment '0' is the main segment loaded on startup. The resolutionTable maps require() arguments to actual file paths. ```json { "segments": { "0": [ "./cjs-subdir-main.js", "cjs-subdir-2.js", "bar/cjs-subdir-bar.js", "foo/cjs-subdir-foo.js" ] }, "resolutionTable": { "./cjs-subdir-main.js": { "foo": "./foo/cjs-subdir-foo.js" }, "./foo/cjs-subdir-foo.js": { "bar": "./bar/cjs-subdir-bar.js" } } } ``` -------------------------------- ### Deep Profiling Workflow Source: https://github.com/facebook/hermes/blob/static_h/agent-perf/README.md A five-step workflow for deep performance profiling, starting from PMU counters and ending with source-level hotspot annotation. ```bash # Step 1: Collect PMU counters agent-perf/tools/collect_pmu.sh workload.js --json > /tmp/pmu.json ``` ```bash # Step 2: Check for anomalies agent-perf/tools/pmu_anomalies.py -i /tmp/pmu.json ``` ```bash # Step 3: Profile with perf perf record -g -- ./compiled_binary perf report --stdio > /tmp/report.txt ``` ```bash # Step 4: Parse profile and find hot runtime functions agent-perf/tools/profile_to_json.py -i /tmp/report.txt --json agent-perf/tools/runtime_call_profiler.py -i /tmp/report.txt --json ``` ```bash # Step 5: Annotate source with hotspots perf annotate --stdio > /tmp/annotate.txt agent-perf/tools/annotate_source.py -i /tmp/annotate.txt ``` -------------------------------- ### Run Richards Benchmark Simulation Source: https://github.com/facebook/hermes/blob/static_h/test/AST2JS/richards.js.txt Initializes and runs the Richards benchmark simulation. It sets up various tasks (idle, worker, handler, device) and their queues, then starts the scheduler. Includes error checking for expected queue and hold counts. ```javascript function runRichards() { var scheduler = new Scheduler(); scheduler.addIdleTask(ID_IDLE, 0, null, COUNT); var queue = new Packet(null, ID_WORKER, KIND_WORK); queue = new Packet(queue, ID_WORKER, KIND_WORK); scheduler.addWorkerTask(ID_WORKER, 1000, queue); queue = new Packet(null, ID_DEVICE_A, KIND_DEVICE); queue = new Packet(queue, ID_DEVICE_A, KIND_DEVICE); queue = new Packet(queue, ID_DEVICE_A, KIND_DEVICE); scheduler.addHandlerTask(ID_HANDLER_A, 2000, queue); queue = new Packet(null, ID_DEVICE_B, KIND_DEVICE); queue = new Packet(queue, ID_DEVICE_B, KIND_DEVICE); queue = new Packet(queue, ID_DEVICE_B, KIND_DEVICE); scheduler.addHandlerTask(ID_HANDLER_B, 3000, queue); scheduler.addDeviceTask(ID_DEVICE_A, 4000, null); scheduler.addDeviceTask(ID_DEVICE_B, 5000, null); scheduler.schedule(); if (scheduler.queueCount != EXPECTED_QUEUE_COUNT || scheduler.holdCount != EXPECTED_HOLD_COUNT) { var msg = "Error during execution: queueCount = " + scheduler.queueCount + ", holdCount = " + scheduler.holdCount + "."; throw new Error(msg); } } ``` -------------------------------- ### Real-world example: Array constructor Source: https://github.com/facebook/hermes/blob/static_h/doc/GCSafeCoding.md Illustrates the use of PinnedValue for managing 'self' and 'selfParent' within the array constructor function. ```cpp CallResult arrayConstructor(void *, Runtime &runtime) { NativeArgs args = runtime.getCurrentFrame().getNativeArgs(); struct : public Locals { PinnedValue selfParent; PinnedValue self; } lv; LocalsRAII lraii(runtime, &lv); if (LLVM_LIKELY(!args.isConstructorCall() || ...)) { CallResult> selfRes = JSArray::create(runtime, runtime.arrayPrototype); if (LLVM_UNLIKELY(selfRes == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; lv.self = std::move(*selfRes); } else { CallResult> thisParentRes = NativeConstructor::parentForNewThis_RJS(runtime, ...); if (LLVM_UNLIKELY(thisParentRes == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; lv.selfParent = std::move(*thisParentRes); auto arrRes = JSArray::create(runtime, lv.selfParent); if (LLVM_UNLIKELY(arrRes == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; lv.self = std::move(*arrRes); } // ...use lv.self throughout the rest of the function... return lv.self.getHermesValue(); } ``` -------------------------------- ### BranchInst Example Source: https://github.com/facebook/hermes/blob/static_h/doc/IR.md Represents a jump to a different basic block. Terminates the current basic block and transfers control. Does not interact with memory. ```hermes-ir %0 = BranchInst %BB1 ``` -------------------------------- ### JS Setup for TextEncoder JSI Extension Source: https://github.com/facebook/hermes/blob/static_h/doc/blog/2025-12-12-new-way-to-contribute.md This JavaScript code sets up the TextEncoder constructor and its prototype methods, receiving native C++ implementations as arguments. It's designed to be called from C++ and installs the TextEncoder on the globalThis object. ```javascript extensions.TextEncoder = function(nativeInit, nativeEncode, nativeEncodeInto) { function TextEncoder() { if (!new.target) { throw new TypeError('TextEncoder must be called as a constructor'); } nativeInit(this); } TextEncoder.prototype.encode = nativeEncode; TextEncoder.prototype.encodeInto = nativeEncodeInto; // ... property definitions ... globalThis.TextEncoder = TextEncoder; }; ``` -------------------------------- ### Merged Benchmark Comparison Output Source: https://github.com/facebook/hermes/blob/static_h/benchmarks/bench-runner/README.md Example output from bench-merge, showing a comparison of benchmark results between two different runs (e.g., 'before' and 'after' revisions of Hermes). Includes total time and ratio. ```text runner benchmark Total time ratio ================================================================================================================ hermes (before) box2d 1677.4 s +- 0.8% 1.000 hermes (after) box2d 1653.4 s +- 0.3% 0.986 ---------------------------------------------------------------------------------------------------------------- hermes (before) code-load 2376.0 s +- 1.5% 1.000 hermes (after) code-load 2433.0 s +- 4.8% 1.024 ... hermes (before) v8-splay 115.4 s +- 0.8% 1.000 hermes (after) v8-splay 113.8 s +- 1.7% 0.986 ---------------------------------------------------------------------------------------------------------------- hermes (before) geomean 1.000 hermes (after) geomean 0.988 ``` -------------------------------- ### Configure AsmJit Target Options Source: https://github.com/facebook/hermes/blob/static_h/external/asmjit/asmjit/CMakeLists.txt Sets compile options and include directories for the AsmJit target. Ensures public headers are available for installation and build interfaces. ```cmake target_compile_options(asmjit INTERFACE ${ASMJIT_CFLAGS}) target_include_directories(asmjit BEFORE INTERFACE $ $) ``` -------------------------------- ### Dependency Graph for Phase 1 Source: https://github.com/facebook/hermes/blob/static_h/doc/plans/ir-type/phase1-steps.md Visualizes the dependencies between different implementation steps in Phase 1. This graph guides the order of commits to ensure all prerequisites are met. ```text P1-S1 (skeleton) ├──→ P1-S2 (queries) ──→ P1-S3 (operations) ──→ P1-S4 (utilities) ├──→ P1-S5 (thread-local) └──→ P1-S6 (wire into Module) P1-S5 + P1-S6 ──→ P1-S7 (RAII at entry points) P1-S7 ──→ P1-S7.5 (RAII in tests) P1-S4 + P1-S7.5 ──→ P1-S8 (rewrite Type) ``` -------------------------------- ### Flow Bundler Help Command Source: https://github.com/facebook/hermes/blob/static_h/benchmarks/build-helpers/flow-bundler/README.md View detailed usage instructions and available options for the Flow Bundler by running the help command. ```bash ./benchmarks/build-helpers/flow-bundler/bin/flow-bundler --help ``` -------------------------------- ### Create a JavaScript File Source: https://github.com/facebook/hermes/blob/static_h/doc/Emscripten.md Creates a simple JavaScript file named 'hello.js' with a console log statement. This file will be used to test the Wasm Hermes VM. ```shell echo 'var x = "hello"; console.log(`${x} world`);' > hello.js ``` -------------------------------- ### Basic Flow Bundler Usage Source: https://github.com/facebook/hermes/blob/static_h/benchmarks/build-helpers/flow-bundler/README.md Execute the Flow Bundler with essential arguments: output path, project root, and entry point files. This command generates a single bundle file. ```bash ./benchmarks/build-helpers/flow-bundler/bin/flow-bundler \ --out output/path/of/bundle.js --root project/root path/to/entrypoint1.js path/to/entrypoint2.js ``` -------------------------------- ### Create Class Instance Source: https://github.com/facebook/hermes/blob/static_h/doc/IR.md Constructs a new class from its constructor code. %function is the constructor code, %scope is the environment, %varScope describes %scope, %superClass is the parent class, and %homeObjectOutput receives the class's prototype. ```hermes-ir %0 = CreateClassInst %scope, %varScope, %function, %superClass, %homeObjectOutput ``` -------------------------------- ### ResolveScopeInst Source: https://github.com/facebook/hermes/blob/static_h/doc/IR.md Traverses the scope chain to retrieve an enclosing scope. It requires the target VariableScope, the starting scope, and the VariableScope associated with the starting scope. The target scope must be reachable from the starting scope. This instruction does not interact with memory. ```APIDOC ## ResolveScopeInst ### Description Traverse the scope chain to retrieve an enclosing scope. ### Semantics The instruction retrieves the requested scope, which must be reachable from the starting scope. ### Arguments - **%variablescope** (VariableScope) - The VariableScope corresponding to the enclosing scope to retrieve. - **%startVarScope** (VariableScope) - The VariableScope associated with %startScope. - **%startScope** (scope) - The scope from which to start traversing. ### Example `%0 = ResolveScopeInst %variablescope, %startVarScope, %startScope` ### Effects Does not read or write to memory. ``` -------------------------------- ### Install JSI Header Files Source: https://github.com/facebook/hermes/blob/static_h/API/jsi/jsi/CMakeLists.txt Installs JSI header files to the include directory, excluding test files. ```cmake install(DIRECTORY "${PROJECT_SOURCE_DIR}/API/jsi/" DESTINATION include FILES_MATCHING PATTERN "*.h" PATTERN "test" EXCLUDE) ``` -------------------------------- ### Clone and Copy LIT Utilities Source: https://github.com/facebook/hermes/blob/static_h/external/llvh/README.md This command sequence demonstrates how to obtain updated LIT testing tool utilities from the LLVM project repository. It involves cloning the LLVM project, checking out a specific commit, and copying the relevant LIT utility files to the Hermes project's external directory. ```bash git clone https://github.com/llvm/llvm-project.git cd llvm-project git checkout c1a0a213378a458fbea1a5c77b315c7dce08fd05 cp -r ./llvm/utils/lit/* /path/to/hermes/external/llvh/utils/lit ``` -------------------------------- ### Build Instrumented Binary Source: https://github.com/facebook/hermes/blob/static_h/tools/fuzzers/fuzzilli/README.md Configure and build the instrumented binary using CMake with Fuzzilli and trace PC guard enabled. Ensure $OTHER_FLAGS are set if needed. ```shell mkdir fuzzilli_build && cd fuzzilli_build cmake .. -DHERMES_ENABLE_FUZZILLI=ON -DHERMES_ENABLE_TRACE_PC_GUARD=ON $OTHER_FLAGS make fuzzilli ``` -------------------------------- ### File Operations with fopen.js Source: https://github.com/facebook/hermes/blob/static_h/examples/ffi/README.md Demonstrates basic file operations like opening, reading, and closing files using FFI. Run with 'shermes -typed -exec fopen.js'. ```javascript const fs = require('fs'); const fd = fs.open('test.txt', 'w'); fs.write(fd, 'Hello from Hermes FFI!\n'); fs.close(fd); const content = fs.read('test.txt'); console.log(content); ``` -------------------------------- ### Example Hermes IR Function Source: https://github.com/facebook/hermes/blob/static_h/doc/IR.md A well-formed example of a function in Hermes IR, demonstrating basic blocks and control flow instructions like BranchInst, CondBranchInst, and ReturnInst. ```hermesir function forEach(cond : boolean, value : number) %BB0: %0 = BranchInst %BB1 %BB1: %2 = CondBranchInst %cond, %BB2, %BB3 %BB2: %3 = ReturnInst %cond %BB3: %4 = ReturnInst %value ``` -------------------------------- ### Union Type Examples Source: https://github.com/facebook/hermes/blob/static_h/doc/plans/ir-type/ir-type-system-v2-design.md Illustrates the syntax for defining union types, which represent values that can be one of several member types. These examples show unions of primitives, classes, and null. ```hermesir Union(Number, String) -- number or string Union(ClassA, ClassB) -- instance of ClassA or ClassB Union(Number, ClassA, Null) -- number, ClassA instance, or null ``` -------------------------------- ### Add Executable and Link Libraries Source: https://github.com/facebook/hermes/blob/static_h/benchmarks/imgui-demo/CMakeLists.txt Defines the main executable for the ImGui demo and links it against the 'gui' library. ```cmake add_executable(imdemo-cpp imdemo-cpp.cpp ${BLOBS}) target_link_libraries(imdemo-cpp gui) ``` -------------------------------- ### Install iOS Pods with Custom Hermes Build Source: https://github.com/facebook/hermes/blob/static_h/doc/ReactNativeIntegration.md After disabling the default Hermes pod, run this command to install pods and enable building from source for your custom Hermes integration on iOS. ```bash BUILD_FROM_SOURCE=true bundle exec pod install ``` -------------------------------- ### Get Fuzzilli Source: https://github.com/facebook/hermes/blob/static_h/tools/fuzzers/fuzzilli/README.md Clone the Fuzzilli repository to your local machine. ```shell git clone https://github.com/googleprojectzero/fuzzilli.git ``` -------------------------------- ### Instance Data Source: https://github.com/facebook/hermes/blob/static_h/API/napi/COMPATIBILITY.md Functions for setting and getting instance data. ```APIDOC ## Instance Data ### Description Functions for setting and getting instance data. ### Functions - `napi_set_instance_data` - `napi_get_instance_data` ``` -------------------------------- ### Profile JIT-Compiled Code with Perf Source: https://github.com/facebook/hermes/blob/static_h/doc/PerfProfiling.md Use this command sequence to record, inject, and report JIT performance traces. Ensure you have a Linux machine with ARM64 architecture. The flags `-Xperf-prof` and `-Xperf-prof-dir` enable and specify the output directory for perf profiling, respectively. `-k mono` uses CLOCK_MONOTONIC for clock ID, matching jitdump. Sampling is set to user-space events by default. ```bash perf record -g -k mono -e cycles:u ./bin/hermes ~/js/test.js -Xjit=force \ -Xperf-prof -Xperf-prof-dir ./ perf inject -j -i perf.data -o perf.data.jitted perf report -i perf.data.jitted --call-graph=fractal,callee --children ``` -------------------------------- ### Get Builtin Closure Source: https://github.com/facebook/hermes/blob/static_h/doc/IR.md Retrieves a closure for a specified builtin function. Reads from memory. ```hermesir %0 = GetBuiltinClosureInst %builtinNumber ``` -------------------------------- ### Create C++ Header for Extension Source: https://github.com/facebook/hermes/blob/static_h/API/hermes/extensions/contrib/README.md Declare the C++ function that will install your extension into the Hermes runtime. ```cpp /* * 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. */ #ifndef HERMES_EXTENSIONS_CONTRIB_YOUREXTENSION_H #define HERMES_EXTENSIONS_CONTRIB_YOUREXTENSION_H #include namespace facebook { namespace hermes { void installYourExtension(jsi::Runtime &runtime, jsi::Object &extensions); } // namespace hermes } // namespace facebook #endif ``` -------------------------------- ### Configuration Accessors Source: https://github.com/facebook/hermes/blob/static_h/public/hermes/Public/README.md Example of getter methods generated for accessing fields within a configuration struct. ```cpp size_t FooConfig::getBar() const; std::string FooConfig::getBaz() const; ``` -------------------------------- ### Read from PinnedValue Source: https://github.com/facebook/hermes/blob/static_h/doc/GCSafeCoding.md Access the underlying typed value, dereference for member access, or get as a HermesValue. ```cpp // Get the underlying typed value: JSObject *rawPtr = lv.obj.get(); // or *lv.obj JSObject *rawPtr = *lv.obj; // Dereference to access members: lv.obj->someMethod(); // Get as HermesValue: HermesValue hv = lv.obj.getHermesValue(); ``` -------------------------------- ### Shermes Compilation Command Source: https://github.com/facebook/hermes/blob/static_h/tools/test-runner/DESIGN.md Example of the command used for compiling source code with the Shermes AOT compiler. ```bash shermes -o [-strict] [-O|-O0] ``` -------------------------------- ### Run MiniReact Benchmark with Static Hermes Source: https://github.com/facebook/hermes/blob/static_h/benchmarks/MiniReact/no-objects/README.md Builds and runs the MiniReact benchmark using Static Hermes. This command compiles the benchmark and then executes it with the Static Hermes interpreter. ```bash ~/fbsource/xplat/static_h/benchmarks/MiniReact/no-objects/build.sh && (cd ~/builds/shdebug/; ninja hermesvm shermes && ./bin/shermes -typed -exec -g ~/fbsource/xplat/static_h/benchmarks/MiniReact/no-objects/out/simple.js) ``` -------------------------------- ### Hermes VM Flags Source: https://github.com/facebook/hermes/blob/static_h/utils/testsuite/README.md Example VM flags for running the test262 and CVE test suites with Hermes. ```sh # For hermes VM (running the bytecode) -Xes6-proxy -Xhermes-internal-test-methods -Xmicrotask-queue ``` -------------------------------- ### Build and Run NAPI Unit Tests Source: https://github.com/facebook/hermes/blob/static_h/API/napi/README.md Compile and execute the NAPI unit tests. This command assumes your build directory is set up correctly. ```bash cmake --build --target NapiTests && /unittests/napi/NapiTests ``` -------------------------------- ### Compile and Execute JavaScript Bytecode with Wasm Hermes VM Source: https://github.com/facebook/hermes/blob/static_h/doc/Emscripten.md Compiles 'hello.js' to Hermes bytecode ('hello.hbc') and then executes the bytecode using the Wasm Hermes VM. This shows the two-step execution process. ```shell node ./build-wasm/bin/hermes.js hello.js --emit-binary -out hello.hbc node ./build-wasm/bin/hermes.js hello.hbc ``` -------------------------------- ### Hermes Compiler Flags Source: https://github.com/facebook/hermes/blob/static_h/utils/testsuite/README.md Example compiler flags for running the test262 and CVE test suites with Hermes. ```sh # For hermes compiler -test262 -fno-static-builtins -Xes6-block-scoping -Xenable-tdz ``` -------------------------------- ### TypeContext Constructor Initialization Source: https://github.com/facebook/hermes/blob/static_h/doc/plans/ir-type/ir-type-v2-implementation.md Shows the initial pre-allocation of well-known types within the TypeContext constructor, starting with NoType. ```cpp TypeContext::TypeContext() { // Index 0: NoType entries_.push_back({TypeKind::NoType, {}}); // Index 1: Empty entries_.push_back({TypeKind::Empty, {}}); // Index 2: Uninit entries_.push_back({TypeKind::Uninit, {}}); // ... all primitives and well-known unions ... // Index kAnyTypeId: Union of all JS-observable types // Index kNumericId: Union(Number, BigInt) // ... assert(entries_.size() == kFirstDynamicId); } ``` -------------------------------- ### Run MiniReact Benchmark with Hermes Source: https://github.com/facebook/hermes/blob/static_h/benchmarks/MiniReact/no-objects/README.md Builds and runs the MiniReact benchmark using standard Hermes. This command compiles the benchmark and then executes it with the standard Hermes interpreter. ```bash ~/fbsource/xplat/static_h/benchmarks/MiniReact/no-objects/build.sh && (cd ~/builds/shdebug/; ninja hermesvm hermes && ./bin/hermes -exec -g ~/fbsource/xplat/static_h/benchmarks/MiniReact/no-objects/out/simple-lowered.js) ``` -------------------------------- ### HBCResolveParentEnvironmentInst Source: https://github.com/facebook/hermes/blob/static_h/doc/IR.md Traverses the chain of lexical environments starting from the current function's parent to find a specific environment. ```APIDOC ## HBCResolveParentEnvironmentInst ### Description Traverse the chain of environments starting at the current function's parent to find a given environment. ### Example ``` %0 = HBCResolveParentEnvironmentInst %varScope, %numLevels, %parentScopeParam ``` ### Arguments - **%varScope**: The variable scope to resolve to. - **%numLevels**: The number of scopes up from the current function's parent that the result will be found. - **%parentScopeParam**: Dummy parameter used to model usage of the parent environment. ### Semantics The instruction resolves an environment that is a parent of the current function's environment. ### Effects Does not read or write to memory. ``` -------------------------------- ### Create JavaScript Extension File Source: https://github.com/facebook/hermes/blob/static_h/API/hermes/extensions/contrib/README.md Define the JavaScript entry point for your extension. This function is called by Hermes and receives native helpers. ```javascript /** * 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. */ // YourExtension description extensions.YourExtension = function(nativeHelpers) { // Setup code here // nativeHelpers contains any native functions passed from C++ }; ``` -------------------------------- ### Build and Run Hermes Benchmarks Source: https://github.com/facebook/hermes/blob/static_h/agent-perf/README.md Build the shermes binary using cmake and then run micro benchmarks with the `--json` flag for structured output. This is useful for initial performance checks. ```bash cmake -B cmake-build-release -G Ninja -DCMAKE_BUILD_TYPE=Release cmake --build cmake-build-release --target shermes ``` ```bash agent-perf/tools/run_benchmarks.sh micro --json ``` -------------------------------- ### Run LLVM-lit Wrapper Script Source: https://github.com/facebook/hermes/blob/static_h/external/llvh/utils/lit/README.txt Execute the llvm-lit wrapper script to test LLVM. This command is used after building LLVM tools to ensure proper integration. ```shell /path/to/your/llvm/build/bin/llvm-lit utils/lit/tests ``` -------------------------------- ### Locals and loops with GCScope Source: https://github.com/facebook/hermes/blob/static_h/doc/GCSafeCoding.md Demonstrates using Locals for long-lived values and GCScope for short-lived temporaries within a loop, flushing temporaries each iteration. ```cpp struct : Locals { PinnedValue O; PinnedValue<> elem; PinnedValue sep; } lv; LocalsRAII lraii(runtime, &lv); GCScope gcScope(runtime); // ... auto marker = gcScope.createMarker(); for (uint32_t i = 0; i < len; gcScope.flushToMarker(marker), ++i) { // Temporary handles created inside the loop are flushed each iteration. // Long-lived values stored in lv.* persist across iterations. auto strRes = toString_RJS(runtime, lv.elem); if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; lv.sep = std::move(*strRes); } ``` -------------------------------- ### TypeOfInst: Get Value Type Source: https://github.com/facebook/hermes/blob/static_h/doc/IR.md Implements the JavaScript `typeof` operator. Returns a string representing the type of the given value. ```hermes-ir %0 = TypeOfInst %val ``` -------------------------------- ### List Functions in C++ File Source: https://github.com/facebook/hermes/blob/static_h/CLAUDE.md Lists all functions in a C++ file, sorted by line number. Requires the 'ctags' utility to be installed. ```bash utils/dump-cpp-funcs.sh file.cpp ``` -------------------------------- ### Run Micro-benchmark with Host and Wasm Hermes VMs Source: https://github.com/facebook/hermes/blob/static_h/doc/Emscripten.md Compares the performance of the Wasm Hermes VM against the native host VM by running a JavaScript micro-benchmark. This helps in performance analysis. ```shell # Run the micro-benchmark with the host VM. ./build-host/bin/hermes -w ${HermesSourcePath?}/benchmarks/bench-runner/resource/test-suites/micros/interp-dispatch.js # Run it with the Wasm VM node ./build-wasm/bin/hermes.js -w ${HermesSourcePath?}/benchmarks/bench-runner/resource/test-suites/micros/interp-dispatch.js ``` -------------------------------- ### Build Prettier Plugin Source: https://github.com/facebook/hermes/blob/static_h/tools/hermes-parser/js/prettier-plugin-hermes-parser/CONTRIBUTION.md Run this script to build the Prettier plugin after making modifications. ```bash hermes-parser/js$ ./scripts/build-prettier.sh ``` -------------------------------- ### LIRResolveScopeInst: Resolve Scope by Levels Source: https://github.com/facebook/hermes/blob/static_h/doc/IR.md Traverses the scope chain upwards by a specified number of levels from a starting scope. Does not interact with memory. ```hermes-ir %0 = LIRResolveScopeInst %variablescope, %startScope, %numLevels ``` -------------------------------- ### Assembly: Double to Integer Conversion and Bitwise AND Source: https://github.com/facebook/hermes/blob/static_h/benchmarks/octane/richards-typed/optimization-notes.md Demonstrates the assembly process for converting NaN-boxed doubles to integers for bitwise operations and back. This round-trip incurs overhead. ```asm fjcvtzs w8, d0 ; double → int32 fjcvtzs w9, d1 ; double → int32 and w8, w9, w8 ; actual AND scvtf d0, w8 ; int32 → double ``` -------------------------------- ### Build Configuration with Builder Pattern Source: https://github.com/facebook/hermes/blob/static_h/public/hermes/Public/README.md Use the generated Builder type to create a configuration instance, overriding default values using with methods. ```cpp auto fooConfig = FooConfig::Builder() .withBar(10) .withBaz("Hello, world!") .build(); ``` -------------------------------- ### GetTemplateObjectInst: Get Template Object Source: https://github.com/facebook/hermes/blob/static_h/doc/IR.md Retrieves a template object from the cache or creates a new one if not found. Used for tagged template functions. ```hermes-ir %0 = GetTemplateObjectInst %templateObjID, %dup, %string1, ... ``` -------------------------------- ### Configure Release Build Source: https://github.com/facebook/hermes/blob/static_h/CLAUDE.md Configures a Release build for production, optimized for performance. ```bash cmake -B cmake-build-release -G Ninja -DCMAKE_BUILD_TYPE=Release ```