#!/bin/bash

GCC=riscv64-unknown-elf-gcc
NM=riscv64-unknown-elf-nm 
# Symbol Linkage Demonstration Script
# This script shows the compilation, assembly, and linking process
# and demonstrates different types of symbols

echo "=== C Source to Assembly to Object to Executable Demo ==="
echo

# Clean up any existing files
echo "1. Cleaning up previous builds..."
rm -f *.o *.s *.i a.out demo_program
echo "   Removed previous build artifacts"
echo

# Step 1: Preprocessing
echo "2. Preprocessing (C -> .i files)..."
$GCC -E math.c -o math.i
$GCC -E main.c -o main.i
echo "   math.c -> math.i (preprocessed)"
echo "   main.c -> main.i (preprocessed)"
echo

# Step 2: Compilation to Assembly
echo "3. Compilation (C -> Assembly .s files)..."
$GCC -S math.c -o math.s
$GCC -S main.c -o main.s
echo "   math.c -> math.s (assembly)"
echo "   main.c -> main.s (assembly)"
echo

# Step 3: Assembly to Object files
echo "4. Assembly (Assembly -> Object .o files)..."
$GCC -c math.s -o math.o
$GCC -c main.s -o main.o
echo "   math.s -> math.o (object file)"
echo "   main.s -> main.o (object file)"
echo

# Alternative: Direct compilation to object files
echo "5. Alternative: Direct compilation to object files..."
$GCC -c math.c -o math_alt.o
$GCC -c main.c -o main_alt.o
echo "   math.c -> math_alt.o (direct compilation)"
echo "   main.c -> main_alt.o (direct compilation)"
echo

# Step 4: Symbol analysis
echo "6. Symbol Analysis..."
echo "   Symbols in math.o:"
$NM math.o
echo
echo "   Symbols in main.o:"
$NM main.o
echo

# Step 5: Linking
echo "7. Linking object files to create executable..."
$GCC math.o main.o -o demo_program
echo "   math.o + main.o -> demo_program (executable)"
echo

# Step 6: Running
echo "8. Running the executable..."
spike pk ./demo_program

# Step 7: Show final executable symbols
echo "9. Final executable symbols:"
$NM demo_program | grep -E "(square|pick_prime|get_n|usrid|pi|e|main)"
echo

echo "=== Symbol Type Explanation ==="
echo "Symbol types in $NM output:"
echo "  T/t = Text (code) section - T=global, t=local"
echo "  D/d = Data section - D=global, d=local"  
echo "  B/b = BSS section (uninitialized) - B=global, b=local"
echo "  U   = Undefined (needs to be resolved by linker)"
echo "  R/r = Read-only data section"
echo

echo "Key observations:"
echo "- 'randomval' and 'is_prime' are static -> local symbols (lowercase)"
echo "- 'pi', 'e', 'square', etc. are global -> exported symbols (uppercase)"
echo "- 'usrid' appears as undefined (U) in math.o but defined in main.o"
echo "- 'printf' appears as undefined (U) - resolved by linking with libc"