| // Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file | |
| // for details. All rights reserved. Use of this source code is governed by a | |
| // BSD-style license that can be found in the LICENSE file. | |
| import 'dart:convert'; | |
| import 'dart:io'; | |
| import 'dart:typed_data'; | |
| import 'package:collection/collection.dart'; | |
| const _elfMagic = <int>[0x7f, 0x45, 0x4c, 0x46]; // "\x7fELF" | |
| const _elf32HeaderSize = 52; | |
| const _elf64HeaderSize = 64; | |
| const _elfClassOffset = 4; | |
| const _elfDataOffset = 5; | |
| const _elfClass32 = 1; | |
| const _elfClass64 = 2; | |
| const _elfDataLittleEndian = 1; | |
| const _elf32ProgramHeaderOffsetField = 28; | |
| const _elf64ProgramHeaderOffsetField = 32; | |
| const _elf32ProgramHeaderEntrySizeField = 42; | |
| const _elf64ProgramHeaderEntrySizeField = 54; | |
| const _elf32ProgramHeaderCountField = 44; | |
| const _elf64ProgramHeaderCountField = 56; | |
| const _elf32ProgramHeaderMinSize = 32; | |
| const _elf64ProgramHeaderMinSize = 56; | |
| const _programHeaderTypeField = 0; | |
| const _elfPtNote = 4; | |
| const _elf32SegmentOffsetField = 4; | |
| const _elf64SegmentOffsetField = 8; | |
| const _elf32SegmentFileSizeField = 16; | |
| const _elf64SegmentFileSizeField = 32; | |
| const _elf32SegmentAlignField = 28; | |
| const _elf64SegmentAlignField = 48; | |
| const _noteHeaderSize = 12; | |
| const _noteNameSizeField = 0; | |
| const _noteDescriptorSizeField = 4; | |
| const _noteTypeField = 8; | |
| /// Must stay in sync with `CliBundleNote` in `runtime/bin/main_impl.cc`. | |
| const _cliBundleNoteType = 0x44434c49; // 'DCLI' | |
| const _cliBundleNoteName = <int>[ | |
| 0x44, 0x61, 0x72, 0x74, 0x2e, 0x43, 0x6c, 0x69, 0x2e, 0x76, 0x31, 0x00, // | |
| ]; // "Dart.Cli.v1\0" | |
| const _cliBundleNoteNameLength = 12; | |
| const _cliBundleNoteMagic = <int>[ | |
| 0xdc, 0xdc, 0x44, 0x43, 0x4c, 0x49, 0x00, 0x01, // | |
| ]; | |
| const _descriptorEnabledOffset = 8; | |
| const _descriptorReservedStart = 9; | |
| const _descriptorReservedEnd = 14; | |
| const _descriptorFallbackLengthOffset = 14; | |
| const _descriptorFallbackPathOffset = 16; | |
| const _cliBundleFallbackCapacity = 512; | |
| const _maxFallbackSnapshotPathLength = _cliBundleFallbackCapacity - 1; | |
| const _cliBundleNoteDescriptorSize = | |
| _descriptorFallbackPathOffset + _cliBundleFallbackCapacity; | |
| const _minCliBundleNoteSize = | |
| _noteHeaderSize + _cliBundleNoteNameLength + _cliBundleNoteDescriptorSize; | |
| /// Reads [length] bytes starting at file [offset]. | |
| typedef _ByteSliceReader = Uint8List Function(int offset, int length); | |
| int _alignUp(int value, int alignment) => | |
| (value + alignment - 1) & ~(alignment - 1); | |
| /// Whether the ELF executable at [dartAotRuntimePath] contains an in-place | |
| /// patchable `.note.dart.cli` `PT_NOTE` entry. | |
| bool hasCliBundleNote(String dartAotRuntimePath) { | |
| final file = File(dartAotRuntimePath); | |
| if (!file.existsSync()) { | |
| return false; | |
| } | |
| final handle = file.openSync(); | |
| try { | |
| final fileLength = handle.lengthSync(); | |
| final descriptorOffset = _findCliBundleNoteDescriptorOffset( | |
| fileLength, | |
| (offset, length) { | |
| handle.setPositionSync(offset); | |
| return handle.readSync(length); | |
| }, | |
| ); | |
| return descriptorOffset != null; | |
| } finally { | |
| handle.closeSync(); | |
| } | |
| } | |
| /// Writes a Linux CLI bundle launcher at [outputPath] by copying | |
| /// [dartAotRuntime] and patching its `.note.dart.cli` ELF note in place. | |
| /// | |
| /// Enabling `.note.dart.cli` instructs `dartaotruntime` to load its AOT | |
| /// snapshot from `../lib/libdartaot<name>.so` instead of parsing VM flags, and | |
| /// keeping the marker in an `SHF_ALLOC` `PT_NOTE` ensures it survives `strip` | |
| /// and distro packaging helpers (`dh_strip`, `llvm-strip`). | |
| /// | |
| /// If [fallbackSnapshotRelativePath] is provided (for single-executable | |
| /// bundles), it is embedded as a fallback so renaming the executable still | |
| /// finds the snapshot. It is an error if [fallbackSnapshotRelativePath] exceeds | |
| /// 511 UTF-8 bytes, contains NUL bytes, or if [dartAotRuntime] does not contain | |
| /// a `.note.dart.cli` ELF note. | |
| Future<void> writeCliBundleExecutable( | |
| String dartAotRuntime, | |
| String outputPath, { | |
| String? fallbackSnapshotRelativePath, | |
| }) async { | |
| final fallbackBytes = _encodeFallbackSnapshotPath( | |
| fallbackSnapshotRelativePath, | |
| ); | |
| final executableBytes = await File(dartAotRuntime).readAsBytes(); | |
| final descriptorOffset = _findCliBundleNoteDescriptorOffset( | |
| executableBytes.length, | |
| (offset, length) => | |
| Uint8List.sublistView(executableBytes, offset, offset + length), | |
| ); | |
| if (descriptorOffset == null) { | |
| throw StateError('Missing .note.dart.cli ELF note in $dartAotRuntime'); | |
| } | |
| _patchCliBundleNoteDescriptor( | |
| executableBytes, | |
| descriptorOffset, | |
| fallbackBytes, | |
| ); | |
| await File(outputPath).writeAsBytes(executableBytes); | |
| } | |
| /// Validates and UTF-8 encodes [fallbackSnapshotRelativePath]. | |
| List<int> _encodeFallbackSnapshotPath(String? fallbackSnapshotRelativePath) { | |
| if (fallbackSnapshotRelativePath == null) { | |
| return const <int>[]; | |
| } | |
| final fallbackBytes = utf8.encode(fallbackSnapshotRelativePath); | |
| if (fallbackBytes.length > _maxFallbackSnapshotPathLength) { | |
| throw ArgumentError.value( | |
| fallbackSnapshotRelativePath, | |
| 'fallbackSnapshotRelativePath', | |
| 'Must be at most $_maxFallbackSnapshotPathLength UTF-8 bytes', | |
| ); | |
| } | |
| if (fallbackBytes.contains(0)) { | |
| throw ArgumentError.value( | |
| fallbackSnapshotRelativePath, | |
| 'fallbackSnapshotRelativePath', | |
| 'Must not contain NUL bytes', | |
| ); | |
| } | |
| return fallbackBytes; | |
| } | |
| /// Patches the `.note.dart.cli` descriptor at [descriptorOffset] inside | |
| /// [executableBytes] to enable CLI bundle mode and store [fallbackBytes]. | |
| void _patchCliBundleNoteDescriptor( | |
| Uint8List executableBytes, | |
| int descriptorOffset, | |
| List<int> fallbackBytes, | |
| ) { | |
| final enabledByteOffset = descriptorOffset + _descriptorEnabledOffset; | |
| final reservedStartOffset = descriptorOffset + _descriptorReservedStart; | |
| final reservedEndOffset = descriptorOffset + _descriptorReservedEnd; | |
| final fallbackLengthOffset = | |
| descriptorOffset + _descriptorFallbackLengthOffset; | |
| final fallbackPathStartOffset = | |
| descriptorOffset + _descriptorFallbackPathOffset; | |
| final fallbackPathEndOffset = | |
| fallbackPathStartOffset + _cliBundleFallbackCapacity; | |
| executableBytes[enabledByteOffset] = 1; | |
| executableBytes.fillRange(reservedStartOffset, reservedEndOffset, 0); | |
| ByteData.sublistView( | |
| executableBytes, | |
| fallbackLengthOffset, | |
| fallbackPathStartOffset, | |
| ).setUint16(0, fallbackBytes.length, Endian.little); | |
| executableBytes.fillRange(fallbackPathStartOffset, fallbackPathEndOffset, 0); | |
| executableBytes.setRange( | |
| fallbackPathStartOffset, | |
| fallbackPathStartOffset + fallbackBytes.length, | |
| fallbackBytes, | |
| ); | |
| } | |
| /// Locates the `.note.dart.cli` descriptor inside an ELF binary of length | |
| /// [fileLength], returning its file byte offset or `null` if absent. | |
| int? _findCliBundleNoteDescriptorOffset( | |
| int fileLength, | |
| _ByteSliceReader readSlice, | |
| ) { | |
| final header = _ElfHeader.tryParse(fileLength, readSlice); | |
| if (header == null) { | |
| return null; | |
| } | |
| final noteSegments = _readElfNoteSegments(header, fileLength, readSlice); | |
| if (noteSegments == null) { | |
| return null; | |
| } | |
| for (final segment in noteSegments) { | |
| final descriptorOffset = _findCliBundleNoteInSegment(segment, readSlice); | |
| if (descriptorOffset != null) { | |
| return descriptorOffset; | |
| } | |
| } | |
| return null; | |
| } | |
| /// Parsed fields of a little-endian 32-bit or 64-bit ELF file header | |
| /// (`Elf32_Ehdr` / `Elf64_Ehdr`) needed to read the program header table. | |
| final class _ElfHeader { | |
| final bool is64Bit; | |
| final int programHeaderOffset; | |
| final int programHeaderEntrySize; | |
| final int programHeaderCount; | |
| const _ElfHeader({ | |
| required this.is64Bit, | |
| required this.programHeaderOffset, | |
| required this.programHeaderEntrySize, | |
| required this.programHeaderCount, | |
| }); | |
| /// Total byte length of the program header table. | |
| int get programHeadersByteLength => | |
| programHeaderEntrySize * programHeaderCount; | |
| /// Parses and validates the ELF header at offset 0, returning `null` if the | |
| /// input is not a valid 32-bit or 64-bit little-endian ELF file with an | |
| /// in-bounds program header table. | |
| static _ElfHeader? tryParse(int fileLength, _ByteSliceReader readSlice) { | |
| if (fileLength < _elf32HeaderSize) { | |
| return null; | |
| } | |
| final bytesToRead = fileLength < _elf64HeaderSize | |
| ? fileLength | |
| : _elf64HeaderSize; | |
| final headerBytes = readSlice(0, bytesToRead); | |
| if (headerBytes.length < _elf32HeaderSize) { | |
| return null; | |
| } | |
| final magicView = Uint8List.sublistView(headerBytes, 0, _elfMagic.length); | |
| if (!magicView.equals(_elfMagic)) { | |
| return null; | |
| } | |
| final elfClass = headerBytes[_elfClassOffset]; | |
| final elfData = headerBytes[_elfDataOffset]; | |
| final isLittleEndian = elfData == _elfDataLittleEndian; | |
| final isSupportedClass = elfClass == _elfClass32 || elfClass == _elfClass64; | |
| if (!isLittleEndian || !isSupportedClass) { | |
| return null; | |
| } | |
| final is64Bit = elfClass == _elfClass64; | |
| if (is64Bit && headerBytes.length < _elf64HeaderSize) { | |
| return null; | |
| } | |
| final headerData = ByteData.sublistView(headerBytes); | |
| final programHeaderOffset = is64Bit | |
| ? headerData.getUint64(_elf64ProgramHeaderOffsetField, Endian.little) | |
| : headerData.getUint32(_elf32ProgramHeaderOffsetField, Endian.little); | |
| final programHeaderEntrySize = headerData.getUint16( | |
| is64Bit | |
| ? _elf64ProgramHeaderEntrySizeField | |
| : _elf32ProgramHeaderEntrySizeField, | |
| Endian.little, | |
| ); | |
| final programHeaderCount = headerData.getUint16( | |
| is64Bit ? _elf64ProgramHeaderCountField : _elf32ProgramHeaderCountField, | |
| Endian.little, | |
| ); | |
| final minEntrySize = is64Bit | |
| ? _elf64ProgramHeaderMinSize | |
| : _elf32ProgramHeaderMinSize; | |
| final hasValidHeaderTableOffset = | |
| programHeaderOffset > 0 && programHeaderOffset <= fileLength; | |
| if (!hasValidHeaderTableOffset || | |
| programHeaderCount == 0 || | |
| programHeaderEntrySize < minEntrySize) { | |
| return null; | |
| } | |
| final header = _ElfHeader( | |
| is64Bit: is64Bit, | |
| programHeaderOffset: programHeaderOffset, | |
| programHeaderEntrySize: programHeaderEntrySize, | |
| programHeaderCount: programHeaderCount, | |
| ); | |
| final remainingBytesAfterOffset = fileLength - programHeaderOffset; | |
| if (header.programHeadersByteLength > remainingBytesAfterOffset) { | |
| return null; | |
| } | |
| return header; | |
| } | |
| } | |
| /// File range and note alignment of an ELF `PT_NOTE` segment. | |
| final class _ElfNoteSegment { | |
| final int fileOffset; | |
| final int fileSize; | |
| final int noteAlignment; | |
| const _ElfNoteSegment({ | |
| required this.fileOffset, | |
| required this.fileSize, | |
| required this.noteAlignment, | |
| }); | |
| } | |
| /// Reads the ELF program header table (`Elf32_Phdr` / `Elf64_Phdr`) described | |
| /// by [header] and returns all candidate `PT_NOTE` segments large enough to | |
| /// contain `.note.dart.cli`, or `null` if the table is truncated. | |
| List<_ElfNoteSegment>? _readElfNoteSegments( | |
| _ElfHeader header, | |
| int fileLength, | |
| _ByteSliceReader readSlice, | |
| ) { | |
| final tableLength = header.programHeadersByteLength; | |
| final programHeaders = readSlice(header.programHeaderOffset, tableLength); | |
| if (programHeaders.length < tableLength) { | |
| return null; | |
| } | |
| final programHeadersData = ByteData.sublistView(programHeaders); | |
| final noteSegments = <_ElfNoteSegment>[]; | |
| for (var i = 0; i < header.programHeaderCount; i++) { | |
| final entryBase = i * header.programHeaderEntrySize; | |
| final segmentType = programHeadersData.getUint32( | |
| entryBase + _programHeaderTypeField, | |
| Endian.little, | |
| ); | |
| if (segmentType != _elfPtNote) { | |
| continue; | |
| } | |
| final segmentOffset = header.is64Bit | |
| ? programHeadersData.getUint64( | |
| entryBase + _elf64SegmentOffsetField, | |
| Endian.little, | |
| ) | |
| : programHeadersData.getUint32( | |
| entryBase + _elf32SegmentOffsetField, | |
| Endian.little, | |
| ); | |
| final segmentFileSize = header.is64Bit | |
| ? programHeadersData.getUint64( | |
| entryBase + _elf64SegmentFileSizeField, | |
| Endian.little, | |
| ) | |
| : programHeadersData.getUint32( | |
| entryBase + _elf32SegmentFileSizeField, | |
| Endian.little, | |
| ); | |
| final segmentAlign = header.is64Bit | |
| ? programHeadersData.getUint64( | |
| entryBase + _elf64SegmentAlignField, | |
| Endian.little, | |
| ) | |
| : programHeadersData.getUint32( | |
| entryBase + _elf32SegmentAlignField, | |
| Endian.little, | |
| ); | |
| final isInBounds = | |
| segmentOffset >= 0 && | |
| segmentOffset <= fileLength && | |
| segmentFileSize <= fileLength - segmentOffset; | |
| if (!isInBounds || segmentFileSize < _minCliBundleNoteSize) { | |
| continue; | |
| } | |
| final noteAlignment = segmentAlign == 8 ? 8 : 4; | |
| noteSegments.add( | |
| _ElfNoteSegment( | |
| fileOffset: segmentOffset, | |
| fileSize: segmentFileSize, | |
| noteAlignment: noteAlignment, | |
| ), | |
| ); | |
| } | |
| return noteSegments; | |
| } | |
| /// Scans `Elf32_Nhdr` / `Elf64_Nhdr` records inside [segment] and returns the | |
| /// file byte offset of the `.note.dart.cli` descriptor if present. | |
| /// | |
| /// Each ELF note record consists of three 32-bit words (`namesz`, `descsz`, | |
| /// `type`), followed by the owner name and descriptor each padded to | |
| /// [_ElfNoteSegment.noteAlignment]. | |
| int? _findCliBundleNoteInSegment( | |
| _ElfNoteSegment segment, | |
| _ByteSliceReader readSlice, | |
| ) { | |
| final segmentBytes = readSlice(segment.fileOffset, segment.fileSize); | |
| if (segmentBytes.length < segment.fileSize) { | |
| return null; | |
| } | |
| final segmentData = ByteData.sublistView(segmentBytes); | |
| var noteOffset = 0; | |
| while (noteOffset <= segment.fileSize - _noteHeaderSize) { | |
| final nameSize = segmentData.getUint32( | |
| noteOffset + _noteNameSizeField, | |
| Endian.little, | |
| ); | |
| final descriptorSize = segmentData.getUint32( | |
| noteOffset + _noteDescriptorSizeField, | |
| Endian.little, | |
| ); | |
| final noteType = segmentData.getUint32( | |
| noteOffset + _noteTypeField, | |
| Endian.little, | |
| ); | |
| final nameStart = noteOffset + _noteHeaderSize; | |
| final remainingAfterHeader = segment.fileSize - nameStart; | |
| if (nameSize > remainingAfterHeader) { | |
| break; | |
| } | |
| final nameEnd = nameStart + nameSize; | |
| final descriptorStart = _alignUp(nameEnd, segment.noteAlignment); | |
| if (descriptorStart > segment.fileSize) { | |
| break; | |
| } | |
| final remainingForDescriptor = segment.fileSize - descriptorStart; | |
| if (descriptorSize > remainingForDescriptor) { | |
| break; | |
| } | |
| final hasExpectedMetadata = | |
| noteType == _cliBundleNoteType && | |
| nameSize == _cliBundleNoteName.length && | |
| descriptorSize == _cliBundleNoteDescriptorSize; | |
| if (hasExpectedMetadata) { | |
| final ownerNameBytes = Uint8List.sublistView( | |
| segmentBytes, | |
| nameStart, | |
| nameEnd, | |
| ); | |
| final descriptorMagicEnd = descriptorStart + _cliBundleNoteMagic.length; | |
| final descriptorMagicBytes = Uint8List.sublistView( | |
| segmentBytes, | |
| descriptorStart, | |
| descriptorMagicEnd, | |
| ); | |
| final matchesOwnerName = ownerNameBytes.equals(_cliBundleNoteName); | |
| final matchesDescriptorMagic = descriptorMagicBytes.equals( | |
| _cliBundleNoteMagic, | |
| ); | |
| if (matchesOwnerName && matchesDescriptorMagic) { | |
| return segment.fileOffset + descriptorStart; | |
| } | |
| } | |
| final descriptorEnd = descriptorStart + descriptorSize; | |
| final nextNoteOffset = _alignUp(descriptorEnd, segment.noteAlignment); | |
| if (nextNoteOffset <= noteOffset) { | |
| break; | |
| } | |
| noteOffset = nextNoteOffset; | |
| } | |
| return null; | |
| } |