read static method

DVBinaryPayload? read(
  1. String path
)

The payload in the executable at path, or null when it has none.

Null also for a file that is not a compiled Dart executable, which is what dart run is: a program run from source carries nothing.

Implementation

static DVBinaryPayload? read(String path) {
  final File file = File(path);
  if (!file.existsSync()) return null;
  final RandomAccessFile raf = file.openSync();
  try {
    final int length = raf.lengthSync();
    if (length < 32) return null;
    raf.setPositionSync(length - 16);
    final Uint8List end = raf.readSync(16);
    final ByteData trailer = ByteData.sublistView(end);
    final int start;
    if (ascii.decode(end.sublist(8), allowInvalid: true) == _appendedMagic) {
      // Windows and macOS: after the image.
      start = trailer.getUint64(0, Endian.little);
      if (start > length - 28) return null;
    } else {
      // Linux: between the runtime and the snapshot.
      if (trailer.getUint64(8, Endian.little) != _snapshotMagic) return null;
      final int snapshot = trailer.getUint64(0, Endian.little);
      if (snapshot < 16 || snapshot > length - 16) return null;
      raf.setPositionSync(snapshot - 16);
      final Uint8List locator = raf.readSync(16);
      if (ascii.decode(locator.sublist(8), allowInvalid: true) !=
          _locatorMagic) {
        return null;
      }
      start = ByteData.sublistView(locator).getUint64(0, Endian.little);
    }
    if (start < 0 || start > length - 12) return null;
    raf.setPositionSync(start);
    final Uint8List head = raf.readSync(12);
    if (head.length < 12 ||
        ascii.decode(head.sublist(0, 8), allowInvalid: true) !=
            _payloadMagic) {
      return null;
    }
    final int headerLength =
        ByteData.sublistView(head).getUint32(8, Endian.little);
    final Object? header = jsonDecode(utf8.decode(raf.readSync(headerLength)));
    final Map<String, ({int offset, int length})> sections =
        <String, ({int offset, int length})>{};
    for (final Object? entry in (header as Map)['sections'] as List) {
      final Map<Object?, Object?> section = entry! as Map;
      sections['${section['name']}'] = (
        offset: section['offset']! as int,
        length: section['length']! as int,
      );
    }
    return DVBinaryPayload._(path, start, sections);
  } on FormatException {
    return null;
  } finally {
    raf.closeSync();
  }
}