Skip to content

Instantly share code, notes, and snippets.

@ProducerMatt
Last active April 19, 2022 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ProducerMatt/58893a78afd0b5e3e22b2b5c2b78dd78 to your computer and use it in GitHub Desktop.
Save ProducerMatt/58893a78afd0b5e3e22b2b5c2b78dd78 to your computer and use it in GitHub Desktop.
hacky fish-shell script for Justine Tunney's cosmopolitan C compiler
#!/usr/bin/env fish
set help "Take one .c file and compile it with cosmo.
Outputs to a .com and .com.dbg file in the current directory.
flags:
--help / -h : print this text
--release : compile without debug options.
currently assumes the cosmo repo is in ~/.local/cosmo
"
# TODO: replace --release with --MODE=tiny,rel,opt etc. Would be great if it
# loaded these preferences from the real makefile instead.
argparse --name=cosmo_fish -X 1 'h/help' 'release' 'purge' -- $argv
or exit
if set -q _flag_help
echo $help
exit 0
end
if set -q _flag_O
set opt "-O$_flag_O"
else
set opt '-Os'
end
if test ! -r $argv[1]
echo "file $argv[1] not readable!"
ls -la $argv[1]
exit 1
end
set outputdir (dirname $argv[1])
if test ! \( -d $outputdir -a -w $outputdir \)
echo "target dir $outputdir not writable"
ls -dla $outputdir
exit 1
end
set target (basename $argv[1] .c)
# TODO: test for presence of gcc and objcopy
if set -q _flag_purge
echo "deleting $outputdir/$target.com{,.dbg}"
rm $outputdir/$target.com{,.dbg}
exit 0
end
set files c_header c_library crt_o ape_o ape_lds
set c_header "cosmopolitan.h"
set c_library "cosmopolitan.a"
set crt_o "libc/crt/crt.o"
set ape_o "ape/ape.o"
set ape_lds "ape/ape.lds"
if set -q _flag_release
set debugvars ""
set prefix "$HOME/.local/cosmo/o/"
else
set debugvars "-pg -fno-schedule-insns2 -fno-omit-frame-pointer \
-fno-optimize-sibling-calls -mno-omit-leaf-frame-pointer \
-ggdb -O2 -DSYSDEBUG -fno-inline \
-fsanitize=address -fsanitize=undefined -fno-pie"
set prefix "$HOME/.local/cosmo/o/dbg/"
set c_header "../cosmopolitan.h"
end
# append prefix to each filename
for i in (seq (count $$files))
set $files[$i] {$prefix}{$$files[$i]}
end
set compile_command "gcc $debugvars -static -fno-pie -no-pie -mno-red-zone -nostdlib -nostdinc \
-fno-omit-frame-pointer -pg -mnop-mcount \
-o $outputdir/$target.com.dbg $outputdir/$target.c -Wl,--gc-sections -fuse-ld=bfd \
-Wl,-T,$ape_lds -include $c_header $crt_o $ape_o $c_library"
set obj_command "objcopy -S -O binary $outputdir/$target.com.dbg $outputdir/$target.com"
eval $compile_command
eval $obj_command
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment