From 0b142b1b860c3eb471dfad83516a4668e3f24fff Mon Sep 17 00:00:00 2001 From: John Ring Date: Mon, 12 Jan 2026 21:42:36 -0500 Subject: [PATCH 1/2] Fixed linking issues on MacOS. Made option to use ld as linker more clear. Better ReadMe --- README.md | 211 ++++++++++++++++++++++++++------------- src/emit_iced.rs | 30 +++++- src/main.rs | 255 +++++++++++++++++++++++++++-------------------- tests/runner.rs | 4 +- 4 files changed, 314 insertions(+), 186 deletions(-) diff --git a/README.md b/README.md index 0409ffb..abf7468 100644 --- a/README.md +++ b/README.md @@ -3,21 +3,19 @@ [![Lint](https://github.com/johnhringiv/NCC-Rust/actions/workflows/lint.yml/badge.svg)](https://github.com/johnhringiv/NCC-Rust/actions/workflows/lint.yml) [![codecov](https://codecov.io/gh/johnhringiv/NCC-Rust/graph/badge.svg?token=GJJCD2Z8Y6)](https://codecov.io/gh/johnhringiv/NCC-Rust) -A simple C compiler written in Rust, following Sandler's "Writing a C Compiler". -Some design decisions are informed by the book but the implementation is my own. +A (**N**ot **C**ompletely) **C** compiler written in Rust, inspired by Sandler's "Writing a C Compiler". -So far chapter 10, including extra credit is implemented, which includes a lexer, parser, semantic analysis, and code -generator for C code with functions, local and file-scope variables, storage-class specifiers, compound statements, -loops, and switch statements. -This compiler is a fully standalone executable; it does not rely on any external programs for assembling or linking (on -Linux). -All provided tests pass. +NCC is a full pipeline compiler, going from lexing all the way down to x86-64 machine code emission and linking. +Machine code is encoded directly using [iced-x86](https://github.com/icedland/iced) and emitted to ELF/Mach-O +object files via the [object](https://github.com/gimli-rs/object) crate—no external assembler required. +A substantial subset of C is supported, including functions, static variables, all control flow statements, and +bitwise operations. Additionally, NCC supports developer-friendly warnings and pretty-printing of each compiler pass. +Runs on Linux and macOS (Intel). ## Example -NCC supports a substantial subset of C, including functions, static variables, all control flow statements, and bitwise -operations. Here's a [Collatz Conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture) example showcasing some of -these capabilities: +This [Collatz Conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture) program compiles and runs with NCC, +demonstrating static variables, functions, loops, bitwise operations, and conditionals: ```c // Collatz Conjecture Explorer @@ -63,11 +61,122 @@ int main(void) { } ``` -```sh -$ ncc collatz.c --run -97 +### Generated Assembly + +C code alongside the x86-64 assembly NCC generates (`ncc -S`). Labels are pretty-printed using +the original function and variable names from the source. Redundant moves will be eliminated +once copy propagation is implemented: + + + + + + + + + + +
C CodeGenerated Assembly
+ +```c +static int counter = 0; + +int next(void) { + counter++; + return counter; +} + +int main(void) { + return next() + next(); +} ``` + + +```asm +next: + push %rbp + mov %rsp,%rbp + sub $16,%rsp + mov counter(%rip),%r10d + mov %r10d,-4(%rbp) + mov counter(%rip),%r10d + mov %r10d,-8(%rbp) + addl $1,-8(%rbp) + mov -8(%rbp),%r10d + mov %r10d,counter(%rip) + mov counter(%rip),%eax + mov %rbp,%rsp + pop %rbp + ret + +main: + push %rbp + mov %rsp,%rbp + sub $16,%rsp + call next + mov %eax,-4(%rbp) + mov -4(%rbp),%r10d + mov %r10d,-8(%rbp) + call next + mov %eax,-12(%rbp) + mov -8(%rbp),%r10d + mov %r10d,-16(%rbp) + mov -12(%rbp),%r10d + add %r10d,-16(%rbp) + mov -16(%rbp),%eax + mov %rbp,%rsp + pop %rbp + ret + +.bss +counter: + .zero 4 +``` + +
+ +## Usage + +``` +ncc [OPTIONS] ... +``` + +### Arguments + +`...` Input files (required). Supports multiple C and assembly files. + +### Options + +| Option | Description | +|---------------------------|----------------------------------------------------------| +| `--lex` | Run lexer | +| `--parse` | Run lexer and parser | +| `--validate` | Run lexer, parser, and validator | +| `--codegen` | Run lexer, parser, and code generator | +| `--tacky` | Emit TACKY IR | +| `-S` | Emit assembly | +| `--run` | Run compiled program and print result | +| `-c` | Emit object file only (no linking) | +| `--external-linker` | Use system linker (`ld`) instead of built-in libwild | +| `--static` | Link statically (no runtime dependencies) - Linux only | +| `--no-iced` | Use text-based asm building instead of iced (deprecated) | +| `-o`, `--output ` | Override output file location | +| `-h`, `--help` | Print help | +| `-V`, `--version` | Print version | + +Note: `--lex`, `--parse`, `--validate`, `--codegen`, `--tacky`, `-S`, `--run`, `-c` are mutually exclusive options. + +### Exit Codes + +| Exit Code | Description | +|-----------|-----------------------------------------------| +| 0 | Success | +| 1 | General error (file I/O, compilation failure) | +| 10 | Lexer error (tokenization failed) | +| 20 | Parser error (syntax error) | +| 30 | Validation error (semantic error) | + ## Language Grammar The compiler currently implements a subset of C with the following grammar: @@ -176,7 +285,22 @@ These features help catch common bugs at compile time while providing predictabl ## Requirements - Rust (latest stable) -- GCC (Optional) for linking instead of `libwild` +- A C toolchain to provide and locate system libraries (CRT & libc) - `cc` is not used for compilation + +### Linux + +```bash +sudo apt install build-essential + +# For Makefile (optional - linting/formatting) +sudo apt install pkg-config libssl-dev make +``` + +### macOS + +```bash +xcode-select --install +``` ## Setup @@ -189,15 +313,10 @@ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Initialize submodules git submodule update --init - -# Install build essentials (Linux) -sudo apt install build-essential ``` ## Building -Clone the repository and build with Cargo: - ```sh cargo build --release ``` @@ -208,56 +327,6 @@ cargo build --release cargo test ``` -## Usage - -Usage: ncc [OPTIONS] `...` - -### Arguments - -`...` Input files (required). Supports multiple C and assembly files. - -### Options - -| Option | Description | -|---------------------------|----------------------------------------------------------| -| `--lex` | Run lexer | -| `--parse` | Run lexer and parser | -| `--validate` | Run lexer, parser, and validator | -| `--codegen` | Run lexer, parser, and code generator | -| `--tacky` | Emit TACKY IR | -| `-S` | Emit assembly | -| `--run` | Run compiled program and print result | -| `-c` | Emit object file only (no linking) | -| `--gcc` | Use GCC for linking (instead of wild) | -| `--static` | Link statically (no runtime dependencies) | -| `--no-iced` | Use text-based asm building instead of iced (deprecated) | -| `-o`, `--output ` | Override output file location | -| `-h`, `--help` | Print help | -| `-V`, `--version` | Print version | - -Note: `--lex`, `--parse`, `--validate`, `--codegen`, `--tacky`, `-S`, `--run`, `-c` are mutually exclusive options. - -### Exit Codes - -NCC uses specific exit codes to indicate different types of failures: - -| Exit Code | Description | -|-----------|-----------------------------------------------| -| 0 | Success | -| 1 | General error (file I/O, compilation failure) | -| 10 | Lexer error (tokenization failed) | -| 20 | Parser error (syntax error) | -| 30 | Validation error (semantic error) | - ## Contributing -As a reminder to myself. -Use the Makefile to check code quality `make quality` and fix formatting `make fix`. - -### Requirements for Makefile - -```shell -sudo apt-get install pkg-config libssl-dev make -``` - - +Use the Makefile to check code quality (`make quality`) and fix formatting (`make fix`). diff --git a/src/emit_iced.rs b/src/emit_iced.rs index 2a2a50f..7d36083 100644 --- a/src/emit_iced.rs +++ b/src/emit_iced.rs @@ -244,9 +244,28 @@ fn emit_object_with_labels( // Clone instruction offsets before moving the inner let instruction_offsets = result.inner.new_instruction_offsets.clone(); + let constant_offsets = result.inner.constant_offsets.clone(); // Now move the code buffer - let code = result.inner.code_buffer; + let mut code = result.inner.code_buffer; + + // On Mach-O, patch displacement values for data references. + // The Mach-O linker uses implicit addends: final = existing + (symbol - P - 4) + // We want: final = symbol - (P + bytes_remaining) + // So: existing = -(bytes_remaining - 4) + // For most instructions where bytes_remaining = 4 (displacement only), existing should be 0. + if cfg!(target_os = "macos") { + for (ins_idx, _var_name) in &data_relocs { + let ins_offset = instruction_offsets[*ins_idx] as usize; + let const_off = &constant_offsets[*ins_idx]; + let disp_offset = ins_offset + const_off.displacement_offset() as usize; + let bytes_remaining = const_off.displacement_size() + const_off.immediate_size(); + // Mach-O linker adds 4 to pcrel addend, so we need existing = -(bytes_remaining - 4) + let implicit_addend = -((bytes_remaining as i32) - 4); + let bytes = implicit_addend.to_le_bytes(); + code[disp_offset..disp_offset + 4].copy_from_slice(&bytes); + } + } let mut obj = if cfg!(target_os = "linux") { let mut obj = Object::new(BinaryFormat::Elf, Architecture::X86_64, Endianness::Little); @@ -787,10 +806,15 @@ fn emit_instruction( // Internal function call a.call(lbl)?; } else { - // External function call - emit call to 0 and track for relocation + // External function call - track for relocation let ins_count = a.instructions().len(); external_calls.push((ins_count, name.0.clone())); - a.call(0)?; + // The Mach-O linker adds the existing displacement to (symbol - RIP). + // We want the final result to be (symbol - RIP), so we need displacement = 0. + // For ELF, the explicit addend in the relocation handles this, and the + // existing displacement is ignored. + // E8 = CALL rel32 opcode, 00 00 00 00 = 0 displacement + a.db(&[0xE8, 0x00, 0x00, 0x00, 0x00])?; } } } diff --git a/src/main.rs b/src/main.rs index bc675d8..9b31b94 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,10 +11,12 @@ use crate::pretty::ItfDisplay; use clap::{ArgGroup, Parser}; use colored::{ColoredString, Colorize}; use iced_x86::{Formatter, FormatterOutput, FormatterTextKind}; -use libwild::{Args as WildArgs, Linker}; use std::fs; use std::path::Path; +#[cfg(target_os = "linux")] +use libwild::{Args as WildArgs, Linker}; + #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] #[command(group( @@ -55,11 +57,11 @@ struct Args { #[arg(short = 'c')] c: bool, - /// Use GCC for linking + /// Use external system linker (ld) instead of built-in libwild. Required on macOS. #[arg(long)] - gcc: bool, + external_linker: bool, - /// Link statically (no runtime dependencies) + /// Link statically (no runtime dependencies) - Linux only #[arg(long = "static")] static_link: bool, @@ -87,8 +89,6 @@ impl MyFormatterOutput { impl FormatterOutput for MyFormatterOutput { fn write(&mut self, text: &str, kind: FormatterTextKind) { - // This allocates a string. If that's a problem, just call print!() here - // instead of storing the result in a vector. self.vec.push((String::from(text), kind)); } } @@ -104,14 +104,144 @@ fn get_color(s: &str, kind: FormatterTextKind) -> ColoredString { } } -fn main() { - let mut args = Args::parse(); +/// Ask the C compiler for a file path (e.g., crt1.o, crti.o) +#[cfg(target_os = "linux")] +fn get_cc_file(name: &str) -> Option { + std::process::Command::new("cc") + .arg(format!("-print-file-name={}", name)) + .output() + .ok() + .and_then(|o| String::from_utf8(o.stdout).ok()) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty() && s != name) // cc returns just the name if not found +} + +/// Get library search paths from the C compiler +#[cfg(target_os = "linux")] +fn get_cc_library_paths() -> Vec { + std::process::Command::new("cc") + .args(["-print-search-dirs"]) + .output() + .ok() + .and_then(|o| String::from_utf8(o.stdout).ok()) + .and_then(|s| { + s.lines() + .find(|line| line.starts_with("libraries:")) + .map(|line| { + line.trim_start_matches("libraries:") + .trim_start_matches(" =") + .split(':') + .filter(|p| !p.is_empty() && std::path::Path::new(p).exists()) + .map(String::from) + .collect() + }) + }) + .unwrap_or_default() +} + +/// Build linker arguments for Linux (shared between ld and libwild) +#[cfg(target_os = "linux")] +fn build_linux_linker_args(obj_files: &[String], out_file: &str, static_link: bool) -> Vec { + let mut args = vec!["-o".to_string(), out_file.to_string()]; + + if static_link { + args.push("-static".to_string()); + } else if let Some(ld) = get_cc_file("ld-linux-x86-64.so.2") { + args.push(format!("--dynamic-linker={}", ld)); + } + + // Add library search paths + for path in get_cc_library_paths() { + args.push(format!("-L{}", path)); + } + + if let Some(crt1) = get_cc_file("crt1.o") { + args.push(crt1); + } + if let Some(crti) = get_cc_file("crti.o") { + args.push(crti); + } + + args.extend(obj_files.iter().cloned()); + args.push("-lc".to_string()); - if cfg!(target_os = "macos") & !args.gcc { - println!("Using GCC as libwild does not support MacOS"); - args.gcc = true; + if static_link { + args.push("-lgcc".to_string()); + args.push("-lgcc_eh".to_string()); } + if let Some(crtn) = get_cc_file("crtn.o") { + args.push(crtn); + } + + args +} + +/// Link object files using the system linker (ld) +#[allow(unused_variables)] +fn link_with_ld(obj_files: &[String], out_file: &str, static_link: bool) { + let mut cmd = std::process::Command::new("ld"); + + #[cfg(target_os = "macos")] + { + cmd.args(["-arch", "x86_64"]); + + let macos_version = std::process::Command::new("sw_vers") + .args(["-productVersion"]) + .output() + .ok() + .and_then(|o| String::from_utf8(o.stdout).ok()) + .map(|v| v.trim().to_string()) + .unwrap_or_else(|| "11.0".to_string()); + cmd.args(["-platform_version", "macos", &macos_version, &macos_version]); + + if let Ok(output) = std::process::Command::new("xcrun").args(["--show-sdk-path"]).output() { + let sdk_path = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if !sdk_path.is_empty() { + cmd.arg("-syslibroot").arg(&sdk_path); + } + } + + cmd.arg("-lSystem"); + for obj in obj_files { + cmd.arg(obj); + } + cmd.arg("-o").arg(out_file); + } + + #[cfg(target_os = "linux")] + { + for arg in build_linux_linker_args(obj_files, out_file, static_link) { + cmd.arg(arg); + } + } + + let status = cmd.status().expect("Failed to execute ld"); + if !status.success() { + eprintln!("Linking failed with status: {status}"); + std::process::exit(1); + } +} + +/// Link object files using libwild (Linux only, in-process linker) +#[cfg(target_os = "linux")] +fn link_with_libwild(obj_files: &[String], out_file: &str, static_link: bool) { + let args_vec = build_linux_linker_args(obj_files, out_file, static_link); + let args_refs: Vec<&str> = args_vec.iter().map(|s| s.as_str()).collect(); + + let linker = Linker::new(); + let parsed = WildArgs::parse(|| args_refs.iter()).expect("parse args"); + let _ = libwild::setup_tracing(&parsed); + let activated = parsed.activate_thread_pool().expect("activate args"); + linker.run(&activated).expect("link failed"); +} + +fn main() { + let args = Args::parse(); + + // On macOS, always use external linker since libwild doesn't support it + let use_external_linker = args.external_linker || cfg!(target_os = "macos"); + // Separate C files from assembly files let (c_files, asm_files): (Vec<_>, Vec<_>) = args.filenames.iter().partition(|f| f.ends_with(".c")); @@ -334,106 +464,11 @@ fn main() { } // Link all object files together - if args.gcc { - let mut cmd = std::process::Command::new("gcc"); - for obj in &obj_files { - cmd.arg(obj); - } - cmd.arg("-o").arg(&out_file); - - let status = cmd.status().expect("Failed to execute gcc"); - - if !status.success() { - eprintln!("Linking failed with status: {status}"); - std::process::exit(1); - } + if use_external_linker { + link_with_ld(&obj_files, &out_file, args.static_link); } else { - let linker = Linker::new(); - - // Library search paths (architecture-specific) - let lib_dirs = [ - "/lib/x86_64-linux-gnu", // Ubuntu/Debian - "/usr/lib/x86_64-linux-gnu", // Alternative Ubuntu/Debian - "/lib64", // RHEL/Fedora - "/usr/lib64", // RHEL/Fedora alt - "/usr/lib", // Generic - ]; - - // Find the library directory that has CRT files - let lib_dir = lib_dirs - .iter() - .find(|d| std::path::Path::new(&format!("{}/crt1.o", d)).exists()); - - let mut args_vec: Vec = vec!["-o".to_string(), out_file.clone()]; - - // Static linking: no dynamic linker needed, links against libc.a - if args.static_link { - args_vec.push("-static".to_string()); - } else { - // Find dynamic linker for dynamic linking - let ld_paths = [ - "/lib64/ld-linux-x86-64.so.2", - "/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2", - ]; - if let Some(ld) = ld_paths.iter().find(|p| std::path::Path::new(p).exists()) { - args_vec.push(format!("--dynamic-linker={}", ld)); - } - } - - // Add library search paths - for dir in &lib_dirs { - if std::path::Path::new(dir).exists() { - args_vec.push(format!("-L{}", dir)); - } - } - - // For static linking, we need libgcc for compiler support routines - if args.static_link { - // Find gcc library directory - let gcc_dirs = [ - "/usr/lib/gcc/x86_64-linux-gnu/13", - "/usr/lib/gcc/x86_64-linux-gnu/12", - "/usr/lib/gcc/x86_64-linux-gnu/11", - "/usr/lib/gcc/x86_64-linux-gnu/10", - "/usr/lib/gcc/x86_64-linux-gnu/9", - "/usr/lib64/gcc/x86_64-linux-gnu/13", - ]; - if let Some(gcc_dir) = gcc_dirs.iter().find(|d| std::path::Path::new(d).exists()) { - args_vec.push(format!("-L{}", gcc_dir)); - } - } - - // Add CRT startup files and object files in correct order: - // crt1.o crti.o -lc [-lgcc -lgcc_eh] crtn.o - if let Some(dir) = lib_dir { - args_vec.push(format!("{}/crt1.o", dir)); - args_vec.push(format!("{}/crti.o", dir)); - } - - // User object files - for obj in &obj_files { - args_vec.push(obj.clone()); - } - - // Link with libc - args_vec.push("-lc".to_string()); - - // Static linking needs libgcc for compiler support - if args.static_link { - args_vec.push("-lgcc".to_string()); - args_vec.push("-lgcc_eh".to_string()); - } - - // CRT epilogue - if let Some(dir) = lib_dir { - args_vec.push(format!("{}/crtn.o", dir)); - } - - let args_refs: Vec<&str> = args_vec.iter().map(|s| s.as_str()).collect(); - let parsed = WildArgs::parse(|| args_refs.iter()).expect("parse args"); - let _ = libwild::setup_tracing(&parsed); - let activated = parsed.activate_thread_pool().expect("activate args"); - linker.run(&activated).expect("link failed"); + #[cfg(target_os = "linux")] + link_with_libwild(&obj_files, &out_file, args.static_link); } // Clean up object files diff --git a/tests/runner.rs b/tests/runner.rs index 5e5c637..3bbc5a5 100644 --- a/tests/runner.rs +++ b/tests/runner.rs @@ -538,8 +538,8 @@ fn run_cases(cases: Vec) { &mut total_passed, &mut total_failed, &mut failed_tests, - &["--gcc".to_string()], - "gcc-link", + &["--external-linker".to_string()], + "external-linker", ); println!("\n=== C Programs Test Results ==="); From 1ee5fca775805af34c0ac732509f64418a6f0487 Mon Sep 17 00:00:00 2001 From: John Ring Date: Mon, 12 Jan 2026 21:50:22 -0500 Subject: [PATCH 2/2] linting --- src/emit_iced.rs | 2 +- src/main.rs | 18 ++++++++---------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/emit_iced.rs b/src/emit_iced.rs index 7d36083..1a79c9d 100644 --- a/src/emit_iced.rs +++ b/src/emit_iced.rs @@ -258,7 +258,7 @@ fn emit_object_with_labels( for (ins_idx, _var_name) in &data_relocs { let ins_offset = instruction_offsets[*ins_idx] as usize; let const_off = &constant_offsets[*ins_idx]; - let disp_offset = ins_offset + const_off.displacement_offset() as usize; + let disp_offset = ins_offset + const_off.displacement_offset(); let bytes_remaining = const_off.displacement_size() + const_off.immediate_size(); // Mach-O linker adds 4 to pcrel addend, so we need existing = -(bytes_remaining - 4) let implicit_addend = -((bytes_remaining as i32) - 4); diff --git a/src/main.rs b/src/main.rs index 9b31b94..be36e93 100644 --- a/src/main.rs +++ b/src/main.rs @@ -125,16 +125,14 @@ fn get_cc_library_paths() -> Vec { .ok() .and_then(|o| String::from_utf8(o.stdout).ok()) .and_then(|s| { - s.lines() - .find(|line| line.starts_with("libraries:")) - .map(|line| { - line.trim_start_matches("libraries:") - .trim_start_matches(" =") - .split(':') - .filter(|p| !p.is_empty() && std::path::Path::new(p).exists()) - .map(String::from) - .collect() - }) + s.lines().find(|line| line.starts_with("libraries:")).map(|line| { + line.trim_start_matches("libraries:") + .trim_start_matches(" =") + .split(':') + .filter(|p| !p.is_empty() && std::path::Path::new(p).exists()) + .map(String::from) + .collect() + }) }) .unwrap_or_default() }