use std::{fs, io::Write, path::Path};
use crate::osconfig::OsConfig;
pub fn compile_with_nasm(code: &String,osconf : OsConfig) -> Result<(), String> {
if osconf == OsConfig::Linux_X86_64 {
let asm_path = Path::new("_.asm");
if asm_path.exists() {
fs::remove_file(asm_path).map_err(|e| e.to_string())?;
}
{
let mut asm_file = fs::File::create(asm_path).map_err(|e| e.to_string())?;
asm_file.write_all(code.as_bytes()).map_err(|e| e.to_string())?;
}
let nasm_status = std::process::Command::new("nasm")
.args(["-f", "elf64", "-o", "_.o", "_.asm"])
.status()
.map_err(|e| e.to_string())?;
if !nasm_status.success() {
return Err("Error running nasm".to_string());
}
let ld_status = std::process::Command::new("ld")
.args(["-o", "out", "_.o"])
.status()
.map_err(|e| e.to_string())?;
if !ld_status.success() {
return Err("Error running ld".to_string());
}
fs::remove_file(asm_path).map_err(|e| e.to_string())?;
fs::remove_file("_.o").map_err(|e| e.to_string())?;
Ok(())
} else if osconf == OsConfig::Linux_X86_32 {
let asm_path = Path::new("_.asm");
if asm_path.exists() {
fs::remove_file(asm_path).map_err(|e| e.to_string())?;
}
{
let mut asm_file = fs::File::create(asm_path).map_err(|e| e.to_string())?;
asm_file.write_all(code.as_bytes()).map_err(|e| e.to_string())?;
}
let nasm_status = std::process::Command::new("nasm")
.args(["-f", "elf32", "-o", "_.o", "_.asm"])
.status()
.map_err(|e| e.to_string())?;
if !nasm_status.success() {
return Err("Error running nasm for 32-bit".to_string());
}
let ld_status = std::process::Command::new("ld")
.args(["-m", "elf_i386", "-o", "out", "_.o"])
.status()
.map_err(|e| e.to_string())?;
if !ld_status.success() {
return Err("Error running ld for 32-bit".to_string());
}
fs::remove_file(asm_path).map_err(|e| e.to_string())?;
fs::remove_file("_.o").map_err(|e| e.to_string())?;
Ok(())
} else {
Err("Unsupported OS configuration".to_string())
}
}