Skip to main content

oxide_artifacts/
lib.rs

1/*
2 * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! Embedded device artifact bundles.
7//!
8//! The wire format is intentionally independent of a particular accelerator
9//! backend. A bundle names a producer, records the device target it was built
10//! for, and carries one or more generated device-code payloads.
11
12use core::fmt;
13
14pub const ARTIFACT_SECTION_NAME: &str = ".oxart";
15#[cfg(feature = "object-write")]
16const ARTIFACT_ANCHOR_SECTION_NAME: &str = ".oxlink";
17pub const ARTIFACT_MAGIC: [u8; 8] = *b"OXIDEART";
18pub const ARTIFACT_VERSION: u16 = 2;
19const LEGACY_ARTIFACT_VERSION: u16 = 1;
20
21const HEADER_BYTES: usize = 32;
22const PAYLOAD_RECORD_BYTES: usize = 24;
23const ENTRY_RECORD_BYTES: usize = 24;
24
25const OPTION_NO_FMA_CONTRACTION: u64 = 1 << 0;
26const OPTION_DEBUG_LINE_TABLES: u64 = 1 << 1;
27const OPTION_DEBUG_FULL: u64 = 1 << 2;
28const OPTION_DEBUG_MASK: u64 = OPTION_DEBUG_LINE_TABLES | OPTION_DEBUG_FULL;
29const KNOWN_COMPILE_OPTIONS: u64 = OPTION_NO_FMA_CONTRACTION | OPTION_DEBUG_MASK;
30
31/// Marker written on the second line of a versioned NVVM/LTOIR `.target`
32/// sidecar. Its presence makes older one-line readers reject the artifact
33/// instead of silently ignoring required compile policy. The marker versions
34/// the target/options handshake; the `.options` file carries its own v1/v2
35/// format header.
36pub const COMPILE_OPTIONS_TARGET_MARKER: &str = "compile-options=v1";
37
38const COMPILE_OPTIONS_SIDECAR_HEADER: &str = "cuda-oxide-compile-options-v1";
39const COMPILE_OPTIONS_FMA_ON: &str = "cuda-oxide-compile-options-v1\nfma-contraction=on\n";
40const COMPILE_OPTIONS_FMA_OFF: &str = "cuda-oxide-compile-options-v1\nfma-contraction=off\n";
41const COMPILE_OPTIONS_FMA_ON_LINE_TABLES: &str =
42    "cuda-oxide-compile-options-v2\nfma-contraction=on\ndebug=line-tables\n";
43const COMPILE_OPTIONS_FMA_OFF_LINE_TABLES: &str =
44    "cuda-oxide-compile-options-v2\nfma-contraction=off\ndebug=line-tables\n";
45const COMPILE_OPTIONS_FMA_ON_FULL_DEBUG: &str =
46    "cuda-oxide-compile-options-v2\nfma-contraction=on\ndebug=full\n";
47const COMPILE_OPTIONS_FMA_OFF_FULL_DEBUG: &str =
48    "cuda-oxide-compile-options-v2\nfma-contraction=off\ndebug=full\n";
49
50/// Debug information that later CUDA compilation/linking stages must retain.
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
52pub enum ArtifactDebugPolicy {
53    /// No device debug output is requested.
54    #[default]
55    None,
56    /// Preserve source line mappings without disabling optimization.
57    LineTables,
58    /// Preserve full debug information; libNVVM finalization runs unoptimized.
59    Full,
60}
61
62/// Compilation policy that must remain attached to a device artifact until
63/// its final machine-code generation step.
64///
65/// A zero value preserves the historical defaults, which keeps version-1
66/// bundles emitted before this field was used fully compatible.
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
68pub struct ArtifactCompileOptions(u64);
69
70impl ArtifactCompileOptions {
71    /// Construct the historical default policy.
72    pub const fn new() -> Self {
73        Self(0)
74    }
75
76    /// Record whether ordinary floating-point multiply/add expressions may
77    /// contract into fused operations.
78    pub const fn with_fma_contraction(mut self, enabled: bool) -> Self {
79        if enabled {
80            self.0 &= !OPTION_NO_FMA_CONTRACTION;
81        } else {
82            self.0 |= OPTION_NO_FMA_CONTRACTION;
83        }
84        self
85    }
86
87    /// Whether ordinary floating-point multiply/add expressions may contract.
88    pub const fn fma_contraction_enabled(self) -> bool {
89        self.0 & OPTION_NO_FMA_CONTRACTION == 0
90    }
91
92    /// Record the debug policy that all remaining CUDA compiler stages must
93    /// use.
94    pub const fn with_debug_policy(mut self, policy: ArtifactDebugPolicy) -> Self {
95        self.0 &= !OPTION_DEBUG_MASK;
96        self.0 |= match policy {
97            ArtifactDebugPolicy::None => 0,
98            ArtifactDebugPolicy::LineTables => OPTION_DEBUG_LINE_TABLES,
99            ArtifactDebugPolicy::Full => OPTION_DEBUG_FULL,
100        };
101        self
102    }
103
104    /// Debug policy attached to this artifact.
105    pub const fn debug_policy(self) -> ArtifactDebugPolicy {
106        match self.0 & OPTION_DEBUG_MASK {
107            OPTION_DEBUG_LINE_TABLES => ArtifactDebugPolicy::LineTables,
108            OPTION_DEBUG_FULL => ArtifactDebugPolicy::Full,
109            _ => ArtifactDebugPolicy::None,
110        }
111    }
112
113    fn from_bits(bits: u64) -> Result<Self, ArtifactError> {
114        if bits & !KNOWN_COMPILE_OPTIONS != 0 || bits & OPTION_DEBUG_MASK == OPTION_DEBUG_MASK {
115            return Err(ArtifactError::UnsupportedCompileOptions(bits));
116        }
117        Ok(Self(bits))
118    }
119
120    const fn bits(self) -> u64 {
121        self.0
122    }
123
124    /// Encode this policy for a sibling `.options` file.
125    pub const fn sidecar_text(self) -> &'static str {
126        match (self.fma_contraction_enabled(), self.debug_policy()) {
127            (true, ArtifactDebugPolicy::None) => COMPILE_OPTIONS_FMA_ON,
128            (false, ArtifactDebugPolicy::None) => COMPILE_OPTIONS_FMA_OFF,
129            (true, ArtifactDebugPolicy::LineTables) => COMPILE_OPTIONS_FMA_ON_LINE_TABLES,
130            (false, ArtifactDebugPolicy::LineTables) => COMPILE_OPTIONS_FMA_OFF_LINE_TABLES,
131            (true, ArtifactDebugPolicy::Full) => COMPILE_OPTIONS_FMA_ON_FULL_DEBUG,
132            (false, ArtifactDebugPolicy::Full) => COMPILE_OPTIONS_FMA_OFF_FULL_DEBUG,
133        }
134    }
135
136    /// Parse a complete `.options` file. Version 1 defaults to no debug policy;
137    /// version 2 records line-table or full-debug preservation explicitly.
138    pub fn from_sidecar_text(value: &str) -> Result<Self, ArtifactError> {
139        match value {
140            COMPILE_OPTIONS_FMA_ON => Ok(Self::new()),
141            COMPILE_OPTIONS_FMA_OFF => Ok(Self::new().with_fma_contraction(false)),
142            COMPILE_OPTIONS_FMA_ON_LINE_TABLES => {
143                Ok(Self::new().with_debug_policy(ArtifactDebugPolicy::LineTables))
144            }
145            COMPILE_OPTIONS_FMA_OFF_LINE_TABLES => Ok(Self::new()
146                .with_fma_contraction(false)
147                .with_debug_policy(ArtifactDebugPolicy::LineTables)),
148            COMPILE_OPTIONS_FMA_ON_FULL_DEBUG => {
149                Ok(Self::new().with_debug_policy(ArtifactDebugPolicy::Full))
150            }
151            COMPILE_OPTIONS_FMA_OFF_FULL_DEBUG => Ok(Self::new()
152                .with_fma_contraction(false)
153                .with_debug_policy(ArtifactDebugPolicy::Full)),
154            _ => Err(ArtifactError::MalformedCompileOptions(format!(
155                "expected `{COMPILE_OPTIONS_SIDECAR_HEADER}` or `cuda-oxide-compile-options-v2` with canonical fma/debug settings"
156            ))),
157        }
158    }
159}
160
161#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
162pub enum ArtifactPayloadKind {
163    Ptx,
164    NvvmIr,
165    Ltoir,
166    Cubin,
167}
168
169impl ArtifactPayloadKind {
170    pub const fn to_u16(self) -> u16 {
171        match self {
172            Self::Ptx => 0x100,
173            Self::NvvmIr => 0x110,
174            Self::Ltoir => 0x120,
175            Self::Cubin => 0x200,
176        }
177    }
178
179    pub const fn from_u16(value: u16) -> Option<Self> {
180        match value {
181            0x100 => Some(Self::Ptx),
182            0x110 => Some(Self::NvvmIr),
183            0x120 => Some(Self::Ltoir),
184            0x200 => Some(Self::Cubin),
185            _ => None,
186        }
187    }
188}
189
190#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
191pub enum ArtifactEntryKind {
192    Kernel,
193    DeviceFunction,
194}
195
196impl ArtifactEntryKind {
197    pub const fn to_u16(self) -> u16 {
198        match self {
199            Self::Kernel => 1,
200            Self::DeviceFunction => 2,
201        }
202    }
203
204    pub const fn from_u16(value: u16) -> Option<Self> {
205        match value {
206            1 => Some(Self::Kernel),
207            2 => Some(Self::DeviceFunction),
208            _ => None,
209        }
210    }
211}
212
213#[derive(Clone, Debug, PartialEq, Eq)]
214pub struct ArtifactPayloadSpec<'a> {
215    pub kind: ArtifactPayloadKind,
216    pub name: &'a str,
217    pub bytes: &'a [u8],
218}
219
220impl<'a> ArtifactPayloadSpec<'a> {
221    pub const fn new(kind: ArtifactPayloadKind, name: &'a str, bytes: &'a [u8]) -> Self {
222        Self { kind, name, bytes }
223    }
224}
225
226#[derive(Clone, Debug, PartialEq, Eq)]
227pub struct ArtifactEntrySpec<'a> {
228    pub symbol: &'a str,
229    pub kind: ArtifactEntryKind,
230    pub metadata: Option<u64>,
231}
232
233impl<'a> ArtifactEntrySpec<'a> {
234    pub const fn new(symbol: &'a str, kind: ArtifactEntryKind) -> Self {
235        Self {
236            symbol,
237            kind,
238            metadata: None,
239        }
240    }
241
242    pub const fn with_metadata(mut self, metadata: u64) -> Self {
243        self.metadata = Some(metadata);
244        self
245    }
246}
247
248#[derive(Clone, Debug, PartialEq, Eq)]
249pub struct ArtifactBundleSpec<'a> {
250    pub name: &'a str,
251    pub target: &'a str,
252    pub compile_options: ArtifactCompileOptions,
253    pub payloads: Vec<ArtifactPayloadSpec<'a>>,
254    pub entries: Vec<ArtifactEntrySpec<'a>>,
255}
256
257impl<'a> ArtifactBundleSpec<'a> {
258    pub fn new(name: &'a str, target: &'a str) -> Self {
259        Self {
260            name,
261            target,
262            compile_options: ArtifactCompileOptions::new(),
263            payloads: Vec::new(),
264            entries: Vec::new(),
265        }
266    }
267
268    pub fn with_payload(mut self, payload: ArtifactPayloadSpec<'a>) -> Self {
269        self.payloads.push(payload);
270        self
271    }
272
273    pub fn with_compile_options(mut self, options: ArtifactCompileOptions) -> Self {
274        self.compile_options = options;
275        self
276    }
277
278    pub fn with_entry(mut self, entry: ArtifactEntrySpec<'a>) -> Self {
279        self.entries.push(entry);
280        self
281    }
282}
283
284#[derive(Clone, Debug, PartialEq, Eq)]
285pub struct ArtifactPayload<'a> {
286    pub kind: ArtifactPayloadKind,
287    pub name: &'a str,
288    pub bytes: &'a [u8],
289}
290
291#[derive(Clone, Debug, PartialEq, Eq)]
292pub struct ArtifactEntry<'a> {
293    pub symbol: &'a str,
294    pub kind: ArtifactEntryKind,
295    pub metadata: Option<u64>,
296}
297
298#[derive(Clone, Debug, PartialEq, Eq)]
299pub struct ArtifactBundle<'a> {
300    pub name: &'a str,
301    pub target: &'a str,
302    pub compile_options: ArtifactCompileOptions,
303    pub payloads: Vec<ArtifactPayload<'a>>,
304    pub entries: Vec<ArtifactEntry<'a>>,
305}
306
307impl<'a> ArtifactBundle<'a> {
308    pub fn payload(&self, kind: ArtifactPayloadKind) -> Option<&'a [u8]> {
309        self.payloads
310            .iter()
311            .find(|payload| payload.kind == kind)
312            .map(|payload| payload.bytes)
313    }
314
315    pub fn entry(&self, symbol: &str) -> Option<&ArtifactEntry<'a>> {
316        self.entries.iter().find(|entry| entry.symbol == symbol)
317    }
318}
319
320#[derive(Clone, Debug, PartialEq, Eq)]
321pub struct OwnedArtifactPayload {
322    pub kind: ArtifactPayloadKind,
323    pub name: String,
324    pub bytes: Vec<u8>,
325}
326
327#[derive(Clone, Debug, PartialEq, Eq)]
328pub struct OwnedArtifactEntry {
329    pub symbol: String,
330    pub kind: ArtifactEntryKind,
331    pub metadata: Option<u64>,
332}
333
334#[derive(Clone, Debug, PartialEq, Eq)]
335pub struct OwnedArtifactBundle {
336    pub name: String,
337    pub target: String,
338    pub compile_options: ArtifactCompileOptions,
339    pub payloads: Vec<OwnedArtifactPayload>,
340    pub entries: Vec<OwnedArtifactEntry>,
341}
342
343impl OwnedArtifactBundle {
344    pub fn payload(&self, kind: ArtifactPayloadKind) -> Option<&[u8]> {
345        self.payloads
346            .iter()
347            .find(|payload| payload.kind == kind)
348            .map(|payload| payload.bytes.as_slice())
349    }
350
351    pub fn entry(&self, symbol: &str) -> Option<&OwnedArtifactEntry> {
352        self.entries.iter().find(|entry| entry.symbol == symbol)
353    }
354}
355
356impl<'a> From<ArtifactBundle<'a>> for OwnedArtifactBundle {
357    fn from(bundle: ArtifactBundle<'a>) -> Self {
358        Self {
359            name: bundle.name.to_string(),
360            target: bundle.target.to_string(),
361            compile_options: bundle.compile_options,
362            payloads: bundle
363                .payloads
364                .into_iter()
365                .map(|payload| OwnedArtifactPayload {
366                    kind: payload.kind,
367                    name: payload.name.to_string(),
368                    bytes: payload.bytes.to_vec(),
369                })
370                .collect(),
371            entries: bundle
372                .entries
373                .into_iter()
374                .map(|entry| OwnedArtifactEntry {
375                    symbol: entry.symbol.to_string(),
376                    kind: entry.kind,
377                    metadata: entry.metadata,
378                })
379                .collect(),
380        }
381    }
382}
383
384#[derive(Clone, Debug, PartialEq, Eq)]
385pub enum ArtifactError {
386    TooLarge(&'static str),
387    EmptyBundleName,
388    EmptyTarget,
389    EmptyPayloadName,
390    EmptyPayload,
391    EmptyEntrySymbol,
392    Truncated(&'static str),
393    BadMagic,
394    UnsupportedVersion(u16),
395    UnsupportedCompileOptions(u64),
396    MalformedCompileOptions(String),
397    UnsupportedPayloadKind(u16),
398    UnsupportedEntryKind(u16),
399    InvalidUtf8(&'static str),
400    UnsupportedHostTarget(String),
401    Object(String),
402    Malformed(String),
403}
404
405impl fmt::Display for ArtifactError {
406    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
407        match self {
408            Self::TooLarge(field) => write!(f, "embedded artifact {field} is too large"),
409            Self::EmptyBundleName => f.write_str("embedded artifact bundle name is empty"),
410            Self::EmptyTarget => f.write_str("embedded artifact target is empty"),
411            Self::EmptyPayloadName => f.write_str("embedded artifact payload name is empty"),
412            Self::EmptyPayload => f.write_str("embedded artifact payload is empty"),
413            Self::EmptyEntrySymbol => f.write_str("embedded artifact entry symbol is empty"),
414            Self::Truncated(field) => write!(f, "embedded artifact is truncated in {field}"),
415            Self::BadMagic => f.write_str("embedded artifact has bad magic"),
416            Self::UnsupportedVersion(version) => {
417                write!(f, "unsupported embedded artifact version {version}")
418            }
419            Self::UnsupportedCompileOptions(bits) => {
420                write!(
421                    f,
422                    "unsupported embedded artifact compile-options bits {bits:#x}"
423                )
424            }
425            Self::MalformedCompileOptions(message) => {
426                write!(f, "malformed cuda-oxide compile options: {message}")
427            }
428            Self::UnsupportedPayloadKind(kind) => {
429                write!(f, "unsupported embedded artifact payload kind {kind}")
430            }
431            Self::UnsupportedEntryKind(kind) => {
432                write!(f, "unsupported embedded artifact entry kind {kind}")
433            }
434            Self::InvalidUtf8(field) => write!(f, "embedded artifact {field} is not utf-8"),
435            Self::UnsupportedHostTarget(target) => {
436                write!(f, "unsupported host object target '{target}'")
437            }
438            Self::Object(message) | Self::Malformed(message) => f.write_str(message),
439        }
440    }
441}
442
443impl std::error::Error for ArtifactError {}
444
445pub fn build_artifact_blob(spec: &ArtifactBundleSpec<'_>) -> Result<Vec<u8>, ArtifactError> {
446    validate_spec(spec)?;
447
448    let mut out = vec![0; HEADER_BYTES];
449    push_bytes(&mut out, spec.name.as_bytes());
450    push_bytes(&mut out, spec.target.as_bytes());
451
452    let payload_record_start = out.len();
453    out.resize(out.len() + spec.payloads.len() * PAYLOAD_RECORD_BYTES, 0);
454    let entry_record_start = out.len();
455    out.resize(out.len() + spec.entries.len() * ENTRY_RECORD_BYTES, 0);
456
457    for (index, payload) in spec.payloads.iter().enumerate() {
458        let name_offset = checked_u32(out.len(), "payload name offset")?;
459        push_bytes(&mut out, payload.name.as_bytes());
460        align_vec(&mut out, 8);
461        let data_offset = checked_u32(out.len(), "payload data offset")?;
462        push_bytes(&mut out, payload.bytes);
463        align_vec(&mut out, 8);
464
465        let record = payload_record_start + index * PAYLOAD_RECORD_BYTES;
466        write_u16(&mut out, record, payload.kind.to_u16());
467        write_u16(&mut out, record + 2, 0);
468        write_u32(&mut out, record + 4, data_offset);
469        write_u32(
470            &mut out,
471            record + 8,
472            checked_u32(payload.bytes.len(), "payload length")?,
473        );
474        write_u32(&mut out, record + 12, name_offset);
475        write_u16(
476            &mut out,
477            record + 16,
478            checked_u16(payload.name.len(), "payload name length")?,
479        );
480    }
481
482    for (index, entry) in spec.entries.iter().enumerate() {
483        let symbol_offset = checked_u32(out.len(), "entry symbol offset")?;
484        push_bytes(&mut out, entry.symbol.as_bytes());
485        align_vec(&mut out, 8);
486
487        let record = entry_record_start + index * ENTRY_RECORD_BYTES;
488        write_u16(&mut out, record, entry.kind.to_u16());
489        write_u16(&mut out, record + 2, u16::from(entry.metadata.is_some()));
490        write_u64(&mut out, record + 4, entry.metadata.unwrap_or(0));
491        write_u32(&mut out, record + 12, symbol_offset);
492        write_u16(
493            &mut out,
494            record + 16,
495            checked_u16(entry.symbol.len(), "entry symbol length")?,
496        );
497    }
498
499    let total_len = checked_u32(out.len(), "total length")?;
500    out[0..8].copy_from_slice(&ARTIFACT_MAGIC);
501    // Keep default-policy bundles on v1 for backward compatibility. A bundle
502    // that carries required compile policy uses v2 so an older reader rejects
503    // it instead of silently ignoring the semantic flag.
504    let version = if spec.compile_options == ArtifactCompileOptions::new() {
505        LEGACY_ARTIFACT_VERSION
506    } else {
507        ARTIFACT_VERSION
508    };
509    write_u16(&mut out, 8, version);
510    write_u16(&mut out, 10, HEADER_BYTES as u16);
511    write_u32(&mut out, 12, total_len);
512    write_u16(&mut out, 16, checked_u16(spec.name.len(), "name length")?);
513    write_u16(
514        &mut out,
515        18,
516        checked_u16(spec.target.len(), "target length")?,
517    );
518    write_u16(
519        &mut out,
520        20,
521        checked_u16(spec.payloads.len(), "payload count")?,
522    );
523    write_u16(
524        &mut out,
525        22,
526        checked_u16(spec.entries.len(), "entry count")?,
527    );
528    write_u64(&mut out, 24, spec.compile_options.bits());
529
530    Ok(out)
531}
532
533pub fn parse_artifact_section(mut bytes: &[u8]) -> Result<Vec<ArtifactBundle<'_>>, ArtifactError> {
534    let mut bundles = Vec::new();
535    while !bytes.is_empty() {
536        if bytes.iter().all(|byte| *byte == 0) {
537            break;
538        }
539        let total_len = artifact_blob_total_len(bytes)?;
540        let (blob, rest) = bytes.split_at(total_len);
541        bundles.push(parse_artifact_blob(blob)?);
542        bytes = rest;
543    }
544    Ok(bundles)
545}
546
547pub fn parse_artifact_blob(bytes: &[u8]) -> Result<ArtifactBundle<'_>, ArtifactError> {
548    require_len(bytes, HEADER_BYTES, "header")?;
549    if bytes[0..8] != ARTIFACT_MAGIC {
550        return Err(ArtifactError::BadMagic);
551    }
552    let version = read_u16(bytes, 8)?;
553    if !matches!(version, LEGACY_ARTIFACT_VERSION | ARTIFACT_VERSION) {
554        return Err(ArtifactError::UnsupportedVersion(version));
555    }
556    let header_len = read_u16(bytes, 10)? as usize;
557    if header_len != HEADER_BYTES {
558        return Err(ArtifactError::Malformed(format!(
559            "unsupported embedded artifact header length {header_len}"
560        )));
561    }
562    let total_len = read_u32(bytes, 12)? as usize;
563    if total_len < HEADER_BYTES {
564        return Err(ArtifactError::Malformed(format!(
565            "embedded artifact length {total_len} is smaller than the header"
566        )));
567    }
568    if total_len > bytes.len() {
569        return Err(ArtifactError::Truncated("blob"));
570    }
571    let bytes = &bytes[..total_len];
572    let name_len = read_u16(bytes, 16)? as usize;
573    let target_len = read_u16(bytes, 18)? as usize;
574    let payload_count = read_u16(bytes, 20)? as usize;
575    let entry_count = read_u16(bytes, 22)? as usize;
576    let compile_options = if version == LEGACY_ARTIFACT_VERSION {
577        ArtifactCompileOptions::new()
578    } else {
579        ArtifactCompileOptions::from_bits(read_u64(bytes, 24)?)?
580    };
581
582    let mut cursor = HEADER_BYTES;
583    let name = read_str(bytes, cursor, name_len, "bundle name")?;
584    cursor += name_len;
585    let target = read_str(bytes, cursor, target_len, "target")?;
586    cursor += target_len;
587
588    let payload_records = cursor;
589    cursor = cursor
590        .checked_add(payload_count * PAYLOAD_RECORD_BYTES)
591        .ok_or(ArtifactError::TooLarge("payload records"))?;
592    require_len(bytes, cursor, "payload records")?;
593    let entry_records = cursor;
594    cursor = cursor
595        .checked_add(entry_count * ENTRY_RECORD_BYTES)
596        .ok_or(ArtifactError::TooLarge("entry records"))?;
597    require_len(bytes, cursor, "entry records")?;
598
599    let mut payloads = Vec::with_capacity(payload_count);
600    for index in 0..payload_count {
601        let record = payload_records + index * PAYLOAD_RECORD_BYTES;
602        let kind_raw = read_u16(bytes, record)?;
603        let kind = ArtifactPayloadKind::from_u16(kind_raw)
604            .ok_or(ArtifactError::UnsupportedPayloadKind(kind_raw))?;
605        let data_offset = read_u32(bytes, record + 4)? as usize;
606        let data_len = read_u32(bytes, record + 8)? as usize;
607        let name_offset = read_u32(bytes, record + 12)? as usize;
608        let name_len = read_u16(bytes, record + 16)? as usize;
609        let name = read_str(bytes, name_offset, name_len, "payload name")?;
610        let data = read_slice(bytes, data_offset, data_len, "payload data")?;
611        payloads.push(ArtifactPayload {
612            kind,
613            name,
614            bytes: data,
615        });
616    }
617
618    let mut entries = Vec::with_capacity(entry_count);
619    for index in 0..entry_count {
620        let record = entry_records + index * ENTRY_RECORD_BYTES;
621        let kind_raw = read_u16(bytes, record)?;
622        let kind = ArtifactEntryKind::from_u16(kind_raw)
623            .ok_or(ArtifactError::UnsupportedEntryKind(kind_raw))?;
624        let flags = read_u16(bytes, record + 2)?;
625        let metadata = if flags & 1 != 0 {
626            Some(read_u64(bytes, record + 4)?)
627        } else {
628            None
629        };
630        let symbol_offset = read_u32(bytes, record + 12)? as usize;
631        let symbol_len = read_u16(bytes, record + 16)? as usize;
632        let symbol = read_str(bytes, symbol_offset, symbol_len, "entry symbol")?;
633        entries.push(ArtifactEntry {
634            symbol,
635            kind,
636            metadata,
637        });
638    }
639
640    Ok(ArtifactBundle {
641        name,
642        target,
643        compile_options,
644        payloads,
645        entries,
646    })
647}
648
649pub fn artifact_blob_total_len(bytes: &[u8]) -> Result<usize, ArtifactError> {
650    require_len(bytes, HEADER_BYTES, "header")?;
651    if bytes[0..8] != ARTIFACT_MAGIC {
652        return Err(ArtifactError::BadMagic);
653    }
654    let total_len = read_u32(bytes, 12)? as usize;
655    if total_len < HEADER_BYTES {
656        return Err(ArtifactError::Malformed(format!(
657            "embedded artifact length {total_len} is smaller than the header"
658        )));
659    }
660    if total_len > bytes.len() {
661        return Err(ArtifactError::Truncated("blob"));
662    }
663    Ok(total_len)
664}
665
666#[cfg(feature = "object-read")]
667pub fn read_artifact_bundles_from_object_bytes(
668    bytes: &[u8],
669) -> Result<Vec<OwnedArtifactBundle>, ArtifactError> {
670    use object::{Object, ObjectSection};
671
672    let file = object::File::parse(bytes).map_err(|e| ArtifactError::Object(e.to_string()))?;
673    let mut bundles = Vec::new();
674    for section in file.sections() {
675        let name = section
676            .name()
677            .map_err(|e| ArtifactError::Object(e.to_string()))?;
678        if name != ARTIFACT_SECTION_NAME {
679            continue;
680        }
681        let data = section
682            .data()
683            .map_err(|e| ArtifactError::Object(e.to_string()))?;
684        bundles.extend(parse_artifact_section(data)?.into_iter().map(Into::into));
685    }
686    Ok(bundles)
687}
688
689/// Wrap an artifact section blob in a relocatable host object file.
690///
691/// The object contains a single `.oxart` data section. When
692/// `anchor_symbol` is given, a global symbol with that name is defined at
693/// the start of the section. The anchor matters for *library* crates:
694/// their artifact object becomes a member of an `.rlib` archive, and a
695/// linker only extracts an archive member when the member defines a
696/// symbol that resolves an outstanding undefined reference. Without a
697/// defined symbol the member is silently skipped and the bundle never
698/// reaches the final binary. Host-side code (the `#[cuda_module]` macro)
699/// emits a matching reference to the anchor to force the extraction.
700/// `SHF_GNU_RETAIN` on the section additionally protects it from
701/// `--gc-sections` once the member has been linked in.
702#[cfg(feature = "object-write")]
703pub fn build_host_object_for_target(
704    section_data: &[u8],
705    target: &str,
706    anchor_symbol: Option<&str>,
707) -> Result<Vec<u8>, ArtifactError> {
708    if section_data.is_empty() {
709        return Err(ArtifactError::EmptyPayload);
710    }
711
712    match anchor_symbol {
713        Some(anchor_symbol) => build_host_object_with_section(
714            ARTIFACT_SECTION_NAME,
715            section_data,
716            target,
717            &[(anchor_symbol, false)],
718        ),
719        None => build_host_object_with_section(ARTIFACT_SECTION_NAME, section_data, target, &[]),
720    }
721}
722
723/// Wrap an artifact blob with a target-specific anchor and a weak legacy alias.
724///
725/// New owner-filter-aware macros reference the target-specific symbol. The
726/// weak package-level alias keeps older macro expansions link-compatible while
727/// avoiding duplicate-symbol failures when one package has several targets.
728#[cfg(feature = "object-write")]
729pub fn build_host_object_for_target_with_legacy_anchor(
730    section_data: &[u8],
731    target: &str,
732    anchor_symbol: &str,
733    legacy_anchor_symbol: &str,
734) -> Result<Vec<u8>, ArtifactError> {
735    if section_data.is_empty() {
736        return Err(ArtifactError::EmptyPayload);
737    }
738    build_host_object_with_section(
739        ARTIFACT_SECTION_NAME,
740        section_data,
741        target,
742        &[(anchor_symbol, false), (legacy_anchor_symbol, true)],
743    )
744}
745
746/// Build a host object that only defines an artifact link-anchor symbol.
747///
748/// The CUDA backend uses this when an owner filter deliberately suppresses a
749/// crate's device artifact. Older `#[cuda_module]` expansions can still
750/// contain the legacy anchor reference, so the linker needs a matching weak
751/// definition even though no `.oxart` section should be embedded. Keeping the
752/// placeholder in a separate section means artifact discovery correctly sees
753/// no device bundle.
754#[cfg(feature = "object-write")]
755pub fn build_host_anchor_object_for_target(
756    target: &str,
757    anchor_symbol: &str,
758) -> Result<Vec<u8>, ArtifactError> {
759    if anchor_symbol.is_empty() {
760        return Err(ArtifactError::Malformed(
761            "embedded artifact anchor symbol is empty".to_string(),
762        ));
763    }
764
765    build_host_object_with_section(
766        ARTIFACT_ANCHOR_SECTION_NAME,
767        &[0],
768        target,
769        &[(anchor_symbol, true)],
770    )
771}
772
773#[cfg(feature = "object-write")]
774fn build_host_object_with_section(
775    section_name: &str,
776    section_data: &[u8],
777    target: &str,
778    anchor_symbols: &[(&str, bool)],
779) -> Result<Vec<u8>, ArtifactError> {
780    use object::write::{Object, Symbol, SymbolSection};
781    use object::{SectionFlags, SectionKind, SymbolFlags, SymbolKind, SymbolScope};
782
783    let target = HostObjectTarget::parse(target)?;
784    let mut object = Object::new(target.format, target.architecture, target.endianness);
785    let section_id = object.add_section(
786        Vec::new(),
787        section_name.as_bytes().to_vec(),
788        SectionKind::Data,
789    );
790    let section = object.section_mut(section_id);
791    section.set_data(section_data.to_vec(), 8);
792    section.flags = SectionFlags::Elf {
793        sh_flags: elf::SHF_ALLOC | elf::SHF_GNU_RETAIN,
794    };
795
796    for (anchor_symbol, weak) in anchor_symbols {
797        // Global binding so the symbol can satisfy undefined references
798        // from other objects (that is what triggers archive extraction);
799        // `Linkage` scope so it stays hidden and never leaks into the
800        // dynamic symbol table of the final binary.
801        object.add_symbol(Symbol {
802            name: anchor_symbol.as_bytes().to_vec(),
803            value: 0,
804            size: 0,
805            kind: SymbolKind::Data,
806            scope: SymbolScope::Linkage,
807            weak: *weak,
808            section: SymbolSection::Section(section_id),
809            flags: SymbolFlags::None,
810        });
811    }
812
813    object
814        .write()
815        .map_err(|e| ArtifactError::Object(e.to_string()))
816}
817
818#[cfg(feature = "object-write")]
819#[derive(Clone, Copy, Debug, PartialEq, Eq)]
820struct HostObjectTarget {
821    format: object::BinaryFormat,
822    architecture: object::Architecture,
823    endianness: object::Endianness,
824}
825
826#[cfg(feature = "object-write")]
827impl HostObjectTarget {
828    fn parse(target: &str) -> Result<Self, ArtifactError> {
829        let target = target.to_ascii_lowercase();
830        let (architecture, endianness) = if target.starts_with("x86_64")
831            || target.starts_with("amd64")
832            || target.starts_with("x86-64")
833        {
834            (object::Architecture::X86_64, object::Endianness::Little)
835        } else if target.starts_with("aarch64") || target.starts_with("arm64") {
836            (object::Architecture::Aarch64, object::Endianness::Little)
837        } else {
838            return Err(ArtifactError::UnsupportedHostTarget(target));
839        };
840
841        let format = if target.contains("linux") {
842            object::BinaryFormat::Elf
843        } else {
844            return Err(ArtifactError::UnsupportedHostTarget(target));
845        };
846
847        Ok(Self {
848            format,
849            architecture,
850            endianness,
851        })
852    }
853}
854
855#[cfg(feature = "object-write")]
856mod elf {
857    pub const SHF_ALLOC: u64 = 0x2;
858    pub const SHF_GNU_RETAIN: u64 = 0x20_0000;
859}
860
861fn validate_spec(spec: &ArtifactBundleSpec<'_>) -> Result<(), ArtifactError> {
862    if spec.name.is_empty() {
863        return Err(ArtifactError::EmptyBundleName);
864    }
865    if spec.target.is_empty() {
866        return Err(ArtifactError::EmptyTarget);
867    }
868    if spec.payloads.is_empty() {
869        return Err(ArtifactError::EmptyPayload);
870    }
871    for payload in &spec.payloads {
872        if payload.name.is_empty() {
873            return Err(ArtifactError::EmptyPayloadName);
874        }
875        if payload.bytes.is_empty() {
876            return Err(ArtifactError::EmptyPayload);
877        }
878    }
879    for entry in &spec.entries {
880        if entry.symbol.is_empty() {
881            return Err(ArtifactError::EmptyEntrySymbol);
882        }
883    }
884    Ok(())
885}
886
887fn checked_u16(value: usize, field: &'static str) -> Result<u16, ArtifactError> {
888    u16::try_from(value).map_err(|_| ArtifactError::TooLarge(field))
889}
890
891fn checked_u32(value: usize, field: &'static str) -> Result<u32, ArtifactError> {
892    u32::try_from(value).map_err(|_| ArtifactError::TooLarge(field))
893}
894
895fn push_bytes(out: &mut Vec<u8>, bytes: &[u8]) {
896    out.extend_from_slice(bytes);
897}
898
899fn align_vec(out: &mut Vec<u8>, alignment: usize) {
900    let rem = out.len() % alignment;
901    if rem != 0 {
902        out.resize(out.len() + alignment - rem, 0);
903    }
904}
905
906fn read_slice<'a>(
907    bytes: &'a [u8],
908    offset: usize,
909    len: usize,
910    field: &'static str,
911) -> Result<&'a [u8], ArtifactError> {
912    let end = offset
913        .checked_add(len)
914        .ok_or(ArtifactError::TooLarge(field))?;
915    bytes
916        .get(offset..end)
917        .ok_or(ArtifactError::Truncated(field))
918}
919
920fn read_str<'a>(
921    bytes: &'a [u8],
922    offset: usize,
923    len: usize,
924    field: &'static str,
925) -> Result<&'a str, ArtifactError> {
926    let bytes = read_slice(bytes, offset, len, field)?;
927    core::str::from_utf8(bytes).map_err(|_| ArtifactError::InvalidUtf8(field))
928}
929
930fn require_len(bytes: &[u8], len: usize, field: &'static str) -> Result<(), ArtifactError> {
931    if bytes.len() < len {
932        Err(ArtifactError::Truncated(field))
933    } else {
934        Ok(())
935    }
936}
937
938fn read_u16(bytes: &[u8], offset: usize) -> Result<u16, ArtifactError> {
939    let bytes = read_slice(bytes, offset, 2, "u16")?;
940    Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
941}
942
943fn read_u32(bytes: &[u8], offset: usize) -> Result<u32, ArtifactError> {
944    let bytes = read_slice(bytes, offset, 4, "u32")?;
945    Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
946}
947
948fn read_u64(bytes: &[u8], offset: usize) -> Result<u64, ArtifactError> {
949    let bytes = read_slice(bytes, offset, 8, "u64")?;
950    Ok(u64::from_le_bytes([
951        bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
952    ]))
953}
954
955fn write_u16(out: &mut [u8], offset: usize, value: u16) {
956    out[offset..offset + 2].copy_from_slice(&value.to_le_bytes());
957}
958
959fn write_u32(out: &mut [u8], offset: usize, value: u32) {
960    out[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
961}
962
963fn write_u64(out: &mut [u8], offset: usize, value: u64) {
964    out[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
965}
966
967#[cfg(test)]
968mod tests {
969    use super::*;
970
971    fn sample_blob() -> Vec<u8> {
972        build_artifact_blob(
973            &ArtifactBundleSpec::new("demo", "sm_90")
974                .with_payload(ArtifactPayloadSpec::new(
975                    ArtifactPayloadKind::Ptx,
976                    "demo.ptx",
977                    b"ptx",
978                ))
979                .with_entry(ArtifactEntrySpec::new("hello", ArtifactEntryKind::Kernel)),
980        )
981        .unwrap()
982    }
983
984    fn sample_payload_record_start() -> usize {
985        HEADER_BYTES + "demo".len() + "sm_90".len()
986    }
987
988    #[test]
989    fn artifact_blob_round_trips_ptx_payload() {
990        let blob = sample_blob();
991        assert_eq!(read_u16(&blob, 8).unwrap(), LEGACY_ARTIFACT_VERSION);
992        let bundles = parse_artifact_section(&blob).unwrap();
993
994        assert_eq!(bundles.len(), 1);
995        assert_eq!(bundles[0].name, "demo");
996        assert_eq!(bundles[0].target, "sm_90");
997        assert!(bundles[0].compile_options.fma_contraction_enabled());
998        assert_eq!(
999            bundles[0].payload(ArtifactPayloadKind::Ptx),
1000            Some(&b"ptx"[..])
1001        );
1002        assert_eq!(
1003            bundles[0].entry("hello").unwrap().kind,
1004            ArtifactEntryKind::Kernel
1005        );
1006    }
1007
1008    #[test]
1009    fn artifact_blob_round_trips_non_ptx_payload_kinds() {
1010        let blob = build_artifact_blob(
1011            &ArtifactBundleSpec::new("demo", "sm_90")
1012                .with_compile_options(ArtifactCompileOptions::new().with_fma_contraction(false))
1013                .with_payload(ArtifactPayloadSpec::new(
1014                    ArtifactPayloadKind::NvvmIr,
1015                    "demo.ll",
1016                    b"nvvm ir",
1017                ))
1018                .with_payload(ArtifactPayloadSpec::new(
1019                    ArtifactPayloadKind::Ltoir,
1020                    "demo.ltoir",
1021                    b"ltoir",
1022                ))
1023                .with_payload(ArtifactPayloadSpec::new(
1024                    ArtifactPayloadKind::Cubin,
1025                    "demo.cubin",
1026                    b"cubin",
1027                )),
1028        )
1029        .unwrap();
1030        assert_eq!(read_u16(&blob, 8).unwrap(), ARTIFACT_VERSION);
1031        let bundles = parse_artifact_section(&blob).unwrap();
1032
1033        assert_eq!(bundles.len(), 1);
1034        assert!(!bundles[0].compile_options.fma_contraction_enabled());
1035        assert_eq!(
1036            bundles[0].payload(ArtifactPayloadKind::NvvmIr),
1037            Some(&b"nvvm ir"[..])
1038        );
1039        assert_eq!(
1040            bundles[0].payload(ArtifactPayloadKind::Ltoir),
1041            Some(&b"ltoir"[..])
1042        );
1043        assert_eq!(
1044            bundles[0].payload(ArtifactPayloadKind::Cubin),
1045            Some(&b"cubin"[..])
1046        );
1047    }
1048
1049    #[test]
1050    fn legacy_v1_bundle_defaults_to_fma_contraction() {
1051        let mut blob = sample_blob();
1052        write_u16(&mut blob, 8, LEGACY_ARTIFACT_VERSION);
1053        // Version 1 reserved these bytes. A new reader must ignore them and
1054        // preserve the historical default rather than assigning new meaning.
1055        write_u64(&mut blob, 24, OPTION_NO_FMA_CONTRACTION);
1056
1057        let bundle = parse_artifact_blob(&blob).unwrap();
1058        assert!(bundle.compile_options.fma_contraction_enabled());
1059        assert_eq!(
1060            bundle.compile_options.debug_policy(),
1061            ArtifactDebugPolicy::None
1062        );
1063    }
1064
1065    #[test]
1066    fn version_2_rejects_unknown_compile_option_bits() {
1067        let mut blob = sample_blob();
1068        write_u16(&mut blob, 8, ARTIFACT_VERSION);
1069        write_u64(&mut blob, 24, 1 << 63);
1070
1071        assert!(matches!(
1072            parse_artifact_blob(&blob),
1073            Err(ArtifactError::UnsupportedCompileOptions(bits)) if bits == 1 << 63
1074        ));
1075    }
1076
1077    #[test]
1078    fn compile_options_sidecar_round_trips_fma_and_debug_policies() {
1079        for allow_fma_contraction in [true, false] {
1080            for debug in [
1081                ArtifactDebugPolicy::None,
1082                ArtifactDebugPolicy::LineTables,
1083                ArtifactDebugPolicy::Full,
1084            ] {
1085                let expected = ArtifactCompileOptions::new()
1086                    .with_fma_contraction(allow_fma_contraction)
1087                    .with_debug_policy(debug);
1088                let parsed =
1089                    ArtifactCompileOptions::from_sidecar_text(expected.sidecar_text()).unwrap();
1090                assert_eq!(parsed, expected);
1091            }
1092        }
1093        assert!(ArtifactCompileOptions::from_sidecar_text("fma-contraction=off\n").is_err());
1094    }
1095
1096    #[test]
1097    fn artifact_blob_round_trips_each_debug_policy() {
1098        for debug in [ArtifactDebugPolicy::LineTables, ArtifactDebugPolicy::Full] {
1099            let expected = ArtifactCompileOptions::new()
1100                .with_fma_contraction(false)
1101                .with_debug_policy(debug);
1102            let blob = build_artifact_blob(
1103                &ArtifactBundleSpec::new("debug", "sm_90")
1104                    .with_compile_options(expected)
1105                    .with_payload(ArtifactPayloadSpec::new(
1106                        ArtifactPayloadKind::NvvmIr,
1107                        "debug.ll",
1108                        b"nvvm ir",
1109                    )),
1110            )
1111            .unwrap();
1112
1113            assert_eq!(read_u16(&blob, 8).unwrap(), ARTIFACT_VERSION);
1114            assert_eq!(
1115                parse_artifact_blob(&blob).unwrap().compile_options,
1116                expected
1117            );
1118        }
1119    }
1120
1121    #[test]
1122    fn version_2_rejects_conflicting_debug_bits() {
1123        let mut blob = sample_blob();
1124        write_u16(&mut blob, 8, ARTIFACT_VERSION);
1125        write_u64(&mut blob, 24, OPTION_DEBUG_MASK);
1126
1127        assert!(matches!(
1128            parse_artifact_blob(&blob),
1129            Err(ArtifactError::UnsupportedCompileOptions(bits)) if bits == OPTION_DEBUG_MASK
1130        ));
1131    }
1132
1133    #[test]
1134    fn artifact_section_ignores_trailing_zero_padding() {
1135        let mut section = sample_blob();
1136        section.extend_from_slice(&[0; HEADER_BYTES]);
1137
1138        let bundles = parse_artifact_section(&section).unwrap();
1139        assert_eq!(bundles.len(), 1);
1140        assert_eq!(bundles[0].name, "demo");
1141    }
1142
1143    #[test]
1144    fn artifact_section_parses_concatenated_blobs() {
1145        let mut first = build_artifact_blob(&ArtifactBundleSpec::new("a", "sm_80").with_payload(
1146            ArtifactPayloadSpec::new(ArtifactPayloadKind::Ptx, "a.ptx", b"a"),
1147        ))
1148        .unwrap();
1149        write_u16(&mut first, 8, LEGACY_ARTIFACT_VERSION);
1150        let second = build_artifact_blob(&ArtifactBundleSpec::new("b", "sm_90").with_payload(
1151            ArtifactPayloadSpec::new(ArtifactPayloadKind::Ptx, "b.ptx", b"b"),
1152        ))
1153        .unwrap();
1154
1155        let mut section = first;
1156        section.extend_from_slice(&second);
1157
1158        let bundles = parse_artifact_section(&section).unwrap();
1159        assert_eq!(
1160            bundles.iter().map(|bundle| bundle.name).collect::<Vec<_>>(),
1161            ["a", "b"]
1162        );
1163    }
1164
1165    #[test]
1166    fn artifact_section_rejects_truncated_blob_without_panicking() {
1167        let mut blob = sample_blob();
1168        let oversized_len = (blob.len() + 1) as u32;
1169        write_u32(&mut blob, 12, oversized_len);
1170
1171        let error = parse_artifact_section(&blob).unwrap_err();
1172        assert_eq!(error, ArtifactError::Truncated("blob"));
1173    }
1174
1175    #[test]
1176    fn artifact_blob_rejects_total_len_smaller_than_header() {
1177        let mut blob = sample_blob();
1178        write_u32(&mut blob, 12, (HEADER_BYTES - 1) as u32);
1179
1180        let error = parse_artifact_blob(&blob).unwrap_err();
1181        assert!(matches!(
1182            error,
1183            ArtifactError::Malformed(message) if message.contains("smaller than the header")
1184        ));
1185    }
1186
1187    #[test]
1188    fn artifact_blob_rejects_invalid_utf8_payload_name() {
1189        let mut blob = sample_blob();
1190        let payload_record = sample_payload_record_start();
1191        let payload_name_offset = read_u32(&blob, payload_record + 12).unwrap() as usize;
1192        blob[payload_name_offset] = 0xff;
1193
1194        let error = parse_artifact_blob(&blob).unwrap_err();
1195        assert_eq!(error, ArtifactError::InvalidUtf8("payload name"));
1196    }
1197
1198    #[test]
1199    fn artifact_blob_rejects_unknown_payload_kind() {
1200        let mut blob = sample_blob();
1201        write_u16(&mut blob, sample_payload_record_start(), 0xffff);
1202
1203        let error = parse_artifact_blob(&blob).unwrap_err();
1204        assert_eq!(error, ArtifactError::UnsupportedPayloadKind(0xffff));
1205    }
1206
1207    #[test]
1208    fn artifact_section_name_is_portable() {
1209        assert!(ARTIFACT_SECTION_NAME.len() <= 8);
1210    }
1211
1212    #[cfg(all(feature = "object-read", feature = "object-write"))]
1213    #[test]
1214    fn host_object_round_trips_section_on_supported_formats() {
1215        let blob = build_artifact_blob(
1216            &ArtifactBundleSpec::new("demo", "sm_90")
1217                .with_compile_options(ArtifactCompileOptions::new().with_fma_contraction(false))
1218                .with_payload(ArtifactPayloadSpec::new(
1219                    ArtifactPayloadKind::Ptx,
1220                    "demo.ptx",
1221                    b"ptx",
1222                )),
1223        )
1224        .unwrap();
1225
1226        for target in ["x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu"] {
1227            let object = build_host_object_for_target(&blob, target, None).unwrap();
1228            let bundles = read_artifact_bundles_from_object_bytes(&object).unwrap();
1229            assert_eq!(bundles.len(), 1);
1230            assert_eq!(
1231                bundles[0].payload(ArtifactPayloadKind::Ptx),
1232                Some(&b"ptx"[..])
1233            );
1234            assert!(!bundles[0].compile_options.fma_contraction_enabled());
1235        }
1236    }
1237
1238    /// The anchor symbol must be a *defined* global pointing at the
1239    /// `.oxart` section. A linker only extracts an rlib archive member if
1240    /// the member defines a symbol someone references, so an undefined or
1241    /// missing anchor would reintroduce the dropped-bundle bug.
1242    #[cfg(all(feature = "object-read", feature = "object-write"))]
1243    #[test]
1244    fn host_object_defines_requested_anchor_symbol() {
1245        use object::{Object, ObjectSymbol};
1246
1247        let blob = sample_blob();
1248        let bytes =
1249            build_host_object_for_target(&blob, "x86_64-unknown-linux-gnu", Some("demo_anchor"))
1250                .unwrap();
1251
1252        let file = object::File::parse(bytes.as_slice()).unwrap();
1253        let anchor = file
1254            .symbols()
1255            .find(|symbol| symbol.name() == Ok("demo_anchor"))
1256            .expect("anchor symbol missing from artifact object");
1257        assert!(anchor.is_definition());
1258        assert!(anchor.is_global());
1259        assert_eq!(anchor.address(), 0);
1260
1261        // The data must still round-trip with the symbol present.
1262        let bundles = read_artifact_bundles_from_object_bytes(&bytes).unwrap();
1263        assert_eq!(bundles.len(), 1);
1264        assert_eq!(bundles[0].name, "demo");
1265    }
1266
1267    /// Omitting the anchor must keep producing a symbol-free object (the
1268    /// shape used by tests and any non-rlib embedding).
1269    #[cfg(all(feature = "object-read", feature = "object-write"))]
1270    #[test]
1271    fn host_object_without_anchor_has_no_symbols() {
1272        use object::Object;
1273
1274        let blob = sample_blob();
1275        let bytes = build_host_object_for_target(&blob, "x86_64-unknown-linux-gnu", None).unwrap();
1276
1277        let file = object::File::parse(bytes.as_slice()).unwrap();
1278        assert_eq!(file.symbols().count(), 0);
1279    }
1280
1281    /// A filtered crate still needs to satisfy the host macro's anchor
1282    /// reference, but it must not look like it contains a device artifact.
1283    #[cfg(all(feature = "object-read", feature = "object-write"))]
1284    #[test]
1285    fn anchor_only_object_defines_symbol_without_artifact_section() {
1286        use object::{Object, ObjectSymbol};
1287
1288        let bytes = build_host_anchor_object_for_target(
1289            "x86_64-unknown-linux-gnu",
1290            "filtered_crate_anchor",
1291        )
1292        .unwrap();
1293        let file = object::File::parse(bytes.as_slice()).unwrap();
1294        let anchor = file
1295            .symbols()
1296            .find(|symbol| symbol.name() == Ok("filtered_crate_anchor"))
1297            .expect("anchor symbol missing from placeholder object");
1298
1299        assert!(anchor.is_definition());
1300        assert!(anchor.is_global());
1301        assert!(anchor.is_weak());
1302        assert!(
1303            read_artifact_bundles_from_object_bytes(&bytes)
1304                .unwrap()
1305                .is_empty()
1306        );
1307    }
1308
1309    #[cfg(feature = "object-write")]
1310    #[test]
1311    fn anchor_only_object_rejects_empty_symbol() {
1312        assert!(matches!(
1313            build_host_anchor_object_for_target("x86_64-unknown-linux-gnu", ""),
1314            Err(ArtifactError::Malformed(_))
1315        ));
1316    }
1317
1318    #[cfg(all(feature = "object-read", feature = "object-write"))]
1319    #[test]
1320    fn target_anchor_object_also_defines_weak_legacy_alias() {
1321        use object::{Object, ObjectSymbol};
1322
1323        let blob = sample_blob();
1324        let bytes = build_host_object_for_target_with_legacy_anchor(
1325            &blob,
1326            "x86_64-unknown-linux-gnu",
1327            "target_anchor",
1328            "legacy_anchor",
1329        )
1330        .unwrap();
1331        let file = object::File::parse(bytes.as_slice()).unwrap();
1332        let target = file
1333            .symbols()
1334            .find(|symbol| symbol.name() == Ok("target_anchor"))
1335            .expect("target-specific anchor missing");
1336        let legacy = file
1337            .symbols()
1338            .find(|symbol| symbol.name() == Ok("legacy_anchor"))
1339            .expect("legacy anchor alias missing");
1340
1341        assert!(target.is_definition());
1342        assert!(!target.is_weak());
1343        assert!(legacy.is_definition());
1344        assert!(legacy.is_weak());
1345        assert_eq!(
1346            read_artifact_bundles_from_object_bytes(&bytes)
1347                .unwrap()
1348                .len(),
1349            1
1350        );
1351    }
1352
1353    /// A strong undefined reference must pull an archive member whose matching
1354    /// compatibility alias is weak; otherwise old macros could link but lose
1355    /// the actual `.oxart` payload.
1356    #[cfg(all(
1357        target_os = "linux",
1358        target_arch = "x86_64",
1359        feature = "object-read",
1360        feature = "object-write"
1361    ))]
1362    #[test]
1363    fn weak_legacy_alias_extracts_artifact_from_static_archive() {
1364        use std::process::Command;
1365
1366        let unique = std::time::SystemTime::now()
1367            .duration_since(std::time::UNIX_EPOCH)
1368            .unwrap()
1369            .as_nanos();
1370        let root = std::env::temp_dir().join(format!(
1371            "oxide_artifact_weak_archive_{}_{}",
1372            std::process::id(),
1373            unique
1374        ));
1375        std::fs::create_dir_all(&root).unwrap();
1376
1377        let object = build_host_object_for_target_with_legacy_anchor(
1378            &sample_blob(),
1379            "x86_64-unknown-linux-gnu",
1380            "target_anchor",
1381            "legacy_anchor",
1382        )
1383        .unwrap();
1384        let object_path = root.join("artifact.o");
1385        let archive_path = root.join("libartifact.a");
1386        let source_path = root.join("main.c");
1387        let binary_path = root.join("app");
1388        std::fs::write(&object_path, object).unwrap();
1389        std::fs::write(
1390            &source_path,
1391            b"extern const unsigned char legacy_anchor;\nint main(void) { return legacy_anchor; }\n",
1392        )
1393        .unwrap();
1394
1395        let ar = Command::new("ar")
1396            .args(["crs"])
1397            .arg(&archive_path)
1398            .arg(&object_path)
1399            .status()
1400            .expect("`ar` is required for the static-archive anchor test");
1401        assert!(ar.success(), "failed to create static archive");
1402        let cc = Command::new("cc")
1403            .arg(&source_path)
1404            .arg(&archive_path)
1405            .arg("-Wl,-z,noexecstack")
1406            .arg("-o")
1407            .arg(&binary_path)
1408            .status()
1409            .expect("a C linker driver is required for the anchor test");
1410        assert!(
1411            cc.success(),
1412            "weak anchor did not resolve the host reference"
1413        );
1414
1415        let executable = std::fs::read(&binary_path).unwrap();
1416        let bundles = read_artifact_bundles_from_object_bytes(&executable).unwrap();
1417        assert_eq!(bundles.len(), 1, "archive payload was not extracted");
1418        assert_eq!(bundles[0].name, "demo");
1419        std::fs::remove_dir_all(root).unwrap();
1420    }
1421
1422    #[cfg(feature = "object-write")]
1423    #[test]
1424    fn host_object_rejects_non_cuda_host_targets() {
1425        let blob = sample_blob();
1426
1427        for target in ["powerpc64le-unknown-linux-gnu", "x86_64-apple-darwin"] {
1428            assert!(matches!(
1429                build_host_object_for_target(&blob, target, None),
1430                Err(ArtifactError::UnsupportedHostTarget(_))
1431            ));
1432        }
1433    }
1434}