Chapter 4 · Levels 3-4

⚙️ Compiler & Embedded

Understanding Rust Internals and Bare Metal Programming

Part 1: Rust Compiler Internals

Compilation Pipeline

Source Code (.rs)
      ↓
Lexer → Tokens
      ↓
Parser → AST (Abstract Syntax Tree)
      ↓
HIR (High-level IR)
      ↓
Type Checking & Borrow Checking
      ↓
MIR (Mid-level IR)
      ↓
Optimization
      ↓
LLVM IR
      ↓
Machine Code
                

Abstract Syntax Tree (AST)

📝 Example: Exploring AST with syn
use syn::{parse_str, File};

fn main() {
    let code = r#"
        fn add(a: i32, b: i32) -> i32 {
            a + b
        }
    "#;

    let ast: File = parse_str(code).unwrap();

    // Inspect the AST
    println!("{:#?}", ast);
}

// Output shows the structure:
// File {
//     items: [
//         Item::Fn {
//             sig: Signature {
//                 ident: "add",
//                 inputs: [a: i32, b: i32],
//                 output: i32,
//             },
//             block: ...
//         }
//     ]
// }

MIR (Mid-level Intermediate Representation)

📝 Example: Viewing MIR
// To see MIR output:
// rustc +nightly -Z unpretty=mir myfile.rs

fn factorial(n: u32) -> u32 {
    if n == 0 {
        1
    } else {
        n * factorial(n - 1)
    }
}

// MIR representation (simplified):
// fn factorial(_1: u32) -> u32 {
//     let mut _0: u32;
//     let mut _2: bool;
//     let mut _3: u32;
//     let mut _4: u32;
//
//     bb0: {
//         _2 = Eq(_1, const 0_u32);
//         switchInt(_2) -> [false: bb2, otherwise: bb1];
//     }
//
//     bb1: {
//         _0 = const 1_u32;
//         return;
//     }
//
//     bb2: {
//         _4 = Sub(_1, const 1_u32);
//         _3 = factorial(_4);
//         _0 = Mul(_1, _3);
//         return;
//     }
// }

Custom Compiler Plugins

📝 Example: Custom Lint
// In a separate crate with proc-macro = true
#![feature(rustc_private)]

extern crate rustc_driver;
extern crate rustc_interface;
extern crate rustc_lint;
extern crate rustc_session;

use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_session::declare_lint;

declare_lint! {
    pub FORBIDDEN_FUNCTION,
    Warn,
    "warns when using forbidden functions"
}

struct ForbiddenFunctionLint;

impl LateLintPass<'_> for ForbiddenFunctionLint {
    fn check_expr(&mut self, cx: &LateContext<'_>, expr: &rustc_hir::Expr) {
        // Check for forbidden function calls
        // Emit warnings if found
    }
}

Part 2: Embedded Rust (no_std)

Understanding no_std

ℹ️ What is no_std? The #![no_std] attribute tells the compiler not to link the standard library. This is essential for embedded systems and OS kernels where there's no operating system to provide standard library functionality.
📝 Example: Basic no_std Program
#![no_std]
#![no_main]

use core::panic::PanicInfo;

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

#[no_mangle]
pub extern "C" fn _start() -> ! {
    // Entry point for bare metal
    loop {}
}

Embedded Development for ARM Cortex-M

📝 Example: STM32 Blinky (Cargo.toml)
[package]
name = "stm32-blinky"
version = "0.1.0"
edition = "2021"

[dependencies]
cortex-m = "0.7"
cortex-m-rt = "0.7"
panic-halt = "0.2"
stm32f4xx-hal = { version = "0.16", features = ["stm32f411"] }

[profile.release]
opt-level = "z"
lto = true
codegen-units = 1
📝 Example: STM32 Blinky Code
#![no_std]
#![no_main]

use panic_halt as _;
use cortex_m_rt::entry;
use stm32f4xx_hal::{pac, prelude::*};

#[entry]
fn main() -> ! {
    // Get device peripherals
    let dp = pac::Peripherals::take().unwrap();

    // Configure clock
    let rcc = dp.RCC.constrain();
    let clocks = rcc.cfgr.sysclk(84.MHz()).freeze();

    // Get GPIO port C
    let gpioc = dp.GPIOC.split();

    // Configure PC13 as output (LED on BluePill)
    let mut led = gpioc.pc13.into_push_pull_output();

    // Blink LED
    loop {
        led.set_high();
        cortex_m::asm::delay(8_000_000);

        led.set_low();
        cortex_m::asm::delay(8_000_000);
    }
}

Memory Layout and Linker Scripts

📝 Example: Linker Script (memory.x)
/* STM32F411CEU6 */
MEMORY
{
  FLASH : ORIGIN = 0x08000000, LENGTH = 512K
  RAM   : ORIGIN = 0x20000000, LENGTH = 128K
}

/* Stack grows down from end of RAM */
_stack_start = ORIGIN(RAM) + LENGTH(RAM);

SECTIONS
{
  .vector_table ORIGIN(FLASH) : {
    LONG(_stack_start);
    KEEP(*(.vector_table.reset_vector));
  } > FLASH

  .text : {
    *(.text .text.*);
  } > FLASH

  .rodata : {
    *(.rodata .rodata.*);
  } > FLASH

  .data : {
    *(.data .data.*);
  } > RAM AT > FLASH

  .bss : {
    *(.bss .bss.*);
  } > RAM
}

Interrupt Handling

📝 Example: Interrupt Handler
#![no_std]
#![no_main]

use cortex_m_rt::{entry, exception};
use panic_halt as _;

#[entry]
fn main() -> ! {
    // Setup code
    loop {
        // Main loop
    }
}

#[exception]
fn HardFault(ef: &cortex_m_rt::ExceptionFrame) -> ! {
    // Handle hard fault
    panic!("HardFault: {:#?}", ef);
}

#[exception]
fn DefaultHandler(irqn: i16) {
    // Handle other interrupts
    panic!("Unhandled interrupt: {}", irqn);
}

RISC-V Embedded

📝 Example: RISC-V Bare Metal
#![no_std]
#![no_main]

use riscv_rt::entry;
use panic_halt as _;

// UART base address for SiFive FE310
const UART0_BASE: usize = 0x1001_3000;

fn uart_putc(c: u8) {
    unsafe {
        let txdata = (UART0_BASE + 0x00) as *mut u32;
        while (*txdata & 0x8000_0000) != 0 {}
        *txdata = c as u32;
    }
}

fn uart_puts(s: &str) {
    for byte in s.bytes() {
        uart_putc(byte);
    }
}

#[entry]
fn main() -> ! {
    uart_puts("Hello from RISC-V!\r\n");

    loop {
        uart_puts("Tick\r\n");

        // Delay
        for _ in 0..1_000_000 {
            unsafe { riscv::asm::nop(); }
        }
    }
}

Advanced Embedded Patterns

DMA (Direct Memory Access)

📝 Example: DMA Transfer
use stm32f4xx_hal::{dma, pac};

fn setup_dma_transfer() {
    let dp = pac::Peripherals::take().unwrap();

    // Source buffer
    let src_buffer: [u32; 256] = [0; 256];

    // Destination buffer
    let mut dst_buffer: [u32; 256] = [0; 256];

    // Configure DMA stream
    let dma2 = dp.DMA2;
    let stream = dma::StreamsTuple::new(dma2).0;

    // Setup transfer
    let transfer = dma::Transfer::init(
        stream,
        unsafe { &src_buffer },
        unsafe { &mut dst_buffer },
        dma::config::DmaConfig::default()
            .memory_increment(true)
            .peripheral_increment(true),
    );

    // Start transfer
    transfer.start(|_| {});

    // Wait for completion
    while !transfer.get_transfer_complete_flag() {}
}

Power Management

📝 Example: Low Power Mode
use cortex_m::asm;
use stm32f4xx_hal::pac;

fn enter_sleep_mode() {
    let dp = pac::Peripherals::take().unwrap();
    let mut scb = cortex_m::peripheral::SCB::ptr();

    unsafe {
        // Configure sleep mode
        (*scb).set_sleepdeep();

        // Wait for interrupt
        asm::wfi();
    }
}

fn enter_stop_mode() {
    let dp = pac::Peripherals::take().unwrap();

    // Disable systick
    cortex_m::peripheral::SYST::ptr();

    // Enter STOP mode
    dp.PWR.cr.modify(|_, w| w.lpds().set_bit());
    dp.PWR.cr.modify(|_, w| w.pdds().clear_bit());

    unsafe {
        asm::wfi();
    }
}

Real-Time Operating Systems (RTOS)

📝 Example: RTIC Framework
#![no_std]
#![no_main]

use panic_halt as _;
use rtic::app;
use stm32f4xx_hal::{pac, prelude::*};

#[app(device = stm32f4xx_hal::pac, peripherals = true)]
mod app {
    use super::*;

    #[shared]
    struct Shared {
        counter: u32,
    }

    #[local]
    struct Local {
        led: pac::GPIOC,
    }

    #[init]
    fn init(ctx: init::Context) -> (Shared, Local, init::Monotonics) {
        let gpioc = ctx.device.GPIOC;

        (
            Shared { counter: 0 },
            Local { led: gpioc },
            init::Monotonics(),
        )
    }

    #[task(shared = [counter])]
    fn task1(mut ctx: task1::Context) {
        ctx.shared.counter.lock(|c| *c += 1);
    }

    #[task(shared = [counter], local = [led])]
    fn task2(mut ctx: task2::Context) {
        ctx.shared.counter.lock(|c| {
            if *c % 2 == 0 {
                // Toggle LED
            }
        });
    }
}

Best Practices

🔑 Embedded Rust Best Practices

  1. Minimize Binary Size: Use opt-level = "z" and LTO
  2. Avoid Allocations: Use stack-allocated data structures
  3. Handle Panics: Implement appropriate panic handlers
  4. Test on Hardware: Simulators don't catch everything
  5. Use Type Safety: Leverage Rust's type system for hardware safety
  6. Document Memory Maps: Keep clear documentation of hardware layout

Summary

✅ You've learned:

  • Rust compiler internals: AST, HIR, MIR
  • How to work without the standard library (no_std)
  • Embedded development for ARM Cortex-M and RISC-V
  • Memory layout and linker scripts
  • Interrupt handling and DMA
  • Power management and RTOS integration

Understanding compiler internals helps you write better Rust code, while embedded programming skills open up the world of IoT, robotics, and systems programming. These skills are fundamental for becoming a true Rust master.

Korea Standardization Infrastructure Mapping

Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.

Korea Digital Transformation Detailed Mapping

Korea operates digital transformation through a comprehensive governance system. Digital Government: Digital Platform Government Committee (established September 2022, under the President)·Ministry of the Interior and Safety Digital Government Bureau·e-Government Support Center·Gov.kr·National Citizen Service·KDIS (Korea Digital Information Society)·NIA (National Information Society Agency)·MOIS (Ministry of the Interior and Safety). K-DNS Infrastructure: Korea Internet & Security Agency (KISA) Korea Internet Center·KISA DNS Root Server·KRNIC (Korea Network Information Center)·BGP Korea·National Cyber Security Center (NCSC)·KCC (Korea Communications Commission)·MSIT (Ministry of Science and ICT)·NIA·NIPA. Korean Cloud Infrastructure: KT Cloud·NAVER Cloud (NCloud)·Samsung SDS Cloud·LG U+ Cloud·NHN Cloud·Kakao Enterprise Cloud·SK Telecom Cloud·KISA Cloud Security Assurance Program (CSAP)·KCMVP-validated cloud·ISMS-P (Information Security & Personal Information Management System). Korean Security Certifications: KISA ISMS-P certification·KCMVP (Korean Cryptographic Module Validation Program)·NIS (National Intelligence Service) "National Cryptographic Technology Operation Standards"·NCSC "National Cyber Security Strategy 2024-2028"·CC (Common Criteria) Korean evaluation bodies·EAL4·EAL5·KS X ISO/IEC 15408·19790·24759 Korean Profile. Korean Data Standards: NIA AI Hub·National Data Standardization Committee·Statistics Korea (KOSTAT)·MyData 4 Designated Combination Specialists (Samsung SDS, KICI, KOSTAT, KFTC)·National Institute of Korean Language·National Law Information Center·National Spatial Information Platform·National Spatial Data Center·Korean Spatial Information Standards. Finance and Fintech Standards: FSC (Financial Services Commission)·FSS (Financial Supervisory Service)·FIU (Financial Intelligence Unit)·BOK (Bank of Korea)·FSEC (Financial Security Institute)·KFTC (Korea Financial Telecommunications)·KSD (Korea Securities Depository)·KRX (Korea Exchange) 8-agency cooperation. 5G/6G Communications Infrastructure: 5G subscribers 35 million (2024)·5G base stations 350,000·6G commercialization target 2028·5G dedicated networks 16 operators·6G Acceleration Council (MSIT, 2024). K-Content: KOCCA (Korea Creative Content Agency)·MCST (Ministry of Culture, Sports and Tourism)·KCA (Korea Communications Agency)·Korea Culture Information Service Agency·Korean Film Archive·Korea Publishing Industry Promotion Agency. Data 3 Acts (Personal Information Protection Act·Credit Information Act·Telecommunications Network Act, 2020 enforcement)·Data Industry Act (2021)·Public Data Act (2013)·AI Framework Act (2026)·Digital Platform Government Framework Act (2024 proposed) — Korea digital transformation core legislation.

Korea Industrial, Research, Education Infrastructure Mapping

Korea operates its industrial ecosystem and standardization system through the following core infrastructure. Korea Top 5 Groups: Samsung, Hyundai Motor, LG, SK, Lotte. Each group operates standardization committees and ISO/IEC TC Korean secretariats. Samsung Electronics (semiconductors, displays, home appliances, telecom)·Hyundai Motor (automobiles, mobility)·LG Electronics (home appliances, displays, OLED)·SK hynix (memory)·LG Energy Solution·Samsung SDI (batteries)·POSCO Future M (materials)·Hyundai Mobis (parts). Korean IT Big Tech: NAVER (search, cloud, AI HyperCLOVA)·Kakao (messenger, payment, mobility, banking)·Coupang (e-commerce, logistics)·Karrot Market·Toss·Woowa Brothers. Korea Telcos: SK Telecom·KT·LG U+. 5G·5G dedicated networks·B2B cloud·AI businesses operating. Korea Top 7 Research Universities: Seoul National University·KAIST·POSTECH·Yonsei University·Korea University·UNIST·DGIST·GIST. All serve as standardization R&D bases and ISO/IEC/IEEE Korean chairs. Korea Government-affiliated National Research Institutes (26): KIST, KAERI, KIMM, KIER, KFRI, KRICT, KRIBB, KARI, KASI, KIGAM, KICT, KISTI, KETI, ETRI, NIMS, KIMS, KISDI, KOTRA, STEPI, KOEN, KICCE, KIET, KIPF, KIHASA, KICJ, KLRI. Korea Industrial Complexes / Tech Valleys: Pangyo Techno Valley·Dongtan·Gwanggyo·Songdo IBD·Yeouido·Gangnam·Sihwa·Banwol·Gumi·Ulsan·Changwon·Geoje·Yeosu·Onsan·Cheongju·Iksan·Gwangyang·POSCO Gwangyang Steel Mill·Asan Bay·Seosan·Songdo·Incheon Airport·Sejong·Cheongna·Geomdan. Korea Trade and Finance Infrastructure: Korea International Trade Association (KITA)·Korea Trade-Investment Promotion Agency (KOTRA)·Export-Import Bank of Korea (KEXIM)·Bank of Korea·Kookmin Bank·Shinhan·Hana·Woori·NH Nonghyup·IBK Industrial Bank·SC First Bank·Citi Bank Korea·HSBC Korea·DBS Korea — 14 Korean major banks and foreign banks. Korea K-POP / K-Content: HYBE·SM·YG·JYP 4 major entertainment companies·CJ ENM·tvN·MBC·KBS·SBS·EBS·YTN·Yonhap News TV·JTBC Korean broadcasting·NETFLIX Korea·Disney Plus·TVING·Wavve·Watcha·Coupang Play. Korea Gaming Industry: Nexon·NCsoft·Krafton·Netmarble·Kakao Games·Pearl Abyss·Com2uS·Gamevil·NHN·Smilegate·Webzen. Korea Automotive / Battery: Hyundai Motor·Kia·Genesis·LG Energy Solution·Samsung SDI·SK On·POSCO Future M·EcoPro·L&F battery cathode material suppliers. Korea Semiconductor: Samsung Electronics (HBM3E·HBM4)·SK hynix (HBM3E 12-Hi)·DB HiTek·SK siltron·SK Enpulse·Dongjin Semichem·Seoul Semiconductor·Simmtech·Samsung Display·LG Display.