@ohos-perf/core 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +225 -2
  2. package/dist/index.js +561 -63
  3. package/package.json +48 -48
package/dist/index.d.ts CHANGED
@@ -3613,7 +3613,7 @@ declare class ThreadStateQuery {
3613
3613
  forItids(itids: number[], range?: TimeRange): ThreadState[];
3614
3614
  }
3615
3615
 
3616
- type EvidenceKind = 'no_data' | 'jank' | 'frame_load' | 'empty_frame' | 'vsync_anomaly' | 'fps_baseline' | 'degraded_capability' | 'fault_pattern' | 'binder_hotspot' | 'thread_redundancy' | 'memory_growth' | 'native_memory' | 'hilog_match' | 'gc_pressure' | 'rs_skip' | 'startup' | 'ui_tree' | 'tech_stack' | 'duplicate_asset' | 'oversized_asset' | 'symbol_stats' | 'unresolved_symbol' | 'redundant_file' | 'coverage';
3616
+ type EvidenceKind = 'no_data' | 'jank' | 'frame_load' | 'empty_frame' | 'vsync_anomaly' | 'fps_baseline' | 'degraded_capability' | 'fault_pattern' | 'binder_hotspot' | 'thread_redundancy' | 'memory_growth' | 'native_memory' | 'hilog_match' | 'gc_pressure' | 'rs_skip' | 'startup' | 'ui_tree' | 'tech_stack' | 'duplicate_asset' | 'oversized_asset' | 'symbol_stats' | 'unresolved_symbol' | 'redundant_file' | 'coverage' | 'optimization';
3617
3617
  /**
3618
3618
  * A follow-up query an agent can issue to drill into an evidence item.
3619
3619
  *
@@ -6185,6 +6185,229 @@ declare function isZip(bytes: Uint8Array): boolean;
6185
6185
  /** Read the central directory and return an archive over `bytes`. */
6186
6186
  declare function openZip(bytes: Uint8Array): ZipArchive;
6187
6187
 
6188
+ /**
6189
+ * A reader for the ELF headers, sections and symbols of an OHOS native binary.
6190
+ *
6191
+ * This exists for HapRay parity row 27. HapRay's `opt-detector` answers "what
6192
+ * optimization level was this built at, and was LTO on?" by feeding raw
6193
+ * `.text` bytes to a ~2 GB LSTM and a 551-feature SVM and printing the guess
6194
+ * as a percentage. An ELF records much of that directly — LTO leaves
6195
+ * `lto_priv.*` symbols and `.gnu.lto_*` sections, `-O0` leaves debug
6196
+ * sections, and the instruction mix is a fact about the bytes — so the
6197
+ * analyzer built on this reader reports what the file says and labels the
6198
+ * parts that are inference.
6199
+ *
6200
+ * What is here is deliberately narrow: the section header table, the two
6201
+ * symbol tables, and a decoder for the AArch64 instruction classes whose
6202
+ * density differs across optimization levels. There is no program-header
6203
+ * walk, no relocation processing, no dynamic-section parsing and no
6204
+ * disassembly — nothing this reader does not have a caller for.
6205
+ *
6206
+ * ## Refusals
6207
+ *
6208
+ * Every read is bounds-checked against the buffer, because a `.so` shipped
6209
+ * inside an app is attacker-controlled input as far as this package is
6210
+ * concerned. A bad magic, a short header, an unsupported class and a section
6211
+ * table pointing past the end are typed refusals naming the field, not bare
6212
+ * `RangeError`s from a `DataView`.
6213
+ */
6214
+ /** `e_machine` for AArch64, the only machine an OHOS app ships. */
6215
+ declare const EM_AARCH64 = 183;
6216
+ /** One section header, as much of it as a caller here needs. */
6217
+ interface ElfSection {
6218
+ readonly name: string;
6219
+ readonly type: number;
6220
+ readonly flags: number;
6221
+ /** Offset of the payload in the file. */
6222
+ readonly offset: number;
6223
+ /** Declared size. A `NOBITS` section declares one but occupies no bytes. */
6224
+ readonly size: number;
6225
+ /** Entry size for a table section (`sh_entsize`), else 0. */
6226
+ readonly entrySize: number;
6227
+ }
6228
+ /** One symbol, with the binding and type decoded from `st_info`. */
6229
+ interface ElfSymbol {
6230
+ readonly name: string;
6231
+ readonly bind: 'local' | 'global' | 'weak' | 'other';
6232
+ readonly type: 'notype' | 'func' | 'object' | 'section' | 'file' | 'other';
6233
+ readonly size: number;
6234
+ /** Section index the symbol belongs to; 0 for undefined, 0xfff1 for absolute. */
6235
+ readonly sectionIndex: number;
6236
+ }
6237
+ interface ElfFile {
6238
+ readonly bits: 32 | 64;
6239
+ readonly endian: 'little' | 'big';
6240
+ readonly machine: number;
6241
+ /** `e_type`: 1 relocatable, 2 executable, 3 shared object, 4 core. */
6242
+ readonly type: number;
6243
+ readonly sections: readonly ElfSection[];
6244
+ readonly symbols: readonly ElfSymbol[];
6245
+ /** The section with this name, or `undefined`. */
6246
+ readonly section: (name: string) => ElfSection | undefined;
6247
+ /** The payload of a section; empty for `NOBITS` and for a missing section. */
6248
+ readonly bytesOf: (name: string) => Uint8Array;
6249
+ }
6250
+ /**
6251
+ * Read an ELF's headers, sections and symbols.
6252
+ *
6253
+ * Only 64-bit little-endian is decoded. The class and endianness are read
6254
+ * first and refused by name, so a 32-bit or big-endian file gets a message
6255
+ * saying which shape was unsupported rather than a nonsensical section table.
6256
+ */
6257
+ declare function readElf(bytes: Uint8Array): ElfFile;
6258
+ /** The instruction classes whose density differs across optimization levels. */
6259
+ type InstructionClass = 'ret' | 'blr' | 'br' | 'bl' | 'b' | 'bcond' | 'cbz' | 'tbz' | 'adrp' | 'adr' | 'ldr' | 'str' | 'add' | 'vector' | 'other';
6260
+ /** Per-class instruction counts over a `.text` payload. */
6261
+ type InstructionCounts = Record<InstructionClass, number> & {
6262
+ total: number;
6263
+ };
6264
+ /**
6265
+ * Classify one AArch64 instruction word.
6266
+ *
6267
+ * The masks are the ARM ARM's fixed-field encodings for the classes whose
6268
+ * frequency a compiler changes: `ret`/`blr`/`br` (branch-register), `bl`/`b`
6269
+ * (immediate branch), `b.cond`, `cbz`/`cbnz`, `tbz`/`tbnz`, `adrp`/`adr`, and
6270
+ * the SIMD group. `other` covers everything else, which is most arithmetic.
6271
+ *
6272
+ * The order matters: `br`/`blr`/`ret` share a mask and are separated by their
6273
+ * `opc` field, and `b`/`bl` share a mask separated by bit 31.
6274
+ */
6275
+ declare function classifyInstruction(word: number): InstructionClass;
6276
+ /**
6277
+ * Count instruction classes over a payload.
6278
+ *
6279
+ * A trailing partial word is not an instruction and is not counted; a section
6280
+ * whose size is not a multiple of four is legal padding.
6281
+ */
6282
+ declare function countInstructions(payload: Uint8Array): InstructionCounts;
6283
+
6284
+ /**
6285
+ * Optimization-level and LTO detection for an OHOS native binary (HapRay
6286
+ * parity row 27).
6287
+ *
6288
+ * HapRay's `opt-detector` answers two questions — "which `-O` level was this
6289
+ * built at?" and "was LTO on?" — by feeding raw `.text` bytes to a ~2 GB
6290
+ * TensorFlow LSTM and a 551-feature SVM, then printing the guess as a
6291
+ * percentage. Its own source records the accuracy: at the threshold it ships,
6292
+ * low-optimization binaries are misreported 16.7% of the time, and the model
6293
+ * is AArch64-only.
6294
+ *
6295
+ * This does not ship that model. It reads the ELF instead, because the ELF
6296
+ * records several of the answers:
6297
+ *
6298
+ * - **LTO** leaves `lto_priv.*` symbols (GCC's own bookkeeping for a symbol
6299
+ * that survived link-time optimization with local visibility) and
6300
+ * `.gnu.lto_*` sections. Their presence is evidence; their absence from a
6301
+ * file that still has a symbol table is evidence of absence. A stripped file
6302
+ * with no symbol table is `unknown`, not `absent` — the markers may simply
6303
+ * have been removed.
6304
+ * - **The `-O` level** is recorded in `.comment` when the toolchain writes it.
6305
+ * That is the compiler's own statement, so it wins over any inference.
6306
+ * - **The instruction mix** is a fact about the bytes: SIMD density, branch
6307
+ * density and call/return balance all shift with optimization. When nothing
6308
+ * recorded the level, the mix produces a verdict labelled `inferred`, with
6309
+ * the signals named so a reader can disagree with it.
6310
+ *
6311
+ * What is never done is presenting an inference as a measurement. The
6312
+ * `fidelity` on each metric says which it is.
6313
+ */
6314
+
6315
+ /** One binary to inspect: its archive-relative path and its bytes. */
6316
+ interface BinaryInput {
6317
+ readonly path: string;
6318
+ readonly bytes: Uint8Array;
6319
+ }
6320
+ /** What the ELF itself records, before any judgement is applied. */
6321
+ interface BinaryFacts {
6322
+ readonly path: string;
6323
+ readonly size: number;
6324
+ readonly machine: number;
6325
+ /** Bytes of the `.text` section; 0 when the file has none. */
6326
+ readonly textBytes: number;
6327
+ readonly instructions: InstructionCounts;
6328
+ /**
6329
+ * `present` when an LTO marker was found, `absent` when a symbol table
6330
+ * exists and none was, `unknown` when there is no symbol table to search.
6331
+ */
6332
+ readonly lto: 'present' | 'absent' | 'unknown';
6333
+ /** The symbols and sections that proved LTO, in the order they were found. */
6334
+ readonly ltoMarkers: readonly string[];
6335
+ readonly debug: boolean;
6336
+ readonly debugSections: readonly string[];
6337
+ /** NUL-separated strings from `.comment`, in file order. */
6338
+ readonly compiler: readonly string[];
6339
+ /** `-O` flags the build recorded, in file order. */
6340
+ readonly recordedFlags: readonly string[];
6341
+ readonly symbols: {
6342
+ readonly functions: number;
6343
+ readonly global: number;
6344
+ readonly local: number;
6345
+ readonly weak: number;
6346
+ };
6347
+ /** True when no function symbol survived, so symbol-level LTO evidence is gone. */
6348
+ readonly stripped: boolean;
6349
+ }
6350
+ type OptimizationLevel = 'unoptimized' | 'low' | 'medium' | 'high' | 'unknown';
6351
+ /** How a level was decided: the compiler said so, or the mix was read. */
6352
+ type OptimizationBasis = 'recorded' | 'inferred' | 'none';
6353
+ interface OptimizationVerdict {
6354
+ readonly level: OptimizationLevel;
6355
+ readonly basis: OptimizationBasis;
6356
+ /** The signals that produced an `inferred` verdict; empty otherwise. */
6357
+ readonly signals: readonly string[];
6358
+ }
6359
+ /** One inspected binary, with the facts and the verdict kept apart. */
6360
+ interface BinaryReport {
6361
+ readonly path: string;
6362
+ readonly facts: BinaryFacts;
6363
+ readonly verdict: OptimizationVerdict;
6364
+ }
6365
+ interface OptimizationAnalysis {
6366
+ readonly schemaVersion: 1;
6367
+ readonly package: string;
6368
+ readonly binaries: readonly BinaryReport[];
6369
+ readonly totals: {
6370
+ readonly binaries: number;
6371
+ readonly lto: number;
6372
+ readonly debug: number;
6373
+ readonly stripped: number;
6374
+ };
6375
+ readonly metrics: Metric[];
6376
+ readonly evidence: Evidence[];
6377
+ }
6378
+ /**
6379
+ * Inspect one ELF.
6380
+ *
6381
+ * A refusal names the binary, because a package holds many and "not an ELF"
6382
+ * alone would not say which one the caller has to look at.
6383
+ */
6384
+ declare function inspectBinary(input: BinaryInput): BinaryFacts;
6385
+ /**
6386
+ * Decide the optimization level, preferring what the compiler recorded.
6387
+ *
6388
+ * The inference is deliberately coarse: three signals, two thresholds. A
6389
+ * richer model would be a guess dressed as a measurement, which is the defect
6390
+ * this row exists to fix.
6391
+ */
6392
+ declare function classifyOptimization(facts: BinaryFacts): OptimizationVerdict;
6393
+ /**
6394
+ * Pull the arm64 shared objects out of a package, or take a bare `.so`.
6395
+ *
6396
+ * An `ar` archive is refused by name: it is a third container format, and
6397
+ * returning an empty report for one would read as "no optimizations found"
6398
+ * when the truth is "this package did not look".
6399
+ */
6400
+ declare function extractBinaries(input: BinaryInput): BinaryInput[];
6401
+ /**
6402
+ * Measure every binary and summarise the package.
6403
+ *
6404
+ * Binaries are sorted by path, and every number is derived from the bytes, so
6405
+ * two runs over the same package produce the same document.
6406
+ */
6407
+ declare function analyzeBinaries(inputs: readonly BinaryInput[], packageName: string): OptimizationAnalysis;
6408
+ /** Wrap an analysis as the `optimization` section the report renderer takes. */
6409
+ declare function optimizationSection(analysis: OptimizationAnalysis): AnalyzerSection;
6410
+
6188
6411
  type FileCategory = 'images' | 'videos' | 'audio' | 'fonts' | 'scripts' | 'styles' | 'binaries' | 'bytecode' | 'data' | 'other';
6189
6412
  /** One archive entry, measured. Paths are archive names, forward slashes. */
6190
6413
  interface InventoryFile {
@@ -6432,4 +6655,4 @@ interface FlamegraphPageInput {
6432
6655
  */
6433
6656
  declare function renderFlamegraphHtml(input: FlamegraphPageInput): string;
6434
6657
 
6435
- export { ANIMATION_BANDS, type ActionContext, type ActionDevice, type ActionOutcome, type ActiveAlloc, type AnalyzeContext, type AnalyzeResult, type Analyzer, type AnalyzerRun, type AnalyzerSection, type AnimationAnalysis, type AnimationLabel, type AnimationSeverity, type AppIdentity, BUNDLE_RENDERED_FILES, type BaselineComparison, type BelowThresholdPattern, type BinderAnalysis, BinderAnalyzer, type BinderEndpoint, type BinderEvent, type BinderInterfaceStat, type BinderProcessStat, BinderQuery, type BinderThreadStat, type BinderTransaction, type BundleRerenderInput, CATEGORY_EXTENSIONS, CATEGORY_MAX_BYTES, COLLECTOR_NAMES, type CallchainSample, type CallstackEvent, type CallstackEventWithArgs, CallstackQuery, type CapabilityId, type CapabilityInputs, CapabilityMatrix, type CapabilityState, type CaseLoad, type CategoryTotal, type CollectOptions, type CollectSession, type Collector, type CollectorName, type CompiledRule, type ComponentReuse, ComponentReuseAnalyzer, type ConnectOptions, type ContentPattern, CoverageAnalyzer, type CoverageCounts, type CoverageFile, type CoverageRatio, type CoverageReport, type CreateEmulatorRequest, DEFAULT_HILOG_RULES, DEFAULT_QUERY_LIMIT, DEVICE_PERF_PATH, DEVICE_SCREENSHOT_PATH, DEVICE_UI_PATH, type DeltaStatus, type DepGraph, type DepGraphEdge, type DepGraphFile, Device, type DeviceDeps, type DeviceIdentity, DeviceNotFoundError, type DiscoveredCase, type DrillDownHandle, type DuplicateGroup, EXCLUDE_PATTERNS, EmptyFrameAnalyzer, type EmptyFrameFilter, type EmulatorBackend, EmulatorClient, type EmulatorClientOptions, EmulatorCommandError, type EmulatorImage, EmulatorImageMissingError, type EmulatorInstance, EmulatorLifecycle, type EmulatorLifecycleOptions, EmulatorNotFoundError, type EmulatorStartResult, type EmulatorStopResult, type Env, type Evidence, type EvidenceKind, type ExpectPresent, type ExpectationOutcome, type ExplorationAction, type ExplorationClock, type ExplorationDevice, type ExplorationDeviceOptions, type ExplorationHost, type ExplorationOptions, type ExplorationOutcome, type ExplorationResult, type ExplorationState, type ExplorationStep, type ExplorationStrategy, type ExplorationTargetDevice, FLAMEGRAPH_FILES, FPS_COMMAND, FTRACE_CATEGORIES, FaultTreeAnalyzer, type FaultTreeSignals, type Fidelity, type FileCategory, type FileRule, FlamegraphAnalyzer, type FlamegraphPageInput, type FoldedStack, type FpsBucket, type FpsWindow, type Frame, FrameAnalyzer, type FrameFlag, FrameLoadAnalyzer, FrameLoadIndex, type FrameLoadIndexInput, type FrameLoadThread, FrameQuery, type FrameStats, type FrameType, type FtraceOptions, GEOMETRY_TOLERANCE_PX, GcAnalyzer, type GcSignals, type Gesture, GestureDriver, type GestureResult, HILOG_COMMAND, HIPROFILER_PLUGIN_NAMES, HITCH_COMMAND, HITRACE_DEFAULT_CATEGORIES, type HapAnalysis, type HapPackage, type HarEdge, Hdc, HdcNotFoundError, type HdcOptions, type HdcResult, type HdcSlice, type HdcTarget, type HidumperCapture, HidumperCollector, type HidumperSnapshot, HilogAnalyzer, HilogCollector, type HilogLevel, type HilogLine, type HilogMatch, type HilogParseOptions, type HilogRule, type HiperfCapture, type HiperfCollectOptions, HiperfCollector, type HiprofilerCollectOptions, type HiprofilerCollectRequest, HiprofilerCollector, type HiprofilerConfigOptions, type HiprofilerPlugin, type HiprofilerPluginName, HitraceCollector, IGNORED_ATTRIBUTES, type ImageComparison, IngestError, InstantQuery, type InventoryFile, type JsheapCapture, JsheapCollector, MAX_QUERY_LIMIT, METRIC_DIRECTIONS, MIN_BUFFER_PAGES, MIN_HASH_PIXELS, MemMeasureQuery, MemoryAnalyzer, MemoryMeasureAnalyzer, type MemoryPluginOptions, type MetadataPattern, type Metric, type MetricDelta, type MetricDirection, type MetricUnit, type ModuleDecl, type NamedQueryDefinition, type NamedQueryInfo, type NamedQueryResult, type NativeCategory, type NativeEventKind, type NativeHookEvent, type NativeHookFrame, NativeHookQuery, type NativeHookStatistic, NativeMemoryAnalyzer, type NativeMemoryResult, type NativeNames, type NativeTimelineBucket, type NativehookOptions, OhosPerfError, type OptimizationPotential, type OversizedFile, PARITY_ROWS, PLANE_A_PLUGINS, type ParityRow, type ParityStatus, type PerfCallchain, type PerfFileAttribution, type PerfFunction, type PerfLeafAttribution, PerfQuery, type PerfSampleRow, type PerfThread, type PixelOnlyChange, type ProbeResult, type ProbeRunner, type ProbeSnapshot, type ProcessInfo, type ProcessMeasure, type ProcessMeasureFilter, ProcessQuery, ProcfsCollector, type ProcfsSample, type ProcfsStatus, type Provenance, type QueryArgument, type QueryContext, type QueryHandle, REPORT_SCHEMA_VERSION, type Rect, type RedundancyLevel, type RedundancyType, RedundantFileAnalyzer, type RedundantFileEntry, type RedundantFileReport, type RedundantThreadPattern, type RedundantThreadsSummary, type RegionPixelChange, RenderAnalyzer, type ReportGenerator, type ReportInput, type ReportModel, type ReportScenario, type ReportSection, type ReportSummary, type ReportTotals, type RgbaImage, RsSkipAnalyzer, type RsSkipFrame, type RsSkipResult, type RsSkipTraceMethod, type RuleMatch, type RuleMatchKind, type RunOptions, type RunResult, type RunStepResult, type RunnerCollectOptions, type RunnerDevice, SECTION_TITLES, type Scenario, type ScenarioAction, ScenarioRunner, type ScenarioStep, Scene, type SceneLayout, type SceneMetadata, type SceneStep, type SceneStepRef, type ScenesComparison, SchedQuery, type SchedSlice, type ScreenshotCapture, ScreenshotCollector, type Selector, type SelectorRect, type SmapsRollup, StartupAnalyzer, StartupQuery, type StartupRecord, type StepCapture, type StepComparison, type StepExpectation, type StepStatus, Streamer, StreamerNotFoundError, type StreamerOptions, type SymbolStat, SymbolsAnalyzer, TECH_RULES, type TechRule, type ThreadAnalysis, type ThreadAnalysisSummary, ThreadAnalyzer, type ThreadInfo, ThreadQuery, type ThreadState, ThreadStateQuery, type ThreadWakeupResult, type ThreadWakeupThread, type TimeRange, type TimingCycle, type TraceCollectOptions, type Trend, type TrendOrder, type TrendPoint, type TrendRun, type TrendSeries, UI_DIFF_FILES, UiAnalyzer, type UiCompareOptions, type UiDiff, type UiDiffSide, type UiNode, type UiTreeDiff, type UiTreeDifference, UitestCollector, type UnmeasuredRegion, type UnreleasedRow, type VsyncAnalysis, VsyncAnalyzer, type VsyncPeriod, type VsyncPeriodKind, type VsyncSeverity, type WakeupEvent, type WindowHitches, type ZipArchive, type ZipEntry, aggregateUnreleased, analyseAnimations, analyzeHap, analyzeThreadWakeup, animationSeverity, buildDepGraph, buildHiprofilerConfig, buildInventory, buildMatrix, buildNativeTimeline, buildReport, buildTrend, categorize, classifyNativePath, compareImages, compareRegion, compareResults, compareSceneDirs, compareScenes, compileRules, computeBinderAnalysis, computeComponentReuse, computeFaultTree, computeFpsWindows, computeGc, computeRsSkip, computeThreadAnalysis, computeVsyncAnomalies, connect, createSceneLayout, cropRegion, decodePng, defaultAnalyzers, deviceExplorationHost, dhash, diffTrees, discoverCases, encodePng, escapeHtml, evidence, executeAction, explorationDevice, explore, filterEmptyFrames, flattenUiTree, ftracePlugin, gpuPlugin, hapSection, hashTree, hiperfRecordCommand, ingestScene, isUnresolvedSymbol, isZip, loadCases, lookupQuery, markRegions, matchHapRules, matchRules, matchSelector, memoryPlugin, metric, nativeEventKind, nativehookPlugin, nodeIdentity, openDb, openZip, pairNativeMemory, paritySummary, parseBounds, parseCoverageReport, parseFpsCounts, parseHilogLine, parseHilogText, parseHiperfSummary, parseHitches, parseProcfsStatus, parseRedundantFile, parseScenario, parseSelector, parseSmapsRollup, planNextAction, queryDefinitions, readHidumperCapture, readHilogText, readJsheapSnapshot, readProcfsSamples, readSceneMetadata, readUiTree, renderBundle, renderEvidenceCsv, renderFlamegraphHtml, renderFlamegraphSvg, renderMetricsCsv, renderReportHtml, renderReportJson, renderReportXlsx, renderScenesComparison, renderSummaryJson, renderTrendHtml, renderTrendJson, renderUiDiffHtml, resolveAppIdentity, resolveAppIpids, resolveQueryLimit, resolveSelector, round2HalfEven, runAnalyzerSections, runAnalyzers, runDrillDown, runNamedQuery, runProbe, sortSteps, summarizeReport, tableRowCounts, trendRunFromReport, unknownQueryError, validateRules, writeProcfsSamples, writeRunFiles, writeSceneMetadata, xpowerPlugin };
6658
+ export { ANIMATION_BANDS, type ActionContext, type ActionDevice, type ActionOutcome, type ActiveAlloc, type AnalyzeContext, type AnalyzeResult, type Analyzer, type AnalyzerRun, type AnalyzerSection, type AnimationAnalysis, type AnimationLabel, type AnimationSeverity, type AppIdentity, BUNDLE_RENDERED_FILES, type BaselineComparison, type BelowThresholdPattern, type BinaryFacts, type BinaryInput, type BinaryReport, type BinderAnalysis, BinderAnalyzer, type BinderEndpoint, type BinderEvent, type BinderInterfaceStat, type BinderProcessStat, BinderQuery, type BinderThreadStat, type BinderTransaction, type BundleRerenderInput, CATEGORY_EXTENSIONS, CATEGORY_MAX_BYTES, COLLECTOR_NAMES, type CallchainSample, type CallstackEvent, type CallstackEventWithArgs, CallstackQuery, type CapabilityId, type CapabilityInputs, CapabilityMatrix, type CapabilityState, type CaseLoad, type CategoryTotal, type CollectOptions, type CollectSession, type Collector, type CollectorName, type CompiledRule, type ComponentReuse, ComponentReuseAnalyzer, type ConnectOptions, type ContentPattern, CoverageAnalyzer, type CoverageCounts, type CoverageFile, type CoverageRatio, type CoverageReport, type CreateEmulatorRequest, DEFAULT_HILOG_RULES, DEFAULT_QUERY_LIMIT, DEVICE_PERF_PATH, DEVICE_SCREENSHOT_PATH, DEVICE_UI_PATH, type DeltaStatus, type DepGraph, type DepGraphEdge, type DepGraphFile, Device, type DeviceDeps, type DeviceIdentity, DeviceNotFoundError, type DiscoveredCase, type DrillDownHandle, type DuplicateGroup, EM_AARCH64, EXCLUDE_PATTERNS, type ElfFile, type ElfSection, type ElfSymbol, EmptyFrameAnalyzer, type EmptyFrameFilter, type EmulatorBackend, EmulatorClient, type EmulatorClientOptions, EmulatorCommandError, type EmulatorImage, EmulatorImageMissingError, type EmulatorInstance, EmulatorLifecycle, type EmulatorLifecycleOptions, EmulatorNotFoundError, type EmulatorStartResult, type EmulatorStopResult, type Env, type Evidence, type EvidenceKind, type ExpectPresent, type ExpectationOutcome, type ExplorationAction, type ExplorationClock, type ExplorationDevice, type ExplorationDeviceOptions, type ExplorationHost, type ExplorationOptions, type ExplorationOutcome, type ExplorationResult, type ExplorationState, type ExplorationStep, type ExplorationStrategy, type ExplorationTargetDevice, FLAMEGRAPH_FILES, FPS_COMMAND, FTRACE_CATEGORIES, FaultTreeAnalyzer, type FaultTreeSignals, type Fidelity, type FileCategory, type FileRule, FlamegraphAnalyzer, type FlamegraphPageInput, type FoldedStack, type FpsBucket, type FpsWindow, type Frame, FrameAnalyzer, type FrameFlag, FrameLoadAnalyzer, FrameLoadIndex, type FrameLoadIndexInput, type FrameLoadThread, FrameQuery, type FrameStats, type FrameType, type FtraceOptions, GEOMETRY_TOLERANCE_PX, GcAnalyzer, type GcSignals, type Gesture, GestureDriver, type GestureResult, HILOG_COMMAND, HIPROFILER_PLUGIN_NAMES, HITCH_COMMAND, HITRACE_DEFAULT_CATEGORIES, type HapAnalysis, type HapPackage, type HarEdge, Hdc, HdcNotFoundError, type HdcOptions, type HdcResult, type HdcSlice, type HdcTarget, type HidumperCapture, HidumperCollector, type HidumperSnapshot, HilogAnalyzer, HilogCollector, type HilogLevel, type HilogLine, type HilogMatch, type HilogParseOptions, type HilogRule, type HiperfCapture, type HiperfCollectOptions, HiperfCollector, type HiprofilerCollectOptions, type HiprofilerCollectRequest, HiprofilerCollector, type HiprofilerConfigOptions, type HiprofilerPlugin, type HiprofilerPluginName, HitraceCollector, IGNORED_ATTRIBUTES, type ImageComparison, IngestError, InstantQuery, type InstructionClass, type InstructionCounts, type InventoryFile, type JsheapCapture, JsheapCollector, MAX_QUERY_LIMIT, METRIC_DIRECTIONS, MIN_BUFFER_PAGES, MIN_HASH_PIXELS, MemMeasureQuery, MemoryAnalyzer, MemoryMeasureAnalyzer, type MemoryPluginOptions, type MetadataPattern, type Metric, type MetricDelta, type MetricDirection, type MetricUnit, type ModuleDecl, type NamedQueryDefinition, type NamedQueryInfo, type NamedQueryResult, type NativeCategory, type NativeEventKind, type NativeHookEvent, type NativeHookFrame, NativeHookQuery, type NativeHookStatistic, NativeMemoryAnalyzer, type NativeMemoryResult, type NativeNames, type NativeTimelineBucket, type NativehookOptions, OhosPerfError, type OptimizationAnalysis, type OptimizationBasis, type OptimizationLevel, type OptimizationPotential, type OptimizationVerdict, type OversizedFile, PARITY_ROWS, PLANE_A_PLUGINS, type ParityRow, type ParityStatus, type PerfCallchain, type PerfFileAttribution, type PerfFunction, type PerfLeafAttribution, PerfQuery, type PerfSampleRow, type PerfThread, type PixelOnlyChange, type ProbeResult, type ProbeRunner, type ProbeSnapshot, type ProcessInfo, type ProcessMeasure, type ProcessMeasureFilter, ProcessQuery, ProcfsCollector, type ProcfsSample, type ProcfsStatus, type Provenance, type QueryArgument, type QueryContext, type QueryHandle, REPORT_SCHEMA_VERSION, type Rect, type RedundancyLevel, type RedundancyType, RedundantFileAnalyzer, type RedundantFileEntry, type RedundantFileReport, type RedundantThreadPattern, type RedundantThreadsSummary, type RegionPixelChange, RenderAnalyzer, type ReportGenerator, type ReportInput, type ReportModel, type ReportScenario, type ReportSection, type ReportSummary, type ReportTotals, type RgbaImage, RsSkipAnalyzer, type RsSkipFrame, type RsSkipResult, type RsSkipTraceMethod, type RuleMatch, type RuleMatchKind, type RunOptions, type RunResult, type RunStepResult, type RunnerCollectOptions, type RunnerDevice, SECTION_TITLES, type Scenario, type ScenarioAction, ScenarioRunner, type ScenarioStep, Scene, type SceneLayout, type SceneMetadata, type SceneStep, type SceneStepRef, type ScenesComparison, SchedQuery, type SchedSlice, type ScreenshotCapture, ScreenshotCollector, type Selector, type SelectorRect, type SmapsRollup, StartupAnalyzer, StartupQuery, type StartupRecord, type StepCapture, type StepComparison, type StepExpectation, type StepStatus, Streamer, StreamerNotFoundError, type StreamerOptions, type SymbolStat, SymbolsAnalyzer, TECH_RULES, type TechRule, type ThreadAnalysis, type ThreadAnalysisSummary, ThreadAnalyzer, type ThreadInfo, ThreadQuery, type ThreadState, ThreadStateQuery, type ThreadWakeupResult, type ThreadWakeupThread, type TimeRange, type TimingCycle, type TraceCollectOptions, type Trend, type TrendOrder, type TrendPoint, type TrendRun, type TrendSeries, UI_DIFF_FILES, UiAnalyzer, type UiCompareOptions, type UiDiff, type UiDiffSide, type UiNode, type UiTreeDiff, type UiTreeDifference, UitestCollector, type UnmeasuredRegion, type UnreleasedRow, type VsyncAnalysis, VsyncAnalyzer, type VsyncPeriod, type VsyncPeriodKind, type VsyncSeverity, type WakeupEvent, type WindowHitches, type ZipArchive, type ZipEntry, aggregateUnreleased, analyseAnimations, analyzeBinaries, analyzeHap, analyzeThreadWakeup, animationSeverity, buildDepGraph, buildHiprofilerConfig, buildInventory, buildMatrix, buildNativeTimeline, buildReport, buildTrend, categorize, classifyInstruction, classifyNativePath, classifyOptimization, compareImages, compareRegion, compareResults, compareSceneDirs, compareScenes, compileRules, computeBinderAnalysis, computeComponentReuse, computeFaultTree, computeFpsWindows, computeGc, computeRsSkip, computeThreadAnalysis, computeVsyncAnomalies, connect, countInstructions, createSceneLayout, cropRegion, decodePng, defaultAnalyzers, deviceExplorationHost, dhash, diffTrees, discoverCases, encodePng, escapeHtml, evidence, executeAction, explorationDevice, explore, extractBinaries, filterEmptyFrames, flattenUiTree, ftracePlugin, gpuPlugin, hapSection, hashTree, hiperfRecordCommand, ingestScene, inspectBinary, isUnresolvedSymbol, isZip, loadCases, lookupQuery, markRegions, matchHapRules, matchRules, matchSelector, memoryPlugin, metric, nativeEventKind, nativehookPlugin, nodeIdentity, openDb, openZip, optimizationSection, pairNativeMemory, paritySummary, parseBounds, parseCoverageReport, parseFpsCounts, parseHilogLine, parseHilogText, parseHiperfSummary, parseHitches, parseProcfsStatus, parseRedundantFile, parseScenario, parseSelector, parseSmapsRollup, planNextAction, queryDefinitions, readElf, readHidumperCapture, readHilogText, readJsheapSnapshot, readProcfsSamples, readSceneMetadata, readUiTree, renderBundle, renderEvidenceCsv, renderFlamegraphHtml, renderFlamegraphSvg, renderMetricsCsv, renderReportHtml, renderReportJson, renderReportXlsx, renderScenesComparison, renderSummaryJson, renderTrendHtml, renderTrendJson, renderUiDiffHtml, resolveAppIdentity, resolveAppIpids, resolveQueryLimit, resolveSelector, round2HalfEven, runAnalyzerSections, runAnalyzers, runDrillDown, runNamedQuery, runProbe, sortSteps, summarizeReport, tableRowCounts, trendRunFromReport, unknownQueryError, validateRules, writeProcfsSamples, writeRunFiles, writeSceneMetadata, xpowerPlugin };
package/dist/index.js CHANGED
@@ -1836,8 +1836,8 @@ function readChunk(bytes, offset) {
1836
1836
  if (offset + 8 > bytes.length) {
1837
1837
  throw bad("PNG_TRUNCATED", `PNG is truncated at byte ${offset}: no chunk header`);
1838
1838
  }
1839
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1840
- const length = view.getUint32(offset);
1839
+ const view2 = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1840
+ const length = view2.getUint32(offset);
1841
1841
  const type = String.fromCharCode(
1842
1842
  bytes[offset + 4],
1843
1843
  bytes[offset + 5],
@@ -1944,13 +1944,13 @@ function decodePng(bytes) {
1944
1944
  if (chunk2.body.length !== 13) {
1945
1945
  throw bad("PNG_BAD_IHDR", `IHDR is ${chunk2.body.length} bytes, expected 13`);
1946
1946
  }
1947
- const view = new DataView(
1947
+ const view2 = new DataView(
1948
1948
  chunk2.body.buffer,
1949
1949
  chunk2.body.byteOffset,
1950
1950
  chunk2.body.byteLength
1951
1951
  );
1952
- width = view.getUint32(0);
1953
- height = view.getUint32(4);
1952
+ width = view2.getUint32(0);
1953
+ height = view2.getUint32(4);
1954
1954
  bitDepth = chunk2.body[8];
1955
1955
  colourType = chunk2.body[9];
1956
1956
  interlace = chunk2.body[12];
@@ -2571,9 +2571,9 @@ var CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
2571
2571
  function badGesture(message3) {
2572
2572
  return new OhosPerfError(message3, { code: "UITEST_BAD_GESTURE" });
2573
2573
  }
2574
- function assertPosition(field, value) {
2574
+ function assertPosition(field2, value) {
2575
2575
  if (!Number.isSafeInteger(value) || value < 0) {
2576
- throw badGesture(`gesture ${field} must be a non-negative integer (got ${String(value)})`);
2576
+ throw badGesture(`gesture ${field2} must be a non-negative integer (got ${String(value)})`);
2577
2577
  }
2578
2578
  }
2579
2579
  function assertVelocity(velocity) {
@@ -4167,7 +4167,7 @@ function messageOf(err) {
4167
4167
  return err instanceof Error ? err.message : String(err);
4168
4168
  }
4169
4169
  function isConnectedTcp(target) {
4170
- const fields2 = target.raw.split(" ").filter((field) => field !== "");
4170
+ const fields2 = target.raw.split(" ").filter((field2) => field2 !== "");
4171
4171
  return target.connected && fields2[1] === "TCP";
4172
4172
  }
4173
4173
  function isLoopback(id) {
@@ -6316,8 +6316,8 @@ var PARITY_ROWS = [
6316
6316
  {
6317
6317
  row: 27,
6318
6318
  name: "Optimization detector (`opt-detector`)",
6319
- status: "out",
6320
- reason: "Requires a ~2 GB TensorFlow LSTM plus an sklearn classifier and is AArch64-only; it is a probabilistic guess, not a measurement."
6319
+ status: "ported",
6320
+ reason: ""
6321
6321
  },
6322
6322
  {
6323
6323
  row: 28,
@@ -8061,7 +8061,7 @@ function canonical(tree) {
8061
8061
  node.clickable ? "1" : "0",
8062
8062
  node.enabled ? "1" : "0",
8063
8063
  node.scrollable ? "1" : "0"
8064
- ].map((field) => `${String(field).length}:${String(field)}`).join("");
8064
+ ].map((field2) => `${String(field2).length}:${String(field2)}`).join("");
8065
8065
  return tree.map(line).join("");
8066
8066
  }
8067
8067
  function hashTree(tree) {
@@ -16088,10 +16088,10 @@ function round2HalfEven(value) {
16088
16088
  return negative ? -result : result;
16089
16089
  }
16090
16090
  function decompose(value) {
16091
- const view = new DataView(new ArrayBuffer(8));
16092
- view.setFloat64(0, value);
16093
- const high = view.getUint32(0);
16094
- const low = view.getUint32(4);
16091
+ const view2 = new DataView(new ArrayBuffer(8));
16092
+ view2.setFloat64(0, value);
16093
+ const high = view2.getUint32(0);
16094
+ const low = view2.getUint32(4);
16095
16095
  const exponentBits = high >>> 20 & 2047;
16096
16096
  let mantissa = BigInt(high & 1048575) << 32n | BigInt(low);
16097
16097
  if (exponentBits === 0) return { mantissa, exponent: -1074 };
@@ -17763,6 +17763,495 @@ function openZip(bytes) {
17763
17763
  };
17764
17764
  }
17765
17765
 
17766
+ // src/hap/elf.ts
17767
+ var EM_AARCH64 = 183;
17768
+ var SHT_SYMTAB = 2;
17769
+ var SHT_NOBITS = 8;
17770
+ var SHT_DYNSYM = 11;
17771
+ function fail2(message3, cause) {
17772
+ throw new OhosPerfError(message3, { code: "ELF_INVALID", ...cause === void 0 ? {} : { cause } });
17773
+ }
17774
+ function view(bytes) {
17775
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
17776
+ }
17777
+ function field(dv, at, size, what) {
17778
+ if (at < 0 || at + size > dv.byteLength) {
17779
+ fail2(`ELF is truncated: ${what} at offset ${at} runs past the ${dv.byteLength}-byte file`);
17780
+ }
17781
+ if (size === 1) return dv.getUint8(at);
17782
+ if (size === 2) return dv.getUint16(at, true);
17783
+ if (size === 4) return dv.getUint32(at, true);
17784
+ return dv.getUint32(at, true) + dv.getUint32(at + 4, true) * 2 ** 32;
17785
+ }
17786
+ function readString(table, offset) {
17787
+ if (offset < 0 || offset >= table.length) return "";
17788
+ const end = table.indexOf(0, offset);
17789
+ return new TextDecoder("utf-8").decode(
17790
+ table.subarray(offset, end === -1 ? table.length : end)
17791
+ );
17792
+ }
17793
+ function bindOf(info) {
17794
+ const bind = info >> 4;
17795
+ if (bind === 0) return "local";
17796
+ if (bind === 1) return "global";
17797
+ if (bind === 2) return "weak";
17798
+ return "other";
17799
+ }
17800
+ function typeOf(info) {
17801
+ const type = info & 15;
17802
+ if (type === 0) return "notype";
17803
+ if (type === 1) return "object";
17804
+ if (type === 2) return "func";
17805
+ if (type === 3) return "section";
17806
+ if (type === 4) return "file";
17807
+ return "other";
17808
+ }
17809
+ function symbolTableOf(dv, sections, links, bytes, index) {
17810
+ const section = sections[index];
17811
+ const link = links[index];
17812
+ const strings = link >= 0 && link < sections.length ? bytes.subarray(sections[link].offset, sections[link].offset + sections[link].size) : new Uint8Array(0);
17813
+ const entrySize = section.entrySize === 0 ? 24 : section.entrySize;
17814
+ const count = Math.floor(section.size / entrySize);
17815
+ const symbols = [];
17816
+ for (let at = 0; at < count; at += 1) {
17817
+ const base = section.offset + at * entrySize;
17818
+ if (at === 0) continue;
17819
+ const nameOffset = field(dv, base, 4, "st_name");
17820
+ const info = field(dv, base + 4, 1, "st_info");
17821
+ const sectionIndex = field(dv, base + 6, 2, "st_shndx");
17822
+ const size = field(dv, base + 16, 8, "st_size");
17823
+ const name = readString(strings, nameOffset);
17824
+ symbols.push({ name, bind: bindOf(info), type: typeOf(info), size, sectionIndex });
17825
+ }
17826
+ return symbols;
17827
+ }
17828
+ function readElf(bytes) {
17829
+ if (bytes.length < 4) {
17830
+ fail2(`ELF is truncated: ${bytes.length} bytes is shorter than the 4-byte magic`);
17831
+ }
17832
+ if (bytes[0] !== 127 || bytes[1] !== 69 || bytes[2] !== 76 || bytes[3] !== 70) {
17833
+ fail2("not an ELF file: the first four bytes are not \\x7fELF");
17834
+ }
17835
+ if (bytes.length < 16) {
17836
+ fail2(`ELF is truncated: ${bytes.length} bytes is shorter than the 16-byte ident`);
17837
+ }
17838
+ const bits = bytes[4] === 2 ? 64 : bytes[4] === 1 ? 32 : 0;
17839
+ if (bits === 0) {
17840
+ fail2(`unsupported ELF class ${String(bytes[4])}: only 32-bit and 64-bit are defined`);
17841
+ }
17842
+ const endian = bytes[5] === 1 ? "little" : bytes[5] === 2 ? "big" : void 0;
17843
+ if (endian === void 0) {
17844
+ fail2(`unsupported ELF data encoding ${String(bytes[5])}: only little and big endian are defined`);
17845
+ }
17846
+ if (bits !== 64 || endian !== "little") {
17847
+ fail2(`unsupported ELF: ${String(bits)}-bit ${endian}-endian; OHOS ships 64-bit little-endian`);
17848
+ }
17849
+ const headerSize = 64;
17850
+ if (bytes.length < headerSize) {
17851
+ fail2(`ELF is truncated: ${bytes.length} bytes is shorter than the ${headerSize}-byte header`);
17852
+ }
17853
+ const dv = view(bytes);
17854
+ const machine = field(dv, 18, 2, "e_machine");
17855
+ const type = field(dv, 16, 2, "e_type");
17856
+ const shoff = field(dv, 40, 8, "e_shoff");
17857
+ const shentsize = field(dv, 58, 2, "e_shentsize");
17858
+ const shnum = field(dv, 60, 2, "e_shnum");
17859
+ const shstrndx = field(dv, 62, 2, "e_shstrndx");
17860
+ if (shnum === 0) {
17861
+ return {
17862
+ bits: 64,
17863
+ endian,
17864
+ machine,
17865
+ type,
17866
+ sections: [],
17867
+ symbols: [],
17868
+ section: () => void 0,
17869
+ bytesOf: () => new Uint8Array(0)
17870
+ };
17871
+ }
17872
+ if (shentsize !== 64) {
17873
+ fail2(`unsupported section header size ${shentsize}: a 64-bit ELF uses 64`);
17874
+ }
17875
+ if (shoff + shnum * shentsize > bytes.length) {
17876
+ fail2(
17877
+ `ELF is truncated: the section header table at offset ${shoff} with ${shnum} entries runs past the ${bytes.length}-byte file`
17878
+ );
17879
+ }
17880
+ if (shstrndx >= shnum) {
17881
+ fail2(`e_shstrndx ${shstrndx} names a section beyond the ${shnum} the file declares`);
17882
+ }
17883
+ const raw = [];
17884
+ const links = [];
17885
+ for (let index = 0; index < shnum; index += 1) {
17886
+ const at = shoff + index * shentsize;
17887
+ raw.push({
17888
+ nameOffset: field(dv, at, 4, `section[${index}].sh_name`),
17889
+ type: field(dv, at + 4, 4, `section[${index}].sh_type`),
17890
+ flags: field(dv, at + 8, 8, `section[${index}].sh_flags`),
17891
+ offset: field(dv, at + 24, 8, `section[${index}].sh_offset`),
17892
+ size: field(dv, at + 32, 8, `section[${index}].sh_size`),
17893
+ link: field(dv, at + 40, 4, `section[${index}].sh_link`),
17894
+ entrySize: field(dv, at + 56, 8, `section[${index}].sh_entsize`)
17895
+ });
17896
+ links.push(raw[index].link);
17897
+ }
17898
+ for (const [index, section] of raw.entries()) {
17899
+ if (section.type === SHT_NOBITS || section.type === 0) continue;
17900
+ if (section.offset + section.size > bytes.length) {
17901
+ fail2(
17902
+ `ELF is truncated: section ${index} at offset ${section.offset} with size ${section.size} runs past the ${bytes.length}-byte file`
17903
+ );
17904
+ }
17905
+ }
17906
+ const nameTable = raw[shstrndx];
17907
+ const strings = bytes.subarray(nameTable.offset, nameTable.offset + nameTable.size);
17908
+ const sections = raw.map((section) => ({
17909
+ name: readString(strings, section.nameOffset),
17910
+ type: section.type,
17911
+ flags: section.flags,
17912
+ offset: section.offset,
17913
+ size: section.size,
17914
+ entrySize: section.entrySize
17915
+ }));
17916
+ const symbols = [];
17917
+ for (const [index, section] of sections.entries()) {
17918
+ if (section.type !== SHT_SYMTAB && section.type !== SHT_DYNSYM) continue;
17919
+ symbols.push(...symbolTableOf(dv, sections, links, bytes, index));
17920
+ }
17921
+ const byName = new Map(sections.map((section) => [section.name, section]));
17922
+ return {
17923
+ bits: 64,
17924
+ endian,
17925
+ machine,
17926
+ type,
17927
+ sections,
17928
+ symbols,
17929
+ section: (name) => byName.get(name),
17930
+ bytesOf: (name) => {
17931
+ const section = byName.get(name);
17932
+ if (section === void 0 || section.type === SHT_NOBITS) return new Uint8Array(0);
17933
+ return bytes.subarray(section.offset, section.offset + section.size);
17934
+ }
17935
+ };
17936
+ }
17937
+ function classifyInstruction(word) {
17938
+ const masked = (mask) => (word & mask) >>> 0;
17939
+ if (masked(4294966303) === 3596550144) return "ret";
17940
+ if (masked(4294966303) === 3594452992) return "blr";
17941
+ if (masked(4294966303) === 3592355840) return "br";
17942
+ if (masked(4227858432) === 2483027968) return "bl";
17943
+ if (masked(4227858432) === 335544320) return "b";
17944
+ if (masked(4278190096) === 1409286144) return "bcond";
17945
+ if (masked(2113929216) === 872415232) return "cbz";
17946
+ if (masked(2113929216) === 905969664) return "tbz";
17947
+ if (masked(2667577344) === 2415919104) return "adrp";
17948
+ if (masked(2667577344) === 268435456) return "adr";
17949
+ if (masked(989855744) === 956301312) {
17950
+ return masked(4194304) === 0 ? "str" : "ldr";
17951
+ }
17952
+ if (masked(520093696) === 285212672) return "add";
17953
+ if (masked(167772160) === 167772160) return "vector";
17954
+ return "other";
17955
+ }
17956
+ function countInstructions(payload) {
17957
+ const counts = {
17958
+ total: 0,
17959
+ ret: 0,
17960
+ blr: 0,
17961
+ br: 0,
17962
+ bl: 0,
17963
+ b: 0,
17964
+ bcond: 0,
17965
+ cbz: 0,
17966
+ tbz: 0,
17967
+ adrp: 0,
17968
+ adr: 0,
17969
+ ldr: 0,
17970
+ str: 0,
17971
+ add: 0,
17972
+ vector: 0,
17973
+ other: 0
17974
+ };
17975
+ const dv = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
17976
+ const words = Math.floor(payload.length / 4);
17977
+ for (let index = 0; index < words; index += 1) {
17978
+ const cls = classifyInstruction(dv.getUint32(index * 4, true));
17979
+ counts[cls] += 1;
17980
+ counts.total += 1;
17981
+ }
17982
+ return counts;
17983
+ }
17984
+
17985
+ // src/hap/optimization.ts
17986
+ var OFFLINE_WINDOW = { startNs: 0, endNs: 0 };
17987
+ var LTO_PATTERNS = [
17988
+ { pattern: /^lto_priv\./, why: "lto_priv symbol" },
17989
+ { pattern: /^\.gnu\.lto_/, why: ".gnu.lto section" },
17990
+ { pattern: /^\.gnu\.lto$/, why: ".gnu.lto section" },
17991
+ { pattern: /^lto_[0-9]+\.[0-9]+$/, why: "lto_N.M symbol" }
17992
+ ];
17993
+ var RECORDED_FLAG = /^-(O[0-3s]|Oz|Ofast)$/;
17994
+ var LEVEL_OF_FLAG = {
17995
+ "-O0": "unoptimized",
17996
+ "-O1": "low",
17997
+ "-O2": "medium",
17998
+ "-O3": "high",
17999
+ "-Os": "medium",
18000
+ "-Oz": "medium",
18001
+ "-Ofast": "high"
18002
+ };
18003
+ var VECTOR_DENSITY_HIGH = 0.1;
18004
+ var VECTOR_DENSITY_NONE = 0.02;
18005
+ function byString6(a, b) {
18006
+ return a < b ? -1 : a > b ? 1 : 0;
18007
+ }
18008
+ function decode(bytes) {
18009
+ return new TextDecoder("utf-8").decode(bytes);
18010
+ }
18011
+ function commentStrings(bytes) {
18012
+ return decode(bytes).split("\0").map((part) => part.trim()).filter((part) => part !== "");
18013
+ }
18014
+ function inspectBinary(input) {
18015
+ let elf;
18016
+ try {
18017
+ elf = readElf(input.bytes);
18018
+ } catch (err) {
18019
+ throw new OhosPerfError(
18020
+ `${input.path}: ${err.message}`,
18021
+ { code: "ELF_INVALID", cause: err }
18022
+ );
18023
+ }
18024
+ const textSection = elf.section(".text");
18025
+ const textBytes = textSection?.size ?? 0;
18026
+ const instructions = countInstructions(elf.bytesOf(".text"));
18027
+ const symbolTablePresent = elf.sections.some(
18028
+ (section) => section.type === 2 || section.type === 11
18029
+ );
18030
+ const ltoMarkers = [];
18031
+ for (const section of elf.sections) {
18032
+ if (LTO_PATTERNS.some((entry) => entry.pattern.test(section.name))) {
18033
+ ltoMarkers.push(section.name);
18034
+ }
18035
+ }
18036
+ for (const symbol of elf.symbols) {
18037
+ if (LTO_PATTERNS.some((entry) => entry.pattern.test(symbol.name))) {
18038
+ ltoMarkers.push(symbol.name);
18039
+ }
18040
+ }
18041
+ const lto = ltoMarkers.length > 0 ? "present" : symbolTablePresent ? "absent" : "unknown";
18042
+ const debugSections = elf.sections.map((section) => section.name).filter((name) => name.startsWith(".debug_") || name === ".zdebug_info");
18043
+ const commentSection = elf.section(".comment");
18044
+ const compiler = commentSection === void 0 ? [] : commentStrings(elf.bytesOf(".comment"));
18045
+ const recordedFlags = [];
18046
+ for (const line of compiler) {
18047
+ for (const token of line.split(/\s+/)) {
18048
+ if (RECORDED_FLAG.test(token) && !recordedFlags.includes(token)) recordedFlags.push(token);
18049
+ }
18050
+ }
18051
+ const functions = elf.symbols.filter((symbol) => symbol.type === "func");
18052
+ const countBind = (bind) => functions.filter((symbol) => symbol.bind === bind).length;
18053
+ return {
18054
+ path: input.path,
18055
+ size: input.bytes.length,
18056
+ machine: elf.machine,
18057
+ textBytes,
18058
+ instructions,
18059
+ lto,
18060
+ ltoMarkers,
18061
+ debug: debugSections.length > 0,
18062
+ debugSections,
18063
+ compiler,
18064
+ recordedFlags,
18065
+ symbols: {
18066
+ functions: functions.length,
18067
+ global: countBind("global"),
18068
+ local: countBind("local"),
18069
+ weak: countBind("weak")
18070
+ },
18071
+ stripped: functions.length === 0
18072
+ };
18073
+ }
18074
+ function classifyOptimization(facts) {
18075
+ for (const flag2 of facts.recordedFlags) {
18076
+ const level = LEVEL_OF_FLAG[flag2];
18077
+ if (level !== void 0) return { level, basis: "recorded", signals: [] };
18078
+ }
18079
+ const total = facts.instructions.total;
18080
+ if (total === 0) {
18081
+ return { level: "unknown", basis: "none", signals: [] };
18082
+ }
18083
+ const vectorDensity = facts.instructions.vector / total;
18084
+ if (vectorDensity >= VECTOR_DENSITY_HIGH) {
18085
+ return { level: "high", basis: "inferred", signals: ["vector_density"] };
18086
+ }
18087
+ if (facts.debug) {
18088
+ return {
18089
+ level: "unoptimized",
18090
+ basis: "inferred",
18091
+ signals: vectorDensity <= VECTOR_DENSITY_NONE ? ["debug_sections", "no_vector_code"] : ["debug_sections"]
18092
+ };
18093
+ }
18094
+ if (vectorDensity <= VECTOR_DENSITY_NONE) {
18095
+ return { level: "low", basis: "inferred", signals: ["no_vector_code"] };
18096
+ }
18097
+ return { level: "medium", basis: "inferred", signals: ["vector_density"] };
18098
+ }
18099
+ var ARM64_LIBRARY = /^(?:libs|lib)\/arm64(?:-v8a)?\//;
18100
+ var SHARED_OBJECT = /\.so(?:\.|$)/;
18101
+ function extractBinaries(input) {
18102
+ if (input.path.endsWith(".a")) {
18103
+ throw new OhosPerfError(
18104
+ `${input.path}: an .a archive is not read by this package; pass the .so files (or the package that contains them) instead`,
18105
+ { code: "SCENARIO_BAD_INPUT" }
18106
+ );
18107
+ }
18108
+ if (!isZip(input.bytes)) {
18109
+ return [{ path: input.path, bytes: input.bytes }];
18110
+ }
18111
+ const archive = openZip(input.bytes);
18112
+ const binaries = [];
18113
+ for (const entry of archive.entries) {
18114
+ if (!ARM64_LIBRARY.test(entry.name)) continue;
18115
+ if (!SHARED_OBJECT.test(entry.name)) continue;
18116
+ const bytes = archive.read(entry);
18117
+ if (bytes.length < 4 || bytes[0] !== 127 || bytes[1] !== 69) continue;
18118
+ binaries.push({ path: entry.name, bytes });
18119
+ }
18120
+ if (binaries.length === 0) {
18121
+ throw new OhosPerfError(
18122
+ `${input.path}: no arm64 libraries (libs/arm64/*.so) in the package`,
18123
+ { code: "SCENARIO_BAD_INPUT" }
18124
+ );
18125
+ }
18126
+ return binaries;
18127
+ }
18128
+ function offlineProvenance(rows) {
18129
+ return { collector: "offline", table: "elf", rows, device: "offline" };
18130
+ }
18131
+ var LEVEL_IDS = {
18132
+ unoptimized: "binary.unoptimized.files.count",
18133
+ low: "binary.low.optimization.files.count",
18134
+ medium: "binary.medium.optimization.files.count",
18135
+ high: "binary.high.optimization.files.count",
18136
+ unknown: "binary.unknown.optimization.files.count"
18137
+ };
18138
+ function buildMetrics(binaries) {
18139
+ const rows = binaries.length;
18140
+ const make = (id, value, unit, fidelity) => metric({
18141
+ id,
18142
+ value,
18143
+ unit,
18144
+ fidelity,
18145
+ provenance: offlineProvenance(rows),
18146
+ window: OFFLINE_WINDOW
18147
+ });
18148
+ const metrics = [
18149
+ make("binary.files.count", rows, "count", "exact"),
18150
+ make("binary.text.bytes", binaries.reduce((sum, b) => sum + b.facts.textBytes, 0), "bytes", "exact"),
18151
+ make(
18152
+ "binary.instructions.count",
18153
+ binaries.reduce((sum, b) => sum + b.facts.instructions.total, 0),
18154
+ "count",
18155
+ "exact"
18156
+ ),
18157
+ make("binary.lto.files.count", binaries.filter((b) => b.facts.lto === "present").length, "count", "exact"),
18158
+ make("binary.lto.unknown.files.count", binaries.filter((b) => b.facts.lto === "unknown").length, "count", "exact"),
18159
+ make("binary.debug.files.count", binaries.filter((b) => b.facts.debug).length, "count", "exact"),
18160
+ make("binary.stripped.files.count", binaries.filter((b) => b.facts.stripped).length, "count", "exact")
18161
+ ];
18162
+ const byLevel = /* @__PURE__ */ new Map();
18163
+ for (const binary of binaries) {
18164
+ byLevel.set(binary.verdict.level, (byLevel.get(binary.verdict.level) ?? 0) + 1);
18165
+ }
18166
+ for (const level of ["unoptimized", "low", "medium", "high", "unknown"]) {
18167
+ const count = byLevel.get(level) ?? 0;
18168
+ if (count === 0) continue;
18169
+ metrics.push(make(LEVEL_IDS[level], count, "count", "proxy"));
18170
+ }
18171
+ return metrics.sort((a, b) => byString6(a.id, b.id));
18172
+ }
18173
+ function buildEvidence(packageName, binaries) {
18174
+ const subject = { process: packageName };
18175
+ const items = [];
18176
+ for (const binary of binaries) {
18177
+ if (binary.facts.lto === "present") {
18178
+ items.push(evidence({
18179
+ kind: "optimization",
18180
+ severity: "info",
18181
+ subject,
18182
+ window: OFFLINE_WINDOW,
18183
+ signals: {
18184
+ path: binary.path,
18185
+ lto: "present",
18186
+ markers: binary.facts.ltoMarkers.length,
18187
+ level: binary.verdict.level,
18188
+ basis: binary.verdict.basis
18189
+ },
18190
+ explain: `${binary.path} was linked with LTO: ${binary.facts.ltoMarkers.slice(0, 3).join(", ")}` + (binary.facts.ltoMarkers.length > 3 ? `, and ${binary.facts.ltoMarkers.length - 3} more` : ""),
18191
+ drillDown: [],
18192
+ key: `${binary.path}:lto`
18193
+ }));
18194
+ }
18195
+ if (binary.facts.instructions.total === 0) {
18196
+ items.push(evidence({
18197
+ kind: "no_data",
18198
+ severity: "info",
18199
+ subject,
18200
+ window: OFFLINE_WINDOW,
18201
+ signals: { path: binary.path },
18202
+ explain: `${binary.path} has no instructions in .text, so its optimization level was not measured; a binary with no code carries no evidence either way`,
18203
+ drillDown: [],
18204
+ key: `${binary.path}:no-text`
18205
+ }));
18206
+ }
18207
+ if (binary.verdict.level === "unoptimized" || binary.verdict.level === "low") {
18208
+ items.push(evidence({
18209
+ kind: "optimization",
18210
+ severity: binary.verdict.level === "unoptimized" ? "warn" : "info",
18211
+ subject,
18212
+ window: OFFLINE_WINDOW,
18213
+ signals: {
18214
+ path: binary.path,
18215
+ level: binary.verdict.level,
18216
+ basis: binary.verdict.basis,
18217
+ signals: [...binary.verdict.signals],
18218
+ vectorDensity: binary.facts.instructions.total === 0 ? 0 : Math.round(binary.facts.instructions.vector / binary.facts.instructions.total * 1e4) / 1e4
18219
+ },
18220
+ explain: `${binary.path} reads as ${binary.verdict.level} optimization` + (binary.verdict.basis === "recorded" ? ` from its recorded flag ${binary.facts.recordedFlags.join(" ")}` : ` from its instruction mix (${binary.verdict.signals.join(", ")})`),
18221
+ drillDown: [],
18222
+ key: `${binary.path}:level`
18223
+ }));
18224
+ }
18225
+ }
18226
+ return items.sort((a, b) => byString6(a.kind, b.kind) || byString6(a.id, b.id));
18227
+ }
18228
+ function analyzeBinaries(inputs, packageName) {
18229
+ const binaries = [...inputs].sort((a, b) => byString6(a.path, b.path)).map((input) => {
18230
+ const facts = inspectBinary(input);
18231
+ return { path: facts.path, facts, verdict: classifyOptimization(facts) };
18232
+ });
18233
+ return {
18234
+ schemaVersion: 1,
18235
+ package: packageName,
18236
+ binaries,
18237
+ totals: {
18238
+ binaries: binaries.length,
18239
+ lto: binaries.filter((binary) => binary.facts.lto === "present").length,
18240
+ debug: binaries.filter((binary) => binary.facts.debug).length,
18241
+ stripped: binaries.filter((binary) => binary.facts.stripped).length
18242
+ },
18243
+ metrics: buildMetrics(binaries),
18244
+ evidence: buildEvidence(packageName, binaries)
18245
+ };
18246
+ }
18247
+ function optimizationSection(analysis) {
18248
+ return {
18249
+ analyzerId: "optimization",
18250
+ status: "measured",
18251
+ result: { metrics: analysis.metrics, evidence: analysis.evidence }
18252
+ };
18253
+ }
18254
+
17766
18255
  // src/hap/inventory.ts
17767
18256
  var CATEGORY_EXTENSIONS = {
17768
18257
  images: ["png", "jpg", "jpeg", "gif", "bmp", "webp", "svg"],
@@ -17817,7 +18306,7 @@ function buildInventory(archive) {
17817
18306
  // src/hap/rules.ts
17818
18307
  var EXCLUDE_PATTERNS = ["resources/base/.*"];
17819
18308
  var KINDS2 = ["filename", "path", "extension", "magic", "content", "combined"];
17820
- function fail2(ruleId, message3) {
18309
+ function fail3(ruleId, message3) {
17821
18310
  throw new OhosPerfError(`rule ${JSON.stringify(ruleId)}: ${message3}`, { code: "HAP_BAD_RULE" });
17822
18311
  }
17823
18312
  function basename3(path) {
@@ -17827,7 +18316,7 @@ function compile(ruleId, source) {
17827
18316
  try {
17828
18317
  return new RegExp(source);
17829
18318
  } catch (err) {
17830
- return fail2(ruleId, `invalid pattern ${JSON.stringify(source)}: ${err.message}`);
18319
+ return fail3(ruleId, `invalid pattern ${JSON.stringify(source)}: ${err.message}`);
17831
18320
  }
17832
18321
  }
17833
18322
  var EntryReader = class {
@@ -17983,15 +18472,15 @@ function matchHapRules(rules, archive, inventory) {
17983
18472
  function validateRules(rules) {
17984
18473
  const seen = /* @__PURE__ */ new Set();
17985
18474
  for (const rule of rules) {
17986
- if (seen.has(rule.id)) fail2(rule.id, "duplicate rule id");
18475
+ if (seen.has(rule.id)) fail3(rule.id, "duplicate rule id");
17987
18476
  seen.add(rule.id);
17988
- if (rule.fileRules.length === 0) fail2(rule.id, "has no file rules");
18477
+ if (rule.fileRules.length === 0) fail3(rule.id, "has no file rules");
17989
18478
  if (rule.requireMetadata === true && (rule.metadataPatterns ?? []).length === 0) {
17990
- fail2(rule.id, "requires metadata but names no metadata pattern");
18479
+ fail3(rule.id, "requires metadata but names no metadata pattern");
17991
18480
  }
17992
18481
  for (const pattern of rule.metadataPatterns ?? []) {
17993
18482
  if (pattern.source !== "content" && pattern.source !== "path" && pattern.source !== "filename") {
17994
- fail2(rule.id, `metadata field ${JSON.stringify(pattern.field)} has unknown source ${JSON.stringify(pattern.source)}`);
18483
+ fail3(rule.id, `metadata field ${JSON.stringify(pattern.field)} has unknown source ${JSON.stringify(pattern.source)}`);
17995
18484
  }
17996
18485
  compile(rule.id, pattern.pattern);
17997
18486
  }
@@ -18000,28 +18489,28 @@ function validateRules(rules) {
18000
18489
  }
18001
18490
  function validateFileRules(ruleId, rules) {
18002
18491
  for (const rule of rules) {
18003
- if (!KINDS2.includes(rule.kind)) fail2(ruleId, `unknown rule kind ${JSON.stringify(rule.kind)}`);
18492
+ if (!KINDS2.includes(rule.kind)) fail3(ruleId, `unknown rule kind ${JSON.stringify(rule.kind)}`);
18004
18493
  switch (rule.kind) {
18005
18494
  case "filename":
18006
18495
  case "path":
18007
18496
  case "content":
18008
- if ((rule.patterns ?? []).length === 0) fail2(ruleId, `a ${rule.kind} rule names no pattern`);
18497
+ if ((rule.patterns ?? []).length === 0) fail3(ruleId, `a ${rule.kind} rule names no pattern`);
18009
18498
  for (const item of rule.patterns ?? []) compile(ruleId, typeof item === "string" ? item : item.pattern);
18010
18499
  break;
18011
18500
  case "extension":
18012
- if ((rule.extensions ?? []).length === 0) fail2(ruleId, "an extension rule names no extension");
18501
+ if ((rule.extensions ?? []).length === 0) fail3(ruleId, "an extension rule names no extension");
18013
18502
  break;
18014
18503
  case "magic":
18015
- if ((rule.bytes ?? []).length === 0) fail2(ruleId, "a magic rule names no bytes");
18504
+ if ((rule.bytes ?? []).length === 0) fail3(ruleId, "a magic rule names no bytes");
18016
18505
  for (const byte of rule.bytes ?? []) {
18017
- if (!Number.isInteger(byte) || byte < 0 || byte > 255) fail2(ruleId, `magic byte ${byte} is not a byte`);
18506
+ if (!Number.isInteger(byte) || byte < 0 || byte > 255) fail3(ruleId, `magic byte ${byte} is not a byte`);
18018
18507
  }
18019
18508
  break;
18020
18509
  case "combined":
18021
18510
  if (rule.operator !== "and" && rule.operator !== "or" && rule.operator !== "not") {
18022
- fail2(ruleId, `combined rule has operator ${JSON.stringify(rule.operator)}`);
18511
+ fail3(ruleId, `combined rule has operator ${JSON.stringify(rule.operator)}`);
18023
18512
  }
18024
- if ((rule.rules ?? []).length === 0) fail2(ruleId, "a combined rule names no sub-rules");
18513
+ if ((rule.rules ?? []).length === 0) fail3(ruleId, "a combined rule names no sub-rules");
18025
18514
  validateFileRules(ruleId, rule.rules ?? []);
18026
18515
  break;
18027
18516
  }
@@ -18404,10 +18893,10 @@ var TECH_RULES = [
18404
18893
 
18405
18894
  // src/hap/analyze.ts
18406
18895
  import { createHash as createHash3 } from "node:crypto";
18407
- var OFFLINE_WINDOW = { startNs: 0, endNs: 0 };
18896
+ var OFFLINE_WINDOW2 = { startNs: 0, endNs: 0 };
18408
18897
  var LARGEST_COUNT = 10;
18409
18898
  var EXPLAIN_PATHS = 5;
18410
- function byString6(a, b) {
18899
+ function byString7(a, b) {
18411
18900
  return a < b ? -1 : a > b ? 1 : 0;
18412
18901
  }
18413
18902
  function sha256(bytes) {
@@ -18459,7 +18948,7 @@ function findDuplicates(archive, inventory) {
18459
18948
  const groups = [];
18460
18949
  for (const [hash, files] of byHash) {
18461
18950
  if (files.length < 2) continue;
18462
- const sorted = [...files].sort((a, b) => byString6(a.path, b.path));
18951
+ const sorted = [...files].sort((a, b) => byString7(a.path, b.path));
18463
18952
  const size = sorted[0].size;
18464
18953
  groups.push({
18465
18954
  sha256: hash,
@@ -18469,7 +18958,7 @@ function findDuplicates(archive, inventory) {
18469
18958
  paths: sorted.map((file) => file.path)
18470
18959
  });
18471
18960
  }
18472
- return groups.sort((a, b) => byString6(a.sha256, b.sha256));
18961
+ return groups.sort((a, b) => byString7(a.sha256, b.sha256));
18473
18962
  }
18474
18963
  function findOversized(inventory) {
18475
18964
  return inventory.filter((file) => file.size > CATEGORY_MAX_BYTES[file.category]).map((file) => ({
@@ -18477,7 +18966,7 @@ function findOversized(inventory) {
18477
18966
  category: file.category,
18478
18967
  size: file.size,
18479
18968
  threshold: CATEGORY_MAX_BYTES[file.category]
18480
- })).sort((a, b) => b.size - a.size || byString6(a.path, b.path));
18969
+ })).sort((a, b) => b.size - a.size || byString7(a.path, b.path));
18481
18970
  }
18482
18971
  function categoryTotals(inventory) {
18483
18972
  const totals = /* @__PURE__ */ new Map();
@@ -18490,72 +18979,72 @@ function categoryTotals(inventory) {
18490
18979
  compressedSize: (current?.compressedSize ?? 0) + file.compressedSize
18491
18980
  });
18492
18981
  }
18493
- return [...totals.values()].sort((a, b) => byString6(a.name, b.name));
18982
+ return [...totals.values()].sort((a, b) => byString7(a.name, b.name));
18494
18983
  }
18495
18984
  function listPaths(paths) {
18496
18985
  const shown = paths.slice(0, EXPLAIN_PATHS).join(", ");
18497
18986
  return paths.length > EXPLAIN_PATHS ? `${shown}, and ${paths.length - EXPLAIN_PATHS} more` : shown;
18498
18987
  }
18499
- function offlineProvenance(rows) {
18988
+ function offlineProvenance2(rows) {
18500
18989
  return { collector: "offline", table: "hap", rows, device: "offline" };
18501
18990
  }
18502
- function buildMetrics(analysis) {
18991
+ function buildMetrics2(analysis) {
18503
18992
  const metrics = [
18504
18993
  metric({
18505
18994
  id: "hap.files.count",
18506
18995
  value: analysis.totals.files,
18507
18996
  unit: "count",
18508
- provenance: offlineProvenance(analysis.totals.files),
18997
+ provenance: offlineProvenance2(analysis.totals.files),
18509
18998
  fidelity: "exact",
18510
- window: OFFLINE_WINDOW
18999
+ window: OFFLINE_WINDOW2
18511
19000
  }),
18512
19001
  metric({
18513
19002
  id: "hap.size.bytes",
18514
19003
  value: analysis.totals.size,
18515
19004
  unit: "bytes",
18516
- provenance: offlineProvenance(analysis.totals.files),
19005
+ provenance: offlineProvenance2(analysis.totals.files),
18517
19006
  fidelity: "exact",
18518
- window: OFFLINE_WINDOW
19007
+ window: OFFLINE_WINDOW2
18519
19008
  }),
18520
19009
  metric({
18521
19010
  id: "hap.size.compressed.bytes",
18522
19011
  value: analysis.totals.compressedSize,
18523
19012
  unit: "bytes",
18524
- provenance: offlineProvenance(analysis.totals.files),
19013
+ provenance: offlineProvenance2(analysis.totals.files),
18525
19014
  fidelity: "exact",
18526
- window: OFFLINE_WINDOW
19015
+ window: OFFLINE_WINDOW2
18527
19016
  }),
18528
19017
  metric({
18529
19018
  id: "hap.techstack.count",
18530
19019
  value: analysis.technologies.length,
18531
19020
  unit: "count",
18532
- provenance: offlineProvenance(analysis.technologies.length),
19021
+ provenance: offlineProvenance2(analysis.technologies.length),
18533
19022
  fidelity: "exact",
18534
- window: OFFLINE_WINDOW
19023
+ window: OFFLINE_WINDOW2
18535
19024
  }),
18536
19025
  metric({
18537
19026
  id: "hap.duplicates.groups",
18538
19027
  value: analysis.duplicates.length,
18539
19028
  unit: "count",
18540
- provenance: offlineProvenance(analysis.duplicates.length),
19029
+ provenance: offlineProvenance2(analysis.duplicates.length),
18541
19030
  fidelity: "exact",
18542
- window: OFFLINE_WINDOW
19031
+ window: OFFLINE_WINDOW2
18543
19032
  }),
18544
19033
  metric({
18545
19034
  id: "hap.duplicates.wasted.bytes",
18546
19035
  value: analysis.duplicates.reduce((sum, group) => sum + group.wastedBytes, 0),
18547
19036
  unit: "bytes",
18548
- provenance: offlineProvenance(analysis.duplicates.length),
19037
+ provenance: offlineProvenance2(analysis.duplicates.length),
18549
19038
  fidelity: "exact",
18550
- window: OFFLINE_WINDOW
19039
+ window: OFFLINE_WINDOW2
18551
19040
  }),
18552
19041
  metric({
18553
19042
  id: "hap.oversized.count",
18554
19043
  value: analysis.oversized.length,
18555
19044
  unit: "count",
18556
- provenance: offlineProvenance(analysis.oversized.length),
19045
+ provenance: offlineProvenance2(analysis.oversized.length),
18557
19046
  fidelity: "exact",
18558
- window: OFFLINE_WINDOW
19047
+ window: OFFLINE_WINDOW2
18559
19048
  })
18560
19049
  ];
18561
19050
  const byType = /* @__PURE__ */ new Map();
@@ -18567,9 +19056,9 @@ function buildMetrics(analysis) {
18567
19056
  id: `hap.techstack.${type}.files`,
18568
19057
  value: files,
18569
19058
  unit: "count",
18570
- provenance: offlineProvenance(files),
19059
+ provenance: offlineProvenance2(files),
18571
19060
  fidelity: "exact",
18572
- window: OFFLINE_WINDOW
19061
+ window: OFFLINE_WINDOW2
18573
19062
  }));
18574
19063
  }
18575
19064
  for (const category of analysis.categories) {
@@ -18577,14 +19066,14 @@ function buildMetrics(analysis) {
18577
19066
  id: `hap.category.${category.name}.bytes`,
18578
19067
  value: category.size,
18579
19068
  unit: "bytes",
18580
- provenance: offlineProvenance(category.files),
19069
+ provenance: offlineProvenance2(category.files),
18581
19070
  fidelity: "exact",
18582
- window: OFFLINE_WINDOW
19071
+ window: OFFLINE_WINDOW2
18583
19072
  }));
18584
19073
  }
18585
- return metrics.sort((a, b) => byString6(a.id, b.id));
19074
+ return metrics.sort((a, b) => byString7(a.id, b.id));
18586
19075
  }
18587
- function buildEvidence(analysis) {
19076
+ function buildEvidence2(analysis) {
18588
19077
  const subject = { process: analysis.package.bundleName === "" ? analysis.package.name : analysis.package.bundleName };
18589
19078
  const items = [];
18590
19079
  for (const match of analysis.technologies) {
@@ -18592,7 +19081,7 @@ function buildEvidence(analysis) {
18592
19081
  kind: "tech_stack",
18593
19082
  severity: "info",
18594
19083
  subject,
18595
- window: OFFLINE_WINDOW,
19084
+ window: OFFLINE_WINDOW2,
18596
19085
  signals: {
18597
19086
  rule: match.ruleId,
18598
19087
  type: match.type,
@@ -18610,7 +19099,7 @@ function buildEvidence(analysis) {
18610
19099
  kind: "duplicate_asset",
18611
19100
  severity: "warn",
18612
19101
  subject,
18613
- window: OFFLINE_WINDOW,
19102
+ window: OFFLINE_WINDOW2,
18614
19103
  signals: {
18615
19104
  hash: group.sha256,
18616
19105
  size: group.size,
@@ -18627,14 +19116,14 @@ function buildEvidence(analysis) {
18627
19116
  kind: "oversized_asset",
18628
19117
  severity: "info",
18629
19118
  subject,
18630
- window: OFFLINE_WINDOW,
19119
+ window: OFFLINE_WINDOW2,
18631
19120
  signals: { category: file.category, size: file.size, threshold: file.threshold },
18632
19121
  explain: `${file.path} is ${file.size} bytes, above the ${file.category} limit of ${file.threshold} bytes`,
18633
19122
  drillDown: [],
18634
19123
  key: file.path
18635
19124
  }));
18636
19125
  }
18637
- return items.sort((a, b) => byString6(a.kind, b.kind) || a.window.startNs - b.window.startNs || byString6(a.id, b.id));
19126
+ return items.sort((a, b) => byString7(a.kind, b.kind) || a.window.startNs - b.window.startNs || byString7(a.id, b.id));
18638
19127
  }
18639
19128
  function analyzeHap(bytes, packageName) {
18640
19129
  const archive = openZip(bytes);
@@ -18650,7 +19139,7 @@ function analyzeHap(bytes, packageName) {
18650
19139
  size: inventory.reduce((sum, file) => sum + file.size, 0),
18651
19140
  compressedSize: inventory.reduce((sum, file) => sum + file.compressedSize, 0)
18652
19141
  };
18653
- const largest = [...inventory].sort((a, b) => b.size - a.size || byString6(a.path, b.path)).slice(0, LARGEST_COUNT).map((file) => ({ path: file.path, size: file.size }));
19142
+ const largest = [...inventory].sort((a, b) => b.size - a.size || byString7(a.path, b.path)).slice(0, LARGEST_COUNT).map((file) => ({ path: file.path, size: file.size }));
18654
19143
  const analysis = {
18655
19144
  schemaVersion: 1,
18656
19145
  package: { name: packageName, ...packageBlock },
@@ -18664,8 +19153,8 @@ function analyzeHap(bytes, packageName) {
18664
19153
  return {
18665
19154
  ...analysis,
18666
19155
  files: inventory,
18667
- metrics: buildMetrics(analysis),
18668
- evidence: buildEvidence(analysis)
19156
+ metrics: buildMetrics2(analysis),
19157
+ evidence: buildEvidence2(analysis)
18669
19158
  };
18670
19159
  }
18671
19160
  function hapSection(analysis) {
@@ -18871,6 +19360,7 @@ export {
18871
19360
  DEVICE_UI_PATH,
18872
19361
  Device,
18873
19362
  DeviceNotFoundError,
19363
+ EM_AARCH64,
18874
19364
  EXCLUDE_PATTERNS,
18875
19365
  EmptyFrameAnalyzer,
18876
19366
  EmulatorClient,
@@ -18945,6 +19435,7 @@ export {
18945
19435
  VsyncAnalyzer,
18946
19436
  aggregateUnreleased,
18947
19437
  analyseAnimations,
19438
+ analyzeBinaries,
18948
19439
  analyzeHap,
18949
19440
  analyzeThreadWakeup,
18950
19441
  animationSeverity,
@@ -18956,7 +19447,9 @@ export {
18956
19447
  buildReport,
18957
19448
  buildTrend,
18958
19449
  categorize,
19450
+ classifyInstruction,
18959
19451
  classifyNativePath,
19452
+ classifyOptimization,
18960
19453
  compareImages,
18961
19454
  compareRegion,
18962
19455
  compareResults,
@@ -18972,6 +19465,7 @@ export {
18972
19465
  computeThreadAnalysis,
18973
19466
  computeVsyncAnomalies,
18974
19467
  connect,
19468
+ countInstructions,
18975
19469
  createSceneLayout,
18976
19470
  cropRegion,
18977
19471
  decodePng,
@@ -18986,6 +19480,7 @@ export {
18986
19480
  executeAction,
18987
19481
  explorationDevice,
18988
19482
  explore,
19483
+ extractBinaries,
18989
19484
  filterEmptyFrames,
18990
19485
  flattenUiTree,
18991
19486
  ftracePlugin,
@@ -18994,6 +19489,7 @@ export {
18994
19489
  hashTree,
18995
19490
  hiperfRecordCommand,
18996
19491
  ingestScene,
19492
+ inspectBinary,
18997
19493
  isUnresolvedSymbol,
18998
19494
  isZip,
18999
19495
  loadCases,
@@ -19009,6 +19505,7 @@ export {
19009
19505
  nodeIdentity,
19010
19506
  openDb,
19011
19507
  openZip,
19508
+ optimizationSection,
19012
19509
  pairNativeMemory,
19013
19510
  paritySummary,
19014
19511
  parseBounds,
@@ -19025,6 +19522,7 @@ export {
19025
19522
  parseSmapsRollup,
19026
19523
  planNextAction,
19027
19524
  queryDefinitions,
19525
+ readElf,
19028
19526
  readHidumperCapture,
19029
19527
  readHilogText,
19030
19528
  readJsheapSnapshot,
package/package.json CHANGED
@@ -1,48 +1,48 @@
1
- {
2
- "name": "@ohos-perf/core",
3
- "version": "0.19.0",
4
- "description": "HarmonyOS performance analysis: capability probing, nine collectors, trace ingest, typed queries, twenty-one analyzers with provenance and fidelity, reports and a scenario runner",
5
- "keywords": [
6
- "harmonyos",
7
- "openharmony",
8
- "ohos",
9
- "performance",
10
- "profiling",
11
- "trace",
12
- "hapray"
13
- ],
14
- "type": "module",
15
- "main": "./dist/index.js",
16
- "types": "./dist/index.d.ts",
17
- "exports": {
18
- ".": {
19
- "types": "./dist/index.d.ts",
20
- "import": "./dist/index.js"
21
- }
22
- },
23
- "files": [
24
- "dist"
25
- ],
26
- "engines": {
27
- "node": "^22.13.0 || >=23.4.0"
28
- },
29
- "license": "MIT",
30
- "author": "growvv",
31
- "homepage": "https://growvv.github.io/ohos-perf/",
32
- "repository": {
33
- "type": "git",
34
- "url": "git+https://github.com/growvv/ohos-perf.git",
35
- "directory": "packages/core"
36
- },
37
- "bugs": {
38
- "url": "https://github.com/growvv/ohos-perf/issues"
39
- },
40
- "publishConfig": {
41
- "access": "public"
42
- },
43
- "scripts": {
44
- "build": "tsup src/index.ts --format esm --dts",
45
- "typecheck": "tsc --noEmit -p tsconfig.test.json",
46
- "prepublishOnly": "npm run build"
47
- }
48
- }
1
+ {
2
+ "name": "@ohos-perf/core",
3
+ "version": "0.20.0",
4
+ "description": "HarmonyOS performance analysis: capability probing, nine collectors, trace ingest, typed queries, twenty-one analyzers with provenance and fidelity, reports and a scenario runner",
5
+ "keywords": [
6
+ "harmonyos",
7
+ "openharmony",
8
+ "ohos",
9
+ "performance",
10
+ "profiling",
11
+ "trace",
12
+ "hapray"
13
+ ],
14
+ "type": "module",
15
+ "main": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "engines": {
27
+ "node": "^22.13.0 || >=23.4.0"
28
+ },
29
+ "license": "MIT",
30
+ "author": "growvv",
31
+ "homepage": "https://growvv.github.io/ohos-perf/",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/growvv/ohos-perf.git",
35
+ "directory": "packages/core"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/growvv/ohos-perf/issues"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "scripts": {
44
+ "build": "tsup src/index.ts --format esm --dts",
45
+ "typecheck": "tsc --noEmit -p tsconfig.test.json",
46
+ "prepublishOnly": "npm run build"
47
+ }
48
+ }