rialo-build-lib 0.10.1

Shared library for Rialo program building logic
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::path::Path;

use anyhow::{Context, Result};

use super::{BuildConfig, BuildResult, CompileFlags, ProgramBuilder, RiscvTarget};
use crate::{
    sanitize_nested_cargo_env,
    toolchain::{GnuRiscvToolchain, RialoRustToolchain, Toolchain},
};

/// Convert a RISC-V ELF file to a PolkaVM blob
///
/// This function uses the polkavm-linker with production settings:
/// - Strip debug symbols
/// - Optimize the blob (O1 to work around a linker bug)
/// - Set minimum stack size to 256KB (0x40000 bytes)
///
/// This is the same configuration used by the simulator's `load_elf_with_linking()` method.
fn link_elf_to_polkavm(elf_bytes: &[u8]) -> Result<Vec<u8>> {
    // Configure linker with production settings
    let mut config = polkavm_linker::Config::default();
    config.set_strip(true);
    config.set_optimize(true);
    config.set_min_stack_size(0x40000); // 256KB stack

    // FIXME(SUB-1596): Use O1 optimization instead of O2 by default due to a bug
    // that generates invalid return addresses in `__fixunsdfdi` (f64→u64 conversion).
    config.set_opt_level(polkavm_linker::OptLevel::O1);

    // Link ELF to PolkaVM blob
    polkavm_linker::program_from_elf(config, elf_bytes)
        .map_err(|e| anyhow::anyhow!("PolkaVM linking failed: {}", e))
}

/// RISC-V program builder
///
/// Supports building both C and Rust programs:
/// - C programs: Uses GNU RISC-V toolchain (gcc, binutils)
/// - Rust programs: Uses Rialo custom Rust toolchain (cargo +rialo)
pub struct RiscvBuilder {
    /// GNU RISC-V toolchain for C programs
    gnu_toolchain: GnuRiscvToolchain,
    /// Rialo Rust toolchain for Rust programs
    rust_toolchain: Option<RialoRustToolchain>,
    /// Target architecture
    target: RiscvTarget,
    /// Custom compile flags for C programs
    compile_flags: Option<CompileFlags>,
}

impl RiscvBuilder {
    /// Create a new RISC-V builder with default toolchain versions
    pub fn new(target: RiscvTarget) -> Result<Self> {
        let gnu_toolchain = GnuRiscvToolchain::new()?;

        // Initialize Rialo Rust toolchain if needed for this target
        let rust_toolchain = if target.requires_rialo_toolchain() {
            Some(RialoRustToolchain::new()?)
        } else {
            None
        };

        Ok(Self {
            gnu_toolchain,
            rust_toolchain,
            target,
            compile_flags: None,
        })
    }

    /// Create a new RISC-V builder with specific toolchain versions
    pub fn with_version(version: &str, target: RiscvTarget) -> Result<Self> {
        let gnu_toolchain = GnuRiscvToolchain::with_version(version)?;

        // Initialize Rialo Rust toolchain if needed for this target
        let rust_toolchain = if target.requires_rialo_toolchain() {
            Some(RialoRustToolchain::with_version(version)?)
        } else {
            None
        };

        Ok(Self {
            gnu_toolchain,
            rust_toolchain,
            target,
            compile_flags: None,
        })
    }

    /// Set custom compile flags
    pub fn with_compile_flags(mut self, flags: CompileFlags) -> Self {
        self.compile_flags = Some(flags);
        self
    }

    /// Check if a directory contains C source files (.c or .S)
    fn has_c_source_files(dir: &Path) -> bool {
        if let Ok(entries) = std::fs::read_dir(dir) {
            for entry in entries.flatten() {
                if let Some(ext) = entry.path().extension().and_then(|e| e.to_str()) {
                    if ext == "c" || ext == "S" {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Detect the program type based on directory contents
    fn detect_program_type(&self, dir: &Path) -> Result<ProgramType> {
        let cargo_toml = dir.join("Cargo.toml");
        let has_cargo_toml = cargo_toml.exists();

        // Check for C source files in root directory
        let has_c_files = Self::has_c_source_files(dir);

        // Check src directory for C files
        let src_dir = dir.join("src");
        let has_c_in_src = src_dir.exists() && Self::has_c_source_files(&src_dir);

        if has_cargo_toml {
            Ok(ProgramType::Rust)
        } else if has_c_files || has_c_in_src {
            Ok(ProgramType::C)
        } else {
            Err(anyhow::anyhow!(
                "Could not detect program type. Directory must contain either Cargo.toml (Rust) or .c/.S files (C)"
            ))
        }
    }

    /// Build a C program
    fn build_c_program(&self, config: &BuildConfig) -> Result<BuildResult> {
        println!("Building C program for RISC-V...");

        // Get the program name from directory
        let program_name = config
            .program_path
            .file_name()
            .context("Failed to get program directory name")?
            .to_str()
            .context("Failed to convert directory name to string")?;

        // Create output directory
        let output_dir = config.output_dir.join(format!("{program_name}-riscv"));
        std::fs::create_dir_all(&output_dir).with_context(|| {
            format!("Failed to create output directory {}", output_dir.display())
        })?;

        // Collect all C and assembly source files
        let mut source_files = Vec::new();
        let src_dir = config.program_path.join("src");
        let search_dirs = if src_dir.exists() {
            vec![&config.program_path, &src_dir]
        } else {
            vec![&config.program_path]
        };

        for dir in search_dirs {
            if let Ok(entries) = std::fs::read_dir(dir) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                        if ext == "c" || ext == "S" {
                            source_files.push(path);
                        }
                    }
                }
            }
        }

        if source_files.is_empty() {
            return Err(anyhow::anyhow!(
                "No C source files (.c or .S) found in {}",
                config.program_path.display()
            ));
        }

        println!("Found {} source files", source_files.len());

        // Get toolchain bin path
        let bin_path = self.gnu_toolchain.get_bin_path()?;
        let gcc_path = bin_path.join(format!("{}-gcc", self.gnu_toolchain.get_tool_prefix()));

        // Build the program
        let output_elf = output_dir.join(format!("{program_name}.elf"));

        let mut command = std::process::Command::new(&gcc_path);

        // Apply compile flags (custom or default)
        if let Some(flags) = &self.compile_flags {
            // Use custom flags from config
            if let Some(march) = &flags.march {
                command.args(["-march", march]);
            } else {
                command.args(["-march", self.target.as_march()]);
            }

            if let Some(mabi) = &flags.mabi {
                command.args(["-mabi", mabi]);
            } else {
                command.args(["-mabi", self.target.as_mabi()]);
            }

            // Default flags (can be overridden by additional_flags)
            command
                .arg("-static")
                .arg("-nostdlib")
                .arg("-nostartfiles")
                .arg("-fno-common")
                .arg("-fvisibility=hidden");

            // Optimization
            if let Some(opt) = &flags.optimization {
                command.arg(format!("-{}", opt));
            } else {
                command.arg("-O2");
            }

            // Additional flags
            for flag in &flags.additional_flags {
                command.arg(flag);
            }
        } else {
            // Use default flags
            command
                .args(["-march", self.target.as_march()])
                .args(["-mabi", self.target.as_mabi()])
                .arg("-static")
                .arg("-nostdlib")
                .arg("-nostartfiles")
                .arg("-fno-common")
                .arg("-fvisibility=hidden")
                .arg("-O2");
        }

        command.arg("-o").arg(&output_elf);

        // Add all source files
        for source in &source_files {
            command.arg(source);
        }

        // Check for linker script
        let linker_script = config.program_path.join("link.ld");
        if linker_script.exists() {
            command.arg("-T").arg(&linker_script);
        }

        println!("Compiling with: {:?}", command);

        let status = command.status().with_context(|| {
            format!(
                "Failed to execute gcc at {}.\n\
                \n\
                Is the GNU RISC-V toolchain installed?\n\
                Run: rialo-build toolchain install gnu-riscv\n\
                \n\
                Note: If you're building Rust programs, you don't need the GNU toolchain.\n\
                Use auto-detection instead: rialo-build --program-path /path/to/program",
                gcc_path.display()
            )
        })?;

        if !status.success() {
            return Err(anyhow::anyhow!(
                "Compilation failed. Check the error output above for details.\n\
                \n\
                Common issues:\n\
                  - Missing or incorrect C source code syntax\n\
                  - Incompatible compiler flags for target architecture\n\
                  - Missing linker script (link.ld)\n\
                \n\
                For Rust programs, use auto-detection instead:\n\
                  rialo-build --program-path /path/to/program"
            ));
        }

        println!("✅ C program compiled successfully");

        // Convert ELF to PolkaVM blob (only for Rialo custom target)
        if self.target.requires_rialo_toolchain() {
            println!("Converting ELF to PolkaVM blob...");

            let elf_bytes = std::fs::read(&output_elf)
                .context("Failed to read ELF file for PolkaVM linking")?;

            let polkavm_bytes =
                link_elf_to_polkavm(&elf_bytes).context("Failed to link ELF to PolkaVM blob")?;

            let artifact_name = program_name.replace('-', "_");
            let polkavm_path = output_dir.join(format!("{artifact_name}.polkavm"));
            std::fs::write(&polkavm_path, &polkavm_bytes).with_context(|| {
                format!("Failed to write PolkaVM blob to {}", polkavm_path.display())
            })?;

            println!("✅ PolkaVM blob created: {}", polkavm_path.display());

            // Return the PolkaVM blob as the primary output
            Ok(BuildResult {
                package_name: program_name.to_string(),
                output_dir: output_dir.clone(),
                program_binary: polkavm_path,
                program_keypair: None,
            })
        } else {
            // For non-Rialo targets, return the ELF as the primary output
            Ok(BuildResult {
                package_name: program_name.to_string(),
                output_dir: output_dir.clone(),
                program_binary: output_elf,
                program_keypair: None,
            })
        }
    }

    /// Build a Rust program
    fn build_rust_program(&self, config: &BuildConfig) -> Result<BuildResult> {
        println!("Building Rust program for RISC-V...");

        // Check which toolchain to use
        let use_rialo_toolchain = self.target.requires_rialo_toolchain();

        if use_rialo_toolchain {
            // Ensure Rialo Rust toolchain is available
            let rust_toolchain = self.rust_toolchain.as_ref().ok_or_else(|| {
                anyhow::anyhow!(
                    "Rialo Rust toolchain not initialized for target {}",
                    self.target.as_target_triple()
                )
            })?;

            // When RIALO_BUILD_CARGO_PATH is set (Bazel rialo_program invocation),
            // the rialo cargo binary is used directly — no rustup registration needed.
            // Skip ensure_installed_atomically() so we don't require either a live
            // internet connection or a rialoman-managed toolchain install during CI.
            let using_direct_cargo = std::env::var("RIALO_BUILD_CARGO_PATH")
                .map(|p| !p.is_empty())
                .unwrap_or(false);

            if !using_direct_cargo {
                rust_toolchain.ensure_installed_atomically()?;
            }

            self.build_rust_with_rialo_toolchain(config)
        } else {
            self.build_rust_with_gnu_toolchain(config)
        }
    }

    /// Build a Rust program using the Rialo custom Rust toolchain
    fn build_rust_with_rialo_toolchain(&self, config: &BuildConfig) -> Result<BuildResult> {
        // When RIALO_BUILD_CARGO_PATH is set (by the Bazel rialo_program rule),
        // invoke the rialo cargo binary directly instead of going through the
        // rustup shim (`cargo +rialo`).  Direct invocation:
        //   - Eliminates the rustup dependency from the build hot path.
        //   - Prevents the workspace rust-toolchain.toml from triggering a
        //     competing toolchain sync when multiple Bazel actions run in parallel.
        //   - Allows the Bazel action to declare the cargo binary as an explicit
        //     file input so its content hash enters the remote-cache key.
        //
        // Fallback to `cargo +rialo` preserves backwards compatibility for
        // manual / rialoman-managed invocations where RIALO_BUILD_CARGO_PATH is
        // not set.
        let direct_cargo = std::env::var("RIALO_BUILD_CARGO_PATH")
            .ok()
            .filter(|p| !p.is_empty());
        let use_direct = direct_cargo.is_some();

        let toolchain_label = if use_direct {
            format!("direct ({})", direct_cargo.as_deref().unwrap_or_default())
        } else {
            "cargo +rialo".to_string()
        };
        println!("Using Rialo custom Rust toolchain ({})", toolchain_label);
        println!("Target: {}", self.target.as_target_triple());

        // Get package name from Cargo.toml
        let package_name = get_package_name(&config.program_path)?;

        // Create output directory
        let output_dir = config.output_dir.join(format!("{package_name}-riscv"));
        std::fs::create_dir_all(&output_dir).with_context(|| {
            format!("Failed to create output directory {}", output_dir.display())
        })?;

        // Convert target_dir to absolute path to avoid issues with relative paths
        // when cargo runs from a different working directory
        let absolute_target_dir = if config.target_dir.is_absolute() {
            config.target_dir.clone()
        } else {
            std::env::current_dir()
                .context("Failed to get current directory")?
                .join(&config.target_dir)
        };

        // Build the cargo command.
        let mut command = if let Some(ref cargo_path) = direct_cargo {
            // Direct invocation: the rialo cargo binary already knows its paired
            // rustc (it's in the same bin/ directory), so no `+rialo` channel
            // selector is needed.
            //
            // IMPORTANT: resolve the cargo path to absolute NOW, before
            // command.current_dir() changes the child's working directory.
            // Bazel passes RIALO_BUILD_CARGO_PATH as an exec-root-relative path
            // (e.g. "external/_main~.../bin/cargo").  After current_dir() the
            // kernel resolves that relative path from the new CWD (program_path),
            // where the binary does not exist, causing ENOENT.
            let abs_cargo = if std::path::Path::new(cargo_path).is_absolute() {
                std::path::PathBuf::from(cargo_path)
            } else {
                std::env::current_dir()
                    .context("Failed to get current working directory")?
                    .join(cargo_path)
            };
            std::process::Command::new(abs_cargo)
        } else {
            // Rustup-shim fallback: tell rustup to use the 'rialo' toolchain.
            let mut cmd = std::process::Command::new("cargo");
            cmd.arg("+rialo");
            cmd
        };
        command.current_dir(&config.program_path);

        let target_triple = self.target.as_target_triple();

        command
            .arg("build")
            .arg("--release")
            .arg("--target")
            .arg(target_triple)
            .arg("--target-dir")
            .arg(&absolute_target_dir);

        // Check if the implementation feature is present in the Cargo.toml
        if has_implementation_feature(&config.program_path)? {
            command
                .arg("--features")
                .arg(rialo_venus_dsl::generate::constants::IMPLEMENTATION_FEATURE);
        }

        sanitize_nested_cargo_env(&mut command);

        // Override rust-toolchain.toml so the rialo cargo doesn't invoke
        // rustup to install host-toolchain components (e.g. clippy-preview)
        // which conflicts with concurrent Bazel steps that already have the
        // component installed.
        command.env("RUSTUP_TOOLCHAIN", "rialo");

        let cargo_display = if use_direct {
            direct_cargo.as_deref().unwrap_or("cargo")
        } else {
            "cargo +rialo"
        };
        println!(
            "Building with: {} build --release --target {}",
            cargo_display, target_triple
        );

        let status = command
            .status()
            .context("Failed to execute cargo +rialo build")?;

        if !status.success() {
            return Err(anyhow::anyhow!("Cargo build failed"));
        }

        // Find the built ELF file
        let target_dir = absolute_target_dir.join(target_triple).join("release");

        // Convert package name hyphens to underscores (Rust convention for binaries)
        let binary_name = package_name.replace('-', "_");

        let source_elf = target_dir.join(&binary_name).with_extension("elf");
        if !source_elf.exists() {
            return Err(anyhow::anyhow!(
                "Built ELF not found at {}. Expected cargo to produce a binary.",
                source_elf.display()
            ));
        }

        println!("✅ Rust program compiled successfully with Rialo toolchain");

        // Convert ELF to PolkaVM blob (only for Rialo custom target)
        if self.target.requires_rialo_toolchain() {
            println!("Converting ELF to PolkaVM blob...");

            let elf_bytes = std::fs::read(&source_elf)
                .context("Failed to read ELF file for PolkaVM linking")?;

            let polkavm_bytes =
                link_elf_to_polkavm(&elf_bytes).context("Failed to link ELF to PolkaVM blob")?;

            let polkavm_path = output_dir.join(format!("{binary_name}.polkavm"));
            std::fs::write(&polkavm_path, &polkavm_bytes).with_context(|| {
                format!("Failed to write PolkaVM blob to {}", polkavm_path.display())
            })?;

            println!("✅ PolkaVM blob created: {}", polkavm_path.display());

            // Return the PolkaVM blob as the primary output
            Ok(BuildResult {
                package_name,
                output_dir: output_dir.clone(),
                program_binary: polkavm_path,
                program_keypair: None,
            })
        } else {
            // For non-Rialo targets, copy the ELF to the output directory
            let output_elf = output_dir.join(format!("{binary_name}.elf"));
            std::fs::copy(&source_elf, &output_elf).with_context(|| {
                format!(
                    "Failed to copy {} to {}",
                    source_elf.display(),
                    output_elf.display()
                )
            })?;

            Ok(BuildResult {
                package_name,
                output_dir: output_dir.clone(),
                program_binary: output_elf,
                program_keypair: None,
            })
        }
    }

    /// Build a Rust program using the GNU RISC-V toolchain (fallback)
    fn build_rust_with_gnu_toolchain(&self, config: &BuildConfig) -> Result<BuildResult> {
        println!("Using GNU RISC-V toolchain with cargo");

        // Get package name from Cargo.toml
        let package_name = get_package_name(&config.program_path)?;

        // Create output directory
        let output_dir = config.output_dir.join(format!("{package_name}-riscv"));
        std::fs::create_dir_all(&output_dir).with_context(|| {
            format!("Failed to create output directory {}", output_dir.display())
        })?;

        // Convert target_dir to absolute path to avoid issues with relative paths
        // when cargo runs from a different working directory
        let absolute_target_dir = if config.target_dir.is_absolute() {
            config.target_dir.clone()
        } else {
            std::env::current_dir()
                .context("Failed to get current directory")?
                .join(&config.target_dir)
        };

        // Get toolchain paths for environment variables
        let bin_path = self.gnu_toolchain.get_bin_path()?;
        let tool_prefix = self.gnu_toolchain.get_tool_prefix();

        // Set up environment variables for cross-compilation
        let mut command = std::process::Command::new("cargo");
        command.current_dir(&config.program_path);

        // Set CC and AR for the target
        let target_triple = self.target.as_target_triple();
        let env_prefix = target_triple.replace('-', "_").to_uppercase();

        command
            .env(
                format!("CC_{}", env_prefix),
                bin_path.join(format!("{}-gcc", tool_prefix)),
            )
            .env(
                format!("AR_{}", env_prefix),
                bin_path.join(format!("{}-ar", tool_prefix)),
            )
            .env("CARGO_BUILD_TARGET", target_triple);

        // Build command
        command
            .arg("build")
            .arg("--release")
            .arg("--target")
            .arg(target_triple)
            .arg("--target-dir")
            .arg(&absolute_target_dir);

        // Add -Z build-std for no_std targets
        command.arg("-Z").arg("build-std=core,alloc");

        println!("Building with cargo: {:?}", command);

        let status = command.status().context("Failed to execute cargo build")?;

        if !status.success() {
            return Err(anyhow::anyhow!("Cargo build failed"));
        }

        // Find the built ELF file
        let target_dir = absolute_target_dir.join(target_triple).join("release");

        // Convert package name hyphens to underscores (Rust convention for binaries)
        let binary_name = package_name.replace('-', "_");

        let source_elf = target_dir.join(&binary_name).with_extension("elf");
        if !source_elf.exists() {
            return Err(anyhow::anyhow!(
                "Built ELF not found at {}. Expected cargo to produce a binary.",
                source_elf.display()
            ));
        }

        println!("✅ Rust program compiled successfully with GNU toolchain");

        // Convert ELF to PolkaVM blob (only for Rialo custom target)
        if self.target.requires_rialo_toolchain() {
            println!("Converting ELF to PolkaVM blob...");

            let elf_bytes = std::fs::read(&source_elf)
                .context("Failed to read ELF file for PolkaVM linking")?;

            let polkavm_bytes =
                link_elf_to_polkavm(&elf_bytes).context("Failed to link ELF to PolkaVM blob")?;

            let polkavm_path = output_dir.join(format!("{binary_name}.polkavm"));
            std::fs::write(&polkavm_path, &polkavm_bytes).with_context(|| {
                format!("Failed to write PolkaVM blob to {}", polkavm_path.display())
            })?;

            println!("✅ PolkaVM blob created: {}", polkavm_path.display());

            // Return the PolkaVM blob as the primary output
            Ok(BuildResult {
                package_name,
                output_dir: output_dir.clone(),
                program_binary: polkavm_path,
                program_keypair: None,
            })
        } else {
            // For non-Rialo targets, copy the ELF to the output directory
            let output_elf = output_dir.join(format!("{binary_name}.elf"));
            std::fs::copy(&source_elf, &output_elf).with_context(|| {
                format!(
                    "Failed to copy {} to {}",
                    source_elf.display(),
                    output_elf.display()
                )
            })?;

            Ok(BuildResult {
                package_name,
                output_dir: output_dir.clone(),
                program_binary: output_elf,
                program_keypair: None,
            })
        }
    }
}

impl ProgramBuilder for RiscvBuilder {
    fn validate(&self) -> Result<()> {
        // Only validate GNU toolchain if not using rialo-custom target
        // (rialo-custom requires rialo-rust toolchain, not GNU)
        if !self.target.requires_rialo_toolchain() {
            self.gnu_toolchain.validate()?;
        }

        // Validate Rialo Rust toolchain if needed for this target
        if let Some(ref rust_toolchain) = self.rust_toolchain {
            if rust_toolchain.is_installed()? {
                rust_toolchain.validate()?;
            } else {
                println!("Note: Rialo Rust toolchain not installed. It will be automatically installed when building Rust programs.");
            }
        }

        Ok(())
    }

    fn build(&self, config: &BuildConfig) -> Result<BuildResult> {
        // Validate program path exists (backwards compatibility)
        crate::validate_program_path(&config.program_path)?;

        // Detect program type
        let program_type = self.detect_program_type(&config.program_path)?;

        match program_type {
            ProgramType::C => self.build_c_program(config),
            ProgramType::Rust => self.build_rust_program(config),
        }
    }
}

/// Program type detected from directory contents
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProgramType {
    /// C program
    C,
    /// Rust program
    Rust,
}

/// Get the package name from Cargo.toml in the specified directory
fn get_package_name(dir: &Path) -> Result<String> {
    let dir = dir
        .canonicalize()
        .with_context(|| format!("Failed to canonicalize directory {}", dir.display()))?;
    let manifest_path = dir.join("Cargo.toml");

    let metadata = cargo_metadata::MetadataCommand::new()
        .manifest_path(&manifest_path)
        .no_deps()
        .exec()
        .with_context(|| format!("Failed to parse Cargo.toml at {}", manifest_path.display()))?;

    Ok(match metadata.workspace_default_packages().first() {
        Some(p) => p.name.clone(),
        None => "<unknown>".into(),
    })
}

/// Check if the implementation feature is present in the Cargo.toml
fn has_implementation_feature(dir: &Path) -> Result<bool> {
    let cargo_toml_path = dir.join("Cargo.toml");
    if !cargo_toml_path.exists() {
        anyhow::bail!("Cargo.toml not found at: {}", cargo_toml_path.display());
    }

    let manifest = cargo_toml::Manifest::from_path(cargo_toml_path)?;
    Ok(manifest
        .features
        .contains_key(rialo_venus_dsl::generate::constants::IMPLEMENTATION_FEATURE))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_riscv_target_conversions() {
        assert_eq!(
            RiscvTarget::Rv64gc.as_target_triple(),
            "riscv64gc-unknown-none-elf"
        );
        assert_eq!(RiscvTarget::Rv64gc.as_march(), "rv64gc");
        assert_eq!(RiscvTarget::Rv64gc.as_mabi(), "lp64d");

        assert_eq!(
            RiscvTarget::Rv32i.as_target_triple(),
            "riscv32i-unknown-none-elf"
        );
        assert_eq!(RiscvTarget::Rv32i.as_march(), "rv32i");
        assert_eq!(RiscvTarget::Rv32i.as_mabi(), "ilp32");
    }

    #[test]
    fn test_default_target() {
        assert_eq!(RiscvTarget::default(), RiscvTarget::RialoCustom);
    }
}