Compare commits

..

39 Commits

Author SHA1 Message Date
Rangi
7ae23e6cdb Release 0.6.0-rc2 2022-09-08 17:07:47 -04:00
Rangi
98a6dffbca Implement opt Q for fixed-point precision, and q literals (e.g. 12.34q8) (#958)
Fixes #957

Co-authored-by: ISSOtm <eldredhabert0@gmail.com>
2022-09-05 00:47:32 +02:00
Rangi
889302a9e2 Document the -H and -l flags
Fixes #1042
2022-09-02 08:43:41 +02:00
Rangi
c01317e08d Only increment the unique \@ ID when it is first used per context (#1030)
This avoids changes to generated `\@` labels just by adding or
removing macros or loops which do not actually use `\@`.

Fixes #1019
2022-08-31 17:45:21 -04:00
Rangi
a52a00a9ca macro_UndefUniqueID uses 0 to mean \@ is undefined 2022-08-30 16:50:34 -04:00
Rangi
fa13611bbf Make comments more consistent
- Changes most `/* comments */` to `// comments`
- Changes `/**` block comments consistently to `/*`
- Adds consistent license comments to all files

Also renames `T_POP_SET` to `T_Z80_SET`
2022-08-30 07:51:32 +02:00
Rangi
dca24a6d50 Test that OPT r fails immediately if the recursion depth is already exceeded
Fixes #1034
2022-08-28 22:21:24 +02:00
Rangi
4363ffcad4 Clarify the JR documentation based on its usage (#1032)
Fixes #1020
2022-08-28 15:42:04 -04:00
Rangi
14e6a79adc Deprecate the old macro syntax (#1025)
Fixes #1011
2022-08-28 15:22:21 -04:00
Rangi
7a2ee26792 rgbasm -r sets the maximum recursion depth (#1026)
Previously it set the minimum failure depth (off by one)

Fixes #978
2022-08-28 15:21:29 -04:00
Rangi
425339ccf6 Implement FMOD function for fixed-point modulo
Fixes #1021
2022-08-28 21:21:10 +02:00
Rangi
1a1f1365e6 Clarify the FOR loop documentation (#1031)
Clarify the FOR loop documentation

Fixes #1003

Co-authored-by: Eldred Habert <eldredhabert0@gmail.com>
2022-08-28 15:16:49 -04:00
Rangi
f97139461c Clarify the linkerscript example (#1028)
* Clarify the linkerscript example

* Explain that backslash escape sequences are supported

Fixes #1006
2022-08-28 15:13:43 -04:00
Rangi
8207dc57b7 Add a -Wunmapped-char warning for characters not in the charmap (#1023)
Fixes #1022
2022-08-28 15:12:43 -04:00
Rangi
d29057e747 Indent "SLACK:" to match the "SECTION" headers 2022-08-28 20:35:21 +02:00
Rangi
f1b74fa610 Report empty space between sections in map file 2022-08-28 20:35:21 +02:00
Rangi
c7a92d3104 rgblink -M omits symbol names from .map file 2022-08-28 20:35:21 +02:00
ISSOtm
0105779789 Fix incorrect Bash completions after --long-opt=
This is because `$COMP_CWORD` points to that `=` "word".
2022-08-10 08:44:41 +02:00
ISSOtm
9ef7954670 Fix some lint warnings in Bash completions 2022-08-10 00:16:05 +02:00
ISSOtm
d7d524294b Fix shebangs in Bash completion scripts
Not that you are really supposed to run them stand-alone?
2022-08-09 22:32:18 +02:00
ISSOtm
12fed4c68e Harden Bash completion scripts against invalid states
Printing an error message is better than locking the shell up, honestly.
2022-08-09 22:30:50 +02:00
ISSOtm
3db3421f07 Correct wrong state transitions in RGBGFX Bash completion script
Isn't strinly-typed programming just lovely?
Fixes #1018
2022-08-09 22:28:12 +02:00
ISSOtm
92eb0a133b Allow rgbgfx -r to read an infinite amount of tiles without tilemap
Previously, indices would be wrapped after 256 even without a tilemap;
since RGBGFX can generate arbitrarily large tile data if `-N` is not used,
it should be possible to read those in.

Of course, this won't work if a tilemap is provided, but such "big blobs"
can't generate a meaningful tilemap anyway.
2022-08-04 20:50:08 +02:00
ISSOtm
b02ccf8f4a Check before attempting to generate empty image
This causes a libpng warning then error, but print a better error message
Fixes #1016
2022-08-04 20:40:20 +02:00
ISSOtm
2e0991f32b Use proper 16-bit type for image reversing width
Fixes #1015
2022-08-04 20:40:20 +02:00
Eldred Habert
f3f2c2ca16 Improve object file format documentation (#1010)
Replacing the big pre-formatted text block with a list brings:
- Better accessibility, obviously
- Responsiveness
- Better formatting (bold, etc.)
- Sub-sections that can now be linked to
- Hyperlink cross-refs to other pages

The slight disadvantage is that `ENDC` etc. are now individual
list items, whereas they'd be better as part of the same item.
No big deal though, it was much worse before.

Some descriptions have been overhauled for clarity, and some
outright corrected (such as Assertions' "Offset" field).

Co-authored-by: Antonio Vivace <avivace4@gmail.com>
2022-07-29 22:48:55 +02:00
ISSOtm
9ec8186ac6 Switch linkdefs from scattered arrays to an array of structs
The info is better organized this way
2022-07-19 19:11:02 +02:00
ISSOtm
ab9945c1ee Avoid using fscanf to detect RGBDS object files
This function is made for text, e.g. accepts spaces, leading zeros, etc. before `%u`.
This way checks that the correct amount of bytes are read instead.
2022-07-19 19:10:58 +02:00
ISSOtm
18e4f132a8 Fix labels subtraction docs
Fixes #1009
2022-07-14 13:43:36 +02:00
ISSOtm
828b2adcdf Make RGBLINK able to link SDCC object files
This requires a LOT of tricky code, mostly due to the format itself being,
er, not the most straightforward.
Everything is converted to existing RGBLINK concepts (sections, patches,
etc.), so the core code is essentially unchanged.
(A couple of genuine RGBLINK bugs were uncovered along the way, so some of
the core code *is* changed, notably regarding `SECTION FRAGMENT`s.)

All of this code was clean-roomed, so SDCC's GPLv2 license does not apply.
2022-07-11 21:17:34 +02:00
ISSOtm
1c2965467d Process linker script before doing sanity checks 2022-07-11 21:17:34 +02:00
ISSOtm
d243e50390 Do not perform any sanity checks for bad section types
Otherwise, the arrays get overflowed
2022-07-11 21:17:34 +02:00
ISSOtm
acb33777c6 Sort RGB colors as specified in the docs 2022-07-10 12:36:10 +02:00
ISSOtm
d15916b1bd Clarify sorting order of RGB colors 2022-07-10 12:32:57 +02:00
ISSOtm
28fcef0ecd Improve some wording slightly 2022-07-10 12:30:18 +02:00
ISSOtm
b53c115ec2 Fix width and height being reported in wrong order 2022-07-10 12:14:24 +02:00
ISSOtm
6a51e39a5c Print error if reverse() fails to open a file 2022-07-10 11:55:56 +02:00
Antonio Vivace
e348f70866 Remove funding options, leaving only OpenCollective 2022-07-08 21:22:28 +02:00
ISSOtm
43a487f0bf Fix two inverted column widths 2022-07-02 17:48:28 +02:00
176 changed files with 3394 additions and 2159 deletions

2
.github/FUNDING.yml vendored
View File

@@ -1,3 +1 @@
github: avivace
patreon: gbdev01
open_collective: gbdev

View File

@@ -91,6 +91,7 @@ rgblink_obj := \
src/link/output.o \
src/link/patch.o \
src/link/script.o \
src/link/sdas_obj.o \
src/link/section.o \
src/link/symbol.o \
src/extern/getopt.o \

View File

@@ -1,4 +1,4 @@
#/usr/bin/env bash
#!/usr/bin/env bash
# Known bugs:
# - Newlines in file/directory names break this script
@@ -11,7 +11,7 @@
# - Directories are not completed as such in "coalesced" short-opt arguments. For example,
# `rgbasm -M d<tab>` can autocomplete to `rgbasm -M dir/` (no space), but
# `rgbasm -Md<tab>` would autocomplete to `rgbasm -Mdir ` (trailing space) instead.
# This is because dircetory handling is performed by Readline, whom we can't tell about the short
# This is because directory handling is performed by Readline, whom we can't tell about the short
# opt kerfuffle. The user can work around by separating the argument, as shown above.
# (Also, there might be more possible bugs if `-Mdir` is actually a directory. Ugh.)
@@ -20,16 +20,16 @@
# Thus, we don't need to do much to handle that form of argument passing: skip '=' after long opts.
_rgbasm_completions() {
COMPREPLY=()
# Format: "long_opt:state_after"
# Empty long opt = it doesn't exit
# See the `state` variable below for info about `state_after`
declare -A opts=(
[V]="version:normal"
[E]="export-all:normal"
[H]="nop-after-halt:normal"
[h]="halt-without-nop:normal"
[L]="preserve-ld:normal"
[l]="auto-ldh:normal"
[v]="verbose:normal"
[w]=":normal"
[b]="binary-digits:unk"
@@ -39,6 +39,7 @@ _rgbasm_completions() {
[M]="dependfile:glob-*.mk *.d"
[o]="output:glob-*.o"
[p]="pad-value:unk"
[Q]="q-precision:unk"
[r]="recursion-depth:unk"
[W]="warning:warning"
)
@@ -58,6 +59,18 @@ _rgbasm_completions() {
# "normal" is not returned, `optlen` will be set to the length (dash included) of the "option"
# part of the argument.
parse_short_opt() {
# These options act like a long option (= takes up the entire word), but only use a single dash
# So, they need some special handling
if [[ "$1" = "-M"[GP] ]]; then
state=normal
optlen=${#1}
return;
elif [[ "$1" = "-M"[QT] ]]; then
state='glob-*.d *.mk *.o'
optlen=${#1}
return;
fi
for (( i = 1; i < "${#1}"; i++ )); do
# If the option is not known, assume it doesn't take an argument
local opt="${opts["${1:$i:1}"]:-":normal"}"
@@ -71,7 +84,7 @@ _rgbasm_completions() {
optlen=0
}
for (( i = 1; i < $COMP_CWORD; i++ )); do
for (( i = 1; i < COMP_CWORD; i++ )); do
local word="${COMP_WORDS[$i]}"
# If currently processing an argument, skip this word
@@ -87,7 +100,7 @@ _rgbasm_completions() {
fi
# Check if it's a long option
if [[ "${word:0:2}" = '--' ]]; then
if [[ "$word" = '--'* ]]; then
# If the option is unknown, assume it takes no arguments: keep the state at "normal"
for long_opt in "${opts[@]}"; do
if [[ "$word" = "--${long_opt%%:*}" ]]; then
@@ -103,25 +116,16 @@ _rgbasm_completions() {
fi
done
# Check if it's a short option
elif [[ "${word:0:1}" = '-' ]]; then
# The `-M?` ones are a mix of short and long, augh
# They must match the *full* word, but only take a single dash
# So, handle them here
if [[ "$1" = "-M"[GP] ]]; then
state=normal
elif [[ "$1" = "-M"[TQ] ]]; then
state='glob-*.d *.mk *.o'
else
parse_short_opt "$word"
# The last option takes an argument...
if [[ "$state" != 'normal' ]]; then
if [[ "$optlen" -ne "${#word}" ]]; then
# If it's contained within the word, we won't complete it, revert to "normal"
state=normal
else
# Otherwise, complete it, but start at the beginning of *that* word
optlen=0
fi
elif [[ "$word" = '-'* ]]; then
parse_short_opt "$word"
# The last option takes an argument...
if [[ "$state" != 'normal' ]]; then
if [[ "$optlen" -ne "${#word}" ]]; then
# If it's contained within the word, we won't complete it, revert to "normal"
state=normal
else
# Otherwise, complete it, but start at the beginning of *that* word
optlen=0
fi
fi
fi
@@ -129,48 +133,48 @@ _rgbasm_completions() {
# Parse current word
# Careful that it might look like an option, so use `--` aggressively!
local cur_word="${COMP_WORDS[$COMP_CWORD]}"
local cur_word="${COMP_WORDS[$i]}"
# Process options, as short ones may change the state
if $opt_ena && [[ "$state" = 'normal' && "${cur_word:0:1}" = '-' ]]; then
if $opt_ena && [[ "$state" = 'normal' && "$cur_word" = '-'* ]]; then
# We might want to complete to an option or an arg to that option
# Parse the option word to check
# There's no whitespace in the option names, so we can ride a little dirty...
# Is this a long option?
if [[ "${cur_word:1:1}" = '-' ]]; then
if [[ "$cur_word" = '--'* ]]; then
# It is, try to complete one
COMPREPLY+=( $(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}") )
mapfile -t COMPREPLY < <(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}")
return 0
elif [[ "$cur_word" = '-M'[GPQT] ]]; then
# These options act like long opts with no arguments, so return them and exactly them
COMPREPLY=( "$cur_word" )
return 0
else
# Short options may be grouped, parse them to determine what to complete
# The `-M?` ones may not be followed by anything
if [[ "$1" != "-M"[GPTQ] ]]; then
parse_short_opt "$cur_word"
# We got some short options that behave like long ones
COMPREPLY+=( $(compgen -W '-MG -MP -MT -MQ' -- "$cur_word") )
parse_short_opt "$cur_word"
if [[ "$state" = 'normal' ]]; then
COMPREPLY+=( $(compgen -W "${!opts[*]}" -P "$cur_word" '') )
return 0
elif [[ "$optlen" = "${#cur_word}" && "$state" != "warning" ]]; then
# This short option group only awaits its argument!
# Post the option group as-is as a reply so that Readline inserts a space,
# so that the next completion request switches to the argument
# An exception is made for warnings, since it's idiomatic to stick them to the
# `-W`, and it doesn't break anything.
COMPREPLY+=( "$cur_word" )
return 0
fi
if [[ "$state" = 'normal' ]]; then
mapfile -t COMPREPLY < <(compgen -W "${!opts[*]}" -P "$cur_word" ''; compgen -W '-MG -MP -MQ -MT' "$cur_word")
return 0
elif [[ "$optlen" = "${#cur_word}" && "$state" != "warning" ]]; then
# This short option group only awaits its argument!
# Post the option group as-is as a reply so that Readline inserts a space,
# so that the next completion request switches to the argument
# An exception is made for warnings, since it's idiomatic to stick them to the
# `-W`, and it doesn't break anything.
COMPREPLY=( "$cur_word" )
return 0
fi
fi
fi
COMPREPLY=()
case "$state" in
unk) # Return with no replies: no idea what to complete!
;;
warning)
COMPREPLY+=( $(compgen -W "
mapfile -t COMPREPLY < <(compgen -W "
assert
backwards-for
builtin-args
@@ -188,11 +192,12 @@ _rgbasm_completions() {
shift
shift-amount
truncation
unmapped-char
user
all
extra
everything
error" -P "${cur_word:0:$optlen}" -- "${cur_word:$optlen}") )
error" -P "${cur_word:0:$optlen}" -- "${cur_word:$optlen}")
;;
normal) # Acts like a glob...
state="glob-*.asm *.inc *.sm83"
@@ -209,6 +214,10 @@ _rgbasm_completions() {
done < <(compgen -A directory -- "${cur_word:$optlen}")
compopt -o filenames
;;
*)
echo >&2 "Internal completion error: invalid state \"$state\", please report this bug"
return 1
;;
esac
}

View File

@@ -1,10 +1,8 @@
#/usr/bin/env bash
#!/usr/bin/env bash
# Same notes as RGBASM
_rgbfix_completions() {
COMPREPLY=()
# Format: "long_opt:state_after"
# Empty long opt = it doesn't exit
# See the `state` variable below for info about `state_after`
@@ -54,7 +52,7 @@ _rgbfix_completions() {
optlen=0
}
for (( i = 1; i < $COMP_CWORD; i++ )); do
for (( i = 1; i < COMP_CWORD; i++ )); do
local word="${COMP_WORDS[$i]}"
# If currently processing an argument, skip this word
@@ -70,7 +68,7 @@ _rgbfix_completions() {
fi
# Check if it's a long option
if [[ "${word:0:2}" = '--' ]]; then
if [[ "$word" = '--'* ]]; then
# If the option is unknown, assume it takes no arguments: keep the state at "normal"
for long_opt in "${opts[@]}"; do
if [[ "$word" = "--${long_opt%%:*}" ]]; then
@@ -86,7 +84,7 @@ _rgbfix_completions() {
fi
done
# Check if it's a short option
elif [[ "${word:0:1}" = '-' ]]; then
elif [[ "$word" = '-'* ]]; then
parse_short_opt "$word"
# The last option takes an argument...
if [[ "$state" != 'normal' ]]; then
@@ -103,25 +101,25 @@ _rgbfix_completions() {
# Parse current word
# Careful that it might look like an option, so use `--` aggressively!
local cur_word="${COMP_WORDS[$COMP_CWORD]}"
local cur_word="${COMP_WORDS[$i]}"
# Process options, as short ones may change the state
if $opt_ena && [[ "$state" = 'normal' && "${cur_word:0:1}" = '-' ]]; then
if $opt_ena && [[ "$state" = 'normal' && "$cur_word" = '-'* ]]; then
# We might want to complete to an option or an arg to that option
# Parse the option word to check
# There's no whitespace in the option names, so we can ride a little dirty...
# Is this a long option?
if [[ "${cur_word:1:1}" = '-' ]]; then
if [[ "$cur_word" = '--'* ]]; then
# It is, try to complete one
COMPREPLY+=( $(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}") )
mapfile -t COMPREPLY < <(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}")
return 0
else
# Short options may be grouped, parse them to determine what to complete
parse_short_opt "$cur_word"
if [[ "$state" = 'normal' ]]; then
COMPREPLY+=( $(compgen -W "${!opts[*]}" -P "$cur_word" '') )
mapfile -t COMPREPLY < <(compgen -W "${!opts[*]}" -P "$cur_word" '')
return 0
elif [[ "$optlen" = "${#cur_word}" && "$state" != "warning" ]]; then
# This short option group only awaits its argument!
@@ -129,22 +127,25 @@ _rgbfix_completions() {
# so that the next completion request switches to the argument
# An exception is made for warnings, since it's idiomatic to stick them to the
# `-W`, and it doesn't break anything.
COMPREPLY+=( "$cur_word" )
COMPREPLY=( "$cur_word" )
return 0
fi
fi
fi
COMPREPLY=()
case "$state" in
unk) # Return with no replies: no idea what to complete!
;;
fix-spec)
COMPREPLY+=( "${cur_word}"{l,h,g,L,H,G} )
COMPREPLY=( "${cur_word}"{l,h,g,L,H,G} )
;;
mbc)
local cur_arg="${cur_word:$optlen}"
cur_arg="${cur_arg@U}"
COMPREPLY=( $(compgen -W "
compopt -o nosort # Keep `help` first in the list, mainly
mapfile -t COMPREPLY < <(compgen -W "help" -P "${cur_word:0:$optlen}" -- "${cur_word:$optlen}")
mapfile -t COMPREPLY -O ${#COMPREPLY} < <(compgen -W "
ROM_ONLY
MBC1{,+RAM,+RAM+BATTERY}
MBC2{,+BATTERY}
@@ -157,8 +158,7 @@ _rgbfix_completions() {
BANDAI_TAMA5
HUC3
HUC1+RAM+BATTERY
TPP1_1.0{,+BATTERY}{,+RTC}{,+RUMBLE,+MULTIRUMBLE}" -P "${cur_word:0:$optlen}" -- "`tr 'a-z ' 'A-Z_' <<<"${cur_word/ /_}"`") )
COMPREPLY+=( $(compgen -W "help" -P "${cur_word:0:$optlen}" -- "${cur_word:$optlen}") )
TPP1_1.0{,+BATTERY}{,+RTC}{,+RUMBLE,+MULTIRUMBLE}" -P "${cur_word:0:$optlen}" -- "${cur_word/ /_}")
;;
normal) # Acts like a glob...
state="glob-*.gb *.gbc *.sgb"
@@ -175,6 +175,10 @@ _rgbfix_completions() {
done < <(compgen -A directory -- "${cur_word:$optlen}")
compopt -o filenames
;;
*)
echo >&2 "Internal completion error: invalid state \"$state\", please report this bug"
return 1
;;
esac
}

View File

@@ -1,10 +1,8 @@
#/usr/bin/env bash
#!/usr/bin/env bash
# Same notes as RGBASM
_rgbgfx_completions() {
COMPREPLY=()
# Format: "long_opt:state_after"
# Empty long opt = it doesn't exit
# See the `state` variable below for info about `state_after`
@@ -15,21 +13,21 @@ _rgbgfx_completions() {
[u]="unique-tiles:normal"
[v]="verbose:normal"
[Z]="columns:normal"
[a]="attr-map:*.attrmap"
[a]="attr-map:glob-*.attrmap"
[A]="output-attr-map:normal"
[b]="base-tiles:unk"
[d]="depth:unk"
[L]="slice:unk"
[N]="nb-tiles:unk"
[n]="nb-palettes:unk"
[o]="output:glob *.2bpp"
[p]="palette:glob *.pal"
[o]="output:glob-*.2bpp"
[p]="palette:glob-*.pal"
[P]="output-palette:normal"
[q]="palette-map:glob *.palmap"
[q]="palette-map:glob-*.palmap"
[Q]="output-palette-map:normal"
[r]="reverse:unk"
[s]="palette-size:unk"
[t]="tilemap:glob *.tilemap"
[t]="tilemap:glob-*.tilemap"
[T]="output-tilemap:normal"
[x]="trim-end:unk"
)
@@ -62,7 +60,7 @@ _rgbgfx_completions() {
optlen=0
}
for (( i = 1; i < $COMP_CWORD; i++ )); do
for (( i = 1; i < COMP_CWORD; i++ )); do
local word="${COMP_WORDS[$i]}"
# If currently processing an argument, skip this word
@@ -78,7 +76,7 @@ _rgbgfx_completions() {
fi
# Check if it's a long option
if [[ "${word:0:2}" = '--' ]]; then
if [[ "$word" = '--'* ]]; then
# If the option is unknown, assume it takes no arguments: keep the state at "normal"
for long_opt in "${opts[@]}"; do
if [[ "$word" = "--${long_opt%%:*}" ]]; then
@@ -94,7 +92,7 @@ _rgbgfx_completions() {
fi
done
# Check if it's a short option
elif [[ "${word:0:1}" = '-' ]]; then
elif [[ "$word" = '-'* ]]; then
parse_short_opt "$word"
# The last option takes an argument...
if [[ "$state" != 'normal' ]]; then
@@ -111,25 +109,25 @@ _rgbgfx_completions() {
# Parse current word
# Careful that it might look like an option, so use `--` aggressively!
local cur_word="${COMP_WORDS[$COMP_CWORD]}"
local cur_word="${COMP_WORDS[$i]}"
# Process options, as short ones may change the state
if $opt_ena && [[ "$state" = 'normal' && "${cur_word:0:1}" = '-' ]]; then
if $opt_ena && [[ "$state" = 'normal' && "$cur_word" = '-'* ]]; then
# We might want to complete to an option or an arg to that option
# Parse the option word to check
# There's no whitespace in the option names, so we can ride a little dirty...
# Is this a long option?
if [[ "${cur_word:1:1}" = '-' ]]; then
if [[ "$cur_word" = '--'* ]]; then
# It is, try to complete one
COMPREPLY+=( $(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}") )
mapfile -t COMPREPLY < <(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}")
return 0
else
# Short options may be grouped, parse them to determine what to complete
parse_short_opt "$cur_word"
if [[ "$state" = 'normal' ]]; then
COMPREPLY+=( $(compgen -W "${!opts[*]}" -P "$cur_word" '') )
mapfile -t COMPREPLY < <(compgen -W "${!opts[*]}" -P "$cur_word" '')
return 0
elif [[ "$optlen" = "${#cur_word}" && "$state" != "warning" ]]; then
# This short option group only awaits its argument!
@@ -137,12 +135,13 @@ _rgbgfx_completions() {
# so that the next completion request switches to the argument
# An exception is made for warnings, since it's idiomatic to stick them to the
# `-W`, and it doesn't break anything.
COMPREPLY+=( "$cur_word" )
COMPREPLY=( "$cur_word" )
return 0
fi
fi
fi
COMPREPLY=()
case "$state" in
unk) # Return with no replies: no idea what to complete!
;;
@@ -161,6 +160,10 @@ _rgbgfx_completions() {
done < <(compgen -A directory -- "${cur_word:$optlen}")
compopt -o filenames
;;
*)
echo >&2 "Internal completion error: invalid state \"$state\", please report this bug"
return 1
;;
esac
}

View File

@@ -1,10 +1,8 @@
#/usr/bin/env bash
#!/usr/bin/env bash
# Same notes as RGBASM
_rgblink_completions() {
COMPREPLY=()
# Format: "long_opt:state_after"
# Empty long opt = it doesn't exit
# See the `state` variable below for info about `state_after`
@@ -16,6 +14,7 @@ _rgblink_completions() {
[w]="wramx:normal"
[x]="nopad:normal"
[l]="linkerscript:glob-*"
[M]="no-sym-in-map:normal"
[m]="map:glob-*.map"
[n]="sym:glob-*.sym"
[O]="overlay:glob-*.gb *.gbc *.sgb"
@@ -52,7 +51,7 @@ _rgblink_completions() {
optlen=0
}
for (( i = 1; i < $COMP_CWORD; i++ )); do
for (( i = 1; i < COMP_CWORD; i++ )); do
local word="${COMP_WORDS[$i]}"
# If currently processing an argument, skip this word
@@ -68,7 +67,7 @@ _rgblink_completions() {
fi
# Check if it's a long option
if [[ "${word:0:2}" = '--' ]]; then
if [[ "$word" = '--'* ]]; then
# If the option is unknown, assume it takes no arguments: keep the state at "normal"
for long_opt in "${opts[@]}"; do
if [[ "$word" = "--${long_opt%%:*}" ]]; then
@@ -84,7 +83,7 @@ _rgblink_completions() {
fi
done
# Check if it's a short option
elif [[ "${word:0:1}" = '-' ]]; then
elif [[ "$word" = '-'* ]]; then
parse_short_opt "$word"
# The last option takes an argument...
if [[ "$state" != 'normal' ]]; then
@@ -101,25 +100,25 @@ _rgblink_completions() {
# Parse current word
# Careful that it might look like an option, so use `--` aggressively!
local cur_word="${COMP_WORDS[$COMP_CWORD]}"
local cur_word="${COMP_WORDS[$i]}"
# Process options, as short ones may change the state
if $opt_ena && [[ "$state" = 'normal' && "${cur_word:0:1}" = '-' ]]; then
if $opt_ena && [[ "$state" = 'normal' && "$cur_word" = '-'* ]]; then
# We might want to complete to an option or an arg to that option
# Parse the option word to check
# There's no whitespace in the option names, so we can ride a little dirty...
# Is this a long option?
if [[ "${cur_word:1:1}" = '-' ]]; then
if [[ "$cur_word" = '--'* ]]; then
# It is, try to complete one
COMPREPLY+=( $(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}") )
mapfile -t COMPREPLY < <(compgen -W "${opts[*]%%:*}" -P '--' -- "${cur_word#--}")
return 0
else
# Short options may be grouped, parse them to determine what to complete
parse_short_opt "$cur_word"
if [[ "$state" = 'normal' ]]; then
COMPREPLY+=( $(compgen -W "${!opts[*]}" -P "$cur_word" '') )
mapfile -t COMPREPLY < <(compgen -W "${!opts[*]}" -P "$cur_word" '')
return 0
elif [[ "$optlen" = "${#cur_word}" && "$state" != "warning" ]]; then
# This short option group only awaits its argument!
@@ -127,12 +126,13 @@ _rgblink_completions() {
# so that the next completion request switches to the argument
# An exception is made for warnings, since it's idiomatic to stick them to the
# `-W`, and it doesn't break anything.
COMPREPLY+=( "$cur_word" )
COMPREPLY=( "$cur_word" )
return 0
fi
fi
fi
COMPREPLY=()
case "$state" in
unk) # Return with no replies: no idea what to complete!
;;
@@ -151,6 +151,10 @@ _rgblink_completions() {
done < <(compgen -A directory -- "${cur_word:$optlen}")
compopt -o filenames
;;
*)
echo >&2 "Internal completion error: invalid state \"$state\", please report this bug"
return 1
;;
esac
}

View File

@@ -25,6 +25,7 @@ _rgbasm_warnings() {
'shift:Warn when shifting negative values'
'shift-amount:Warn when a shift'\''s operand it negative or \> 32'
'truncation:Warn when implicit truncation loses bits'
'unmapped-char:Warn on unmapped character'
'user:Warn when executing the WARN built-in'
)
# TODO: handle `no-` and `error=` somehow?
@@ -37,8 +38,10 @@ local args=(
'(- : * options)'{-V,--version}'[Print version number]'
'(-E --export-all)'{-E,--export-all}'[Export all symbols]'
'(-h --halt-without-nop)'{-h,--halt-without-nop}'[Avoid outputting a `nop` after `halt`]'
'(-L ---preserve-ld)'{-L,--preserve-ld}'[Prevent auto-optimizing `ld` into `ldh`]'
'(-H --nop-after-halt)'{-H,--nop-after-halt}'[Output a `nop` after `halt`]'
'(-h --halt-without-nop)'{-h,--halt-without-nop}'[Prevent outputting a `nop` after `halt`]'
'(-L --preserve-ld)'{-L,--preserve-ld}'[Prevent optimizing `ld` into `ldh`]'
'(-l --auto-ldh)'{-l,--auto-ldh}'[Optimize `ld` into `ldh`]'
'(-v --verbose)'{-v,--verbose}'[Print additional messages regarding progression]'
-w'[Disable all warnings]'
@@ -53,6 +56,7 @@ local args=(
'*'-MQ"+[Add a target to the rules]:target:_files -g '*.{d,mk,o}'"
'(-o --output)'{-o,--output}'+[Output file]:output file:_files'
'(-p --pad-value)'{-p,--pad-value}'+[Set padding byte]:padding byte:'
'(-Q --q-precision)'{-Q,--q-precision}'+[Set fixed-point precision]:precision:'
'(-r --recursion-depth)'{-r,--recursion-depth}'+[Set maximum recursion depth]:depth:'
'(-W --warning)'{-W,--warning}'+[Toggle warning flags]:warning flag:_rgbasm_warnings'

View File

@@ -11,6 +11,7 @@ local args=(
'(-x --nopad)'{-x,--nopad}'[Disable padding the end of the final file]'
'(-l --linkerscript)'{-l,--linkerscript}"+[Use a linker script]:linker script:_files -g '*.link'"
'(-M --no-sym-in-map)'{-M,--no-sym-in-map}'[Do not output symbol names in map file]'
'(-m --map)'{-m,--map}"+[Produce a map file]:map file:_files -g '*.map'"
'(-n --sym)'(-n,--sym)"+[Produce a symbol file]:sym file:_files -g '*.sym'"
'(-O --overlay)'{-O,--overlay}'+[Overlay sections over on top of bin file]:base overlay:_files'

View File

@@ -20,4 +20,4 @@ void charmap_Add(char *mapping, uint8_t value);
size_t charmap_Convert(char const *input, uint8_t *output);
size_t charmap_ConvertNext(char const **input, uint8_t **output);
#endif /* RGBDS_ASM_CHARMAP_H */
#endif // RGBDS_ASM_CHARMAP_H

View File

@@ -11,6 +11,9 @@
#include <stdint.h>
extern uint8_t fixPrecision;
double fix_PrecisionFactor(void);
void fix_Print(int32_t i);
int32_t fix_Sin(int32_t i);
int32_t fix_Cos(int32_t i);
@@ -20,6 +23,7 @@ int32_t fix_ACos(int32_t i);
int32_t fix_ATan(int32_t i);
int32_t fix_ATan2(int32_t i, int32_t j);
int32_t fix_Mul(int32_t i, int32_t j);
int32_t fix_Mod(int32_t i, int32_t j);
int32_t fix_Div(int32_t i, int32_t j);
int32_t fix_Pow(int32_t i, int32_t j);
int32_t fix_Log(int32_t i, int32_t j);
@@ -27,4 +31,4 @@ int32_t fix_Round(int32_t i);
int32_t fix_Ceil(int32_t i);
int32_t fix_Floor(int32_t i);
#endif /* RGBDS_ASM_FIXPOINT_H */
#endif // RGBDS_ASM_FIXPOINT_H

View File

@@ -60,4 +60,4 @@ void fmt_FinishCharacters(struct FormatSpec *fmt);
void fmt_PrintString(char *buf, size_t bufLen, struct FormatSpec const *fmt, char const *value);
void fmt_PrintNumber(char *buf, size_t bufLen, struct FormatSpec const *fmt, uint32_t value);
#endif /* RGBDS_FORMAT_SPEC_H */
#endif // RGBDS_FORMAT_SPEC_H

View File

@@ -6,9 +6,7 @@
* SPDX-License-Identifier: MIT
*/
/*
* Contains some assembler-wide defines and externs
*/
// Contains some assembler-wide defines and externs
#ifndef RGBDS_ASM_FSTACK_H
#define RGBDS_ASM_FSTACK_H
@@ -21,13 +19,13 @@
struct FileStackNode {
struct FileStackNode *parent; /* Pointer to parent node, for error reporting */
/* Line at which the parent context was exited; meaningless for the root level */
struct FileStackNode *parent; // Pointer to parent node, for error reporting
// Line at which the parent context was exited; meaningless for the root level
uint32_t lineNo;
struct FileStackNode *next; /* Next node in the output linked list */
bool referenced; /* If referenced, don't free! */
uint32_t ID; /* Set only if referenced: ID within the object file, -1 if not output yet */
struct FileStackNode *next; // Next node in the output linked list
bool referenced; // If referenced, don't free!
uint32_t ID; // Set only if referenced: ID within the object file, -1 if not output yet
enum {
NODE_REPT,
@@ -36,18 +34,19 @@ struct FileStackNode {
} type;
};
struct FileStackReptNode { /* NODE_REPT */
struct FileStackReptNode { // NODE_REPT
struct FileStackNode node;
uint32_t reptDepth;
/* WARNING: if changing this type, change overflow check in `fstk_Init` */
uint32_t iters[]; /* REPT iteration counts since last named node, in reverse depth order */
// WARNING: if changing this type, change overflow check in `fstk_Init`
uint32_t iters[]; // REPT iteration counts since last named node, in reverse depth order
};
struct FileStackNamedNode { /* NODE_FILE, NODE_MACRO */
struct FileStackNamedNode { // NODE_FILE, NODE_MACRO
struct FileStackNode node;
char name[]; /* File name for files, file::macro name for macros */
char name[]; // File name for files, file::macro name for macros
};
#define DEFAULT_MAX_DEPTH 64
extern size_t maxRecursionDepth;
struct MacroArgs;
@@ -55,11 +54,11 @@ struct MacroArgs;
void fstk_Dump(struct FileStackNode const *node, uint32_t lineNo);
void fstk_DumpCurrent(void);
struct FileStackNode *fstk_GetFileStack(void);
/* The lifetime of the returned chars is until reaching the end of that file */
// The lifetime of the returned chars is until reaching the end of that file
char const *fstk_GetFileName(void);
void fstk_AddIncludePath(char const *s);
/**
/*
* @param path The user-provided file name
* @param fullPath The address of a pointer, which will be made to point at the full path
* The pointer's value must be a valid argument to `realloc`, including NULL
@@ -80,4 +79,4 @@ bool fstk_Break(void);
void fstk_NewRecursionDepth(size_t newDepth);
void fstk_Init(char const *mainPath, size_t maxDepth);
#endif /* RGBDS_ASM_FSTACK_H */
#endif // RGBDS_ASM_FSTACK_H

View File

@@ -11,7 +11,7 @@
#include <stdbool.h>
#define MAXSTRLEN 255
#define MAXSTRLEN 255
struct LexerState;
extern struct LexerState *lexerState;
@@ -49,9 +49,7 @@ static inline void lexer_SetGfxDigits(char const digits[4])
gfxDigits[3] = digits[3];
}
/*
* `path` is referenced, but not held onto..!
*/
// `path` is referenced, but not held onto..!
struct LexerState *lexer_OpenFile(char const *path);
struct LexerState *lexer_OpenFileView(char const *path, char *buf, size_t size, uint32_t lineNo);
void lexer_RestartRept(uint32_t lineNo);
@@ -99,4 +97,4 @@ struct DsArgList {
struct Expression *args;
};
#endif /* RGBDS_ASM_LEXER_H */
#endif // RGBDS_ASM_LEXER_H

View File

@@ -31,7 +31,8 @@ uint32_t macro_GetUniqueID(void);
char const *macro_GetUniqueIDStr(void);
void macro_SetUniqueID(uint32_t id);
uint32_t macro_UseNewUniqueID(void);
uint32_t macro_UndefUniqueID(void);
void macro_ShiftCurrentArgs(int32_t count);
uint32_t macro_NbArgs(void);
#endif
#endif // RGBDS_MACRO_H

View File

@@ -20,7 +20,7 @@ extern bool warnOnHaltNop;
extern bool optimizeLoads;
extern bool warnOnLdOpt;
extern bool verbose;
extern bool warnings; /* True to enable warnings, false to disable them. */
extern bool warnings; // True to enable warnings, false to disable them.
extern FILE *dependfile;
extern char *targetFileName;
@@ -28,4 +28,4 @@ extern bool generatedMissingIncludes;
extern bool failedOnMissingInclude;
extern bool generatePhonyDeps;
#endif /* RGBDS_MAIN_H */
#endif // RGBDS_MAIN_H

View File

@@ -14,7 +14,8 @@
void opt_B(char const chars[2]);
void opt_G(char const chars[4]);
void opt_P(uint8_t fill);
void opt_P(uint8_t padByte);
void opt_Q(uint8_t precision);
void opt_L(bool optimize);
void opt_W(char const *flag);
void opt_Parse(char const *option);
@@ -22,4 +23,4 @@ void opt_Parse(char const *option);
void opt_Push(void);
void opt_Pop(void);
#endif
#endif // RGBDS_OPT_H

View File

@@ -27,4 +27,4 @@ bool out_CreateAssert(enum AssertionType type, struct Expression const *expr,
char const *message, uint32_t ofs);
void out_WriteObject(void);
#endif /* RGBDS_ASM_OUTPUT_H */
#endif // RGBDS_ASM_OUTPUT_H

View File

@@ -27,17 +27,13 @@ struct Expression {
uint32_t rpnPatchSize; // Size the expression will take in the object file
};
/*
* Determines if an expression is known at assembly time
*/
// Determines if an expression is known at assembly time
static inline bool rpn_isKnown(struct Expression const *expr)
{
return expr->isKnown;
}
/*
* Determines if an expression is a symbol suitable for const diffing
*/
// Determines if an expression is a symbol suitable for const diffing
static inline bool rpn_isSymbol(const struct Expression *expr)
{
return expr->isSymbol;
@@ -67,4 +63,4 @@ void rpn_CheckRST(struct Expression *expr, const struct Expression *src);
void rpn_CheckNBit(struct Expression const *expr, uint8_t n);
int32_t rpn_GetConstVal(struct Expression const *expr);
#endif /* RGBDS_ASM_RPN_H */
#endif // RGBDS_ASM_RPN_H

View File

@@ -23,8 +23,8 @@ struct Section {
char *name;
enum SectionType type;
enum SectionModifier modifier;
struct FileStackNode *src; /* Where the section was defined */
uint32_t fileLine; /* Line where the section was defined */
struct FileStackNode *src; // Where the section was defined
uint32_t fileLine; // Line where the section was defined
uint32_t size;
uint32_t org;
uint32_t bank;
@@ -79,4 +79,4 @@ void sect_PopSection(void);
bool sect_IsSizeKnown(struct Section const NONNULL(name));
#endif
#endif // RGBDS_SECTION_H

View File

@@ -32,28 +32,28 @@ enum SymbolType {
struct Symbol {
char name[MAXSYMLEN + 1];
enum SymbolType type;
bool isExported; /* Whether the symbol is to be exported */
bool isBuiltin; /* Whether the symbol is a built-in */
bool isExported; // Whether the symbol is to be exported
bool isBuiltin; // Whether the symbol is a built-in
struct Section *section;
struct FileStackNode *src; /* Where the symbol was defined */
uint32_t fileLine; /* Line where the symbol was defined */
struct FileStackNode *src; // Where the symbol was defined
uint32_t fileLine; // Line where the symbol was defined
bool hasCallback;
union {
/* If sym_IsNumeric */
// If sym_IsNumeric
int32_t value;
int32_t (*numCallback)(void);
/* For SYM_MACRO and SYM_EQUS; TODO: have separate fields */
// For SYM_MACRO and SYM_EQUS; TODO: have separate fields
struct {
size_t macroSize;
char *macro;
};
/* For SYM_EQUS */
// For SYM_EQUS
char const *(*strCallback)(void);
};
uint32_t ID; /* ID of the symbol in the object file (-1 if none) */
struct Symbol *next; /* Next object to output in the object file */
uint32_t ID; // ID of the symbol in the object file (-1 if none)
struct Symbol *next; // Next object to output in the object file
};
bool sym_IsPC(struct Symbol const *sym);
@@ -98,9 +98,7 @@ static inline bool sym_IsExported(struct Symbol const *sym)
return sym->isExported;
}
/*
* Get a string equate's value
*/
// Get a string equate's value
static inline char const *sym_GetStringValue(struct Symbol const *sym)
{
if (sym->hasCallback)
@@ -123,17 +121,11 @@ struct Symbol *sym_AddVar(char const *symName, int32_t value);
uint32_t sym_GetPCValue(void);
uint32_t sym_GetConstantSymValue(struct Symbol const *sym);
uint32_t sym_GetConstantValue(char const *symName);
/*
* Find a symbol by exact name, bypassing expansion checks
*/
// Find a symbol by exact name, bypassing expansion checks
struct Symbol *sym_FindExactSymbol(char const *symName);
/*
* Find a symbol by exact name; may not be scoped, produces an error if it is
*/
// Find a symbol by exact name; may not be scoped, produces an error if it is
struct Symbol *sym_FindUnscopedSymbol(char const *symName);
/*
* Find a symbol, possibly scoped, by name
*/
// Find a symbol, possibly scoped, by name
struct Symbol *sym_FindScopedSymbol(char const *symName);
struct Symbol const *sym_GetPC(void);
struct Symbol *sym_AddMacro(char const *symName, int32_t defLineNo, char *body, size_t size);
@@ -143,8 +135,8 @@ struct Symbol *sym_RedefString(char const *symName, char const *value);
void sym_Purge(char const *symName);
void sym_Init(time_t now);
/* Functions to save and restore the current symbol scope. */
// Functions to save and restore the current symbol scope.
char const *sym_GetCurrentSymbolScope(void);
void sym_SetCurrentSymbolScope(char const *newScope);
#endif /* RGBDS_SYMBOL_H */
#endif // RGBDS_SYMBOL_H

View File

@@ -18,4 +18,4 @@ char const *printChar(int c);
*/
size_t readUTF8Char(uint8_t *dest, char const *src);
#endif /* RGBDS_UTIL_H */
#endif // RGBDS_UTIL_H

View File

@@ -24,7 +24,7 @@ enum WarningID {
WARNING_ASSERT, // Assertions
WARNING_BACKWARDS_FOR, // `for` loop with backwards range
WARNING_BUILTIN_ARG, // Invalid args to builtins
WARNING_CHARMAP_REDEF, // Charmap entry re-definition
WARNING_CHARMAP_REDEF, // Charmap entry re-definition
WARNING_DIV, // Division undefined behavior
WARNING_EMPTY_DATA_DIRECTIVE, // `db`, `dw` or `dl` directive without data in ROM
WARNING_EMPTY_MACRO_ARG, // Empty macro argument
@@ -36,6 +36,7 @@ enum WarningID {
WARNING_OBSOLETE, // Obsolete things
WARNING_SHIFT, // Shifting undefined behavior
WARNING_SHIFT_AMOUNT, // Strange shift amount
WARNING_UNMAPPED_CHAR, // Character without charmap entry
WARNING_USER, // User warnings
NB_PLAIN_WARNINGS,
@@ -90,4 +91,4 @@ _Noreturn void fatalerror(char const *fmt, ...) format_(printf, 1, 2);
*/
void error(char const *fmt, ...) format_(printf, 1, 2);
#endif
#endif // WARNING_H

View File

@@ -1,4 +1,4 @@
/**
/*
* Allocator adaptor that interposes construct() calls to convert value-initialization
* (which is what you get with e.g. `vector::resize`) into default-initialization (which does not
* zero out non-class types).
@@ -36,4 +36,4 @@ public:
template<typename T>
using DefaultInitVec = std::vector<T, default_init_allocator<T>>;
#endif
#endif // DEFAULT_INIT_ALLOC_H

View File

@@ -26,4 +26,4 @@ _Noreturn void errx(char const NONNULL(fmt), ...) format_(printf, 1, 2);
}
#endif
#endif /* RGBDS_ERROR_H */
#endif // RGBDS_ERROR_H

View File

@@ -11,4 +11,4 @@
uint32_t decode(uint32_t *state, uint32_t *codep, uint8_t byte);
#endif /* EXTERN_UTF8DECODER_H */
#endif // EXTERN_UTF8DECODER_H

View File

@@ -21,7 +21,7 @@
#include "gfx/rgba.hpp"
struct Options {
uint8_t reversedWidth = 0; // -r, in pixels
uint16_t reversedWidth = 0; // -r, in tiles
bool reverse() const { return reversedWidth != 0; }
bool useColorCurve = false; // -C
@@ -71,19 +71,19 @@ struct Options {
extern Options options;
/**
/*
* Prints the error count, and exits with failure
*/
[[noreturn]] void giveUp();
/**
/*
* Prints a warning, and does not change the error count
*/
void warning(char const *fmt, ...);
/**
/*
* Prints an error, and increments the error count
*/
void error(char const *fmt, ...);
/**
/*
* Prints a fatal error, increments the error count, and gives up
*/
[[noreturn]] void fatal(char const *fmt, ...);
@@ -120,4 +120,4 @@ static constexpr auto flipTable(std::integer_sequence<T, i...>) {
// Flipping tends to happen fairly often, so take a bite out of dcache to speed it up
static constexpr auto flipTable = detail::flipTable(std::make_integer_sequence<uint16_t, 256>());
#endif /* RGBDS_GFX_MAIN_HPP */
#endif // RGBDS_GFX_MAIN_HPP

View File

@@ -21,7 +21,7 @@ class ProtoPalette;
namespace packing {
/**
/*
* Returns which palette each proto-palette maps to, and how many palettes are necessary
*/
std::tuple<DefaultInitVec<size_t>, size_t>
@@ -29,4 +29,4 @@ std::tuple<DefaultInitVec<size_t>, size_t>
}
#endif /* RGBDS_GFX_PAL_PACKING_HPP */
#endif // RGBDS_GFX_PAL_PACKING_HPP

View File

@@ -29,4 +29,4 @@ void rgb(std::vector<Palette> &palettes);
}
#endif /* RGBDS_GFX_PAL_SORTING_HPP */
#endif // RGBDS_GFX_PAL_SORTING_HPP

View File

@@ -12,4 +12,4 @@
void parseInlinePalSpec(char const * const arg);
void parseExternalPalSpec(char const *arg);
#endif /* RGBDS_GFX_PAL_SPEC_HPP */
#endif // RGBDS_GFX_PAL_SPEC_HPP

View File

@@ -11,4 +11,4 @@
void process();
#endif /* RGBDS_GFX_CONVERT_HPP */
#endif // RGBDS_GFX_CONVERT_HPP

View File

@@ -21,7 +21,7 @@ class ProtoPalette {
std::array<uint16_t, 4> _colorIndices{UINT16_MAX, UINT16_MAX, UINT16_MAX, UINT16_MAX};
public:
/**
/*
* Adds the specified color to the set
* Returns false if the set is full
*/
@@ -41,4 +41,4 @@ public:
decltype(_colorIndices)::const_iterator end() const;
};
#endif /* RGBDS_GFX_PROTO_PALETTE_HPP */
#endif // RGBDS_GFX_PROTO_PALETTE_HPP

View File

@@ -11,4 +11,4 @@
void reverse();
#endif /* RGBDS_GFX_REVERSE_HPP */
#endif // RGBDS_GFX_REVERSE_HPP

View File

@@ -20,7 +20,7 @@ struct Rgba {
constexpr Rgba(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
: red(r), green(g), blue(b), alpha(a) {}
/**
/*
* Constructs the color from a "packed" RGBA representation (0xRRGGBBAA)
*/
explicit constexpr Rgba(uint32_t rgba = 0)
@@ -35,7 +35,7 @@ struct Rgba {
(uint8_t)(cgbColor & 0x8000 ? 0x00 : 0xFF)};
}
/**
/*
* Returns this RGBA as a 32-bit number that can be printed in hex (`%08x`) to yield its CSS
* representation
*/
@@ -45,7 +45,7 @@ struct Rgba {
}
friend bool operator!=(Rgba const &lhs, Rgba const &rhs) { return lhs.toCSS() != rhs.toCSS(); }
/**
/*
* CGB colors are RGB555, so we use bit 15 to signify that the color is transparent instead
* Since the rest of the bits don't matter then, we return 0x8000 exactly.
*/
@@ -55,7 +55,7 @@ struct Rgba {
bool isTransparent() const { return alpha < transparency_threshold; }
static constexpr uint8_t opacity_threshold = 0xF0;
bool isOpaque() const { return alpha >= opacity_threshold; }
/**
/*
* Computes the equivalent CGB color, respects the color curve depending on options
*/
uint16_t cgbColor() const;
@@ -64,4 +64,4 @@ struct Rgba {
uint8_t grayIndex() const;
};
#endif /* RGBDS_GFX_RGBA_HPP */
#endif // RGBDS_GFX_RGBA_HPP

View File

@@ -6,7 +6,7 @@
* SPDX-License-Identifier: MIT
*/
/* Generic hashmap implementation (C++ templates are calling...) */
// Generic hashmap implementation (C++ templates are calling...)
#ifndef RGBDS_LINK_HASHMAP_H
#define RGBDS_LINK_HASHMAP_H
@@ -18,10 +18,10 @@
static_assert(HALF_HASH_NB_BITS * 2 == HASH_NB_BITS, "");
#define HASHMAP_NB_BUCKETS (1 << HALF_HASH_NB_BITS)
/* HashMapEntry is internal, please do not attempt to use it */
// HashMapEntry is internal, please do not attempt to use it
typedef struct HashMapEntry *HashMap[HASHMAP_NB_BUCKETS];
/**
/*
* Adds an element to a hashmap.
* @warning Adding a new element with an already-present key will not cause an
* error, this must be handled externally.
@@ -33,7 +33,7 @@ typedef struct HashMapEntry *HashMap[HASHMAP_NB_BUCKETS];
*/
void **hash_AddElement(HashMap map, char const *key, void *element);
/**
/*
* Removes an element from a hashmap.
* @param map The HashMap to remove the element from
* @param key The key to search the element with
@@ -41,7 +41,7 @@ void **hash_AddElement(HashMap map, char const *key, void *element);
*/
bool hash_RemoveElement(HashMap map, char const *key);
/**
/*
* Finds an element in a hashmap, and returns a pointer to its value field.
* @param map The map to consider the elements of
* @param key The key to search an element for
@@ -49,7 +49,7 @@ bool hash_RemoveElement(HashMap map, char const *key);
*/
void **hash_GetNode(HashMap const map, char const *key);
/**
/*
* Finds an element in a hashmap.
* @param map The map to consider the elements of
* @param key The key to search an element for
@@ -58,7 +58,7 @@ void **hash_GetNode(HashMap const map, char const *key);
*/
void *hash_GetElement(HashMap const map, char const *key);
/**
/*
* Executes a function on each element in a hashmap.
* @param map The map to consider the elements of
* @param func The function to run. The first argument will be the element,
@@ -67,11 +67,11 @@ void *hash_GetElement(HashMap const map, char const *key);
*/
void hash_ForEach(HashMap const map, void (*func)(void *, void *), void *arg);
/**
/*
* Cleanly empties a hashmap from its contents.
* This does not `free` the data structure itself!
* @param map The map to empty
*/
void hash_EmptyMap(HashMap map);
#endif /* RGBDS_LINK_HASHMAP_H */
#endif // RGBDS_LINK_HASHMAP_H

View File

@@ -93,4 +93,4 @@
// (Having two instances of `arr` is OK because the contents of `sizeof` are not evaluated.)
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof *(arr))
#endif /* HELPERS_H */
#endif // HELPERS_H

View File

@@ -79,12 +79,10 @@ using Holder = std::conditional_t<std::is_lvalue_reference_v<T>, T,
std::remove_cv_t<std::remove_reference_t<T>>>;
}
/**
* Does the same number of iterations as the first container's iterator!
*/
// Does the same number of iterations as the first container's iterator!
template<typename... Containers>
static constexpr auto zip(Containers &&...cs) {
return detail::ZipContainer<detail::Holder<Containers>...>(std::forward<Containers>(cs)...);
}
#endif /* RGBDS_ITERTOOLS_HPP */
#endif // RGBDS_ITERTOOLS_HPP

View File

@@ -6,7 +6,7 @@
* SPDX-License-Identifier: MIT
*/
/* Assigning all sections a place */
// Assigning all sections a place
#ifndef RGBDS_LINK_ASSIGN_H
#define RGBDS_LINK_ASSIGN_H
@@ -14,14 +14,10 @@
extern uint64_t nbSectionsToAssign;
/**
* Assigns all sections a slice of the address space
*/
// Assigns all sections a slice of the address space
void assign_AssignSections(void);
/**
* `free`s all assignment memory that was allocated.
*/
// `free`s all assignment memory that was allocated
void assign_Cleanup(void);
#endif /* RGBDS_LINK_ASSIGN_H */
#endif // RGBDS_LINK_ASSIGN_H

View File

@@ -6,7 +6,7 @@
* SPDX-License-Identifier: MIT
*/
/* Declarations that all modules use, as well as `main` and related */
// Declarations that all modules use, as well as `main` and related
#ifndef RGBDS_LINK_MAIN_H
#define RGBDS_LINK_MAIN_H
@@ -16,10 +16,11 @@
#include "helpers.h"
/* Variables related to CLI options */
// Variables related to CLI options
extern bool isDmgMode;
extern char *linkerScriptName;
extern char const *mapFileName;
extern bool noSymInMap;
extern char const *symFileName;
extern char const *overlayFileName;
extern char const *outputFileName;
@@ -34,7 +35,7 @@ extern bool disablePadding;
struct FileStackNode {
struct FileStackNode *parent;
/* Line at which the parent context was exited; meaningless for the root level */
// Line at which the parent context was exited; meaningless for the root level
uint32_t lineNo;
enum {
@@ -43,21 +44,21 @@ struct FileStackNode {
NODE_MACRO,
} type;
union {
char *name; /* NODE_FILE, NODE_MACRO */
struct { /* NODE_REPT */
char *name; // NODE_FILE, NODE_MACRO
struct { // NODE_REPT
uint32_t reptDepth;
uint32_t *iters;
};
};
};
/* Helper macro for printing verbose-mode messages */
// Helper macro for printing verbose-mode messages
#define verbosePrint(...) do { \
if (beVerbose) \
fprintf(stderr, __VA_ARGS__); \
} while (0)
/**
/*
* Dump a file stack to stderr
* @param node The leaf node to dump the context of
*/
@@ -72,7 +73,7 @@ void error(struct FileStackNode const *where, uint32_t lineNo,
_Noreturn void fatal(struct FileStackNode const *where, uint32_t lineNo,
char const *fmt, ...) format_(printf, 3, 4);
/**
/*
* Opens a file if specified, and aborts on error.
* @param fileName The name of the file to open; if NULL, no file will be opened
* @param mode The mode to open the file with
@@ -86,4 +87,4 @@ FILE *openFile(char const *fileName, char const *mode);
fclose(tmp); \
} while (0)
#endif /* RGBDS_LINK_MAIN_H */
#endif // RGBDS_LINK_MAIN_H

View File

@@ -6,37 +6,37 @@
* SPDX-License-Identifier: MIT
*/
/* Declarations related to processing of object (.o) files */
// Declarations related to processing of object (.o) files
#ifndef RGBDS_LINK_OBJECT_H
#define RGBDS_LINK_OBJECT_H
/**
/*
* Read an object (.o) file, and add its info to the data structures.
* @param fileName A path to the object file to be read
* @param i The ID of the file
*/
void obj_ReadFile(char const *fileName, unsigned int i);
/**
/*
* Perform validation on the object files' contents
*/
void obj_DoSanityChecks(void);
/**
/*
* Evaluate all assertions
*/
void obj_CheckAssertions(void);
/**
/*
* Sets up object file reading
* @param nbFiles The number of object files that will be read
*/
void obj_Setup(unsigned int nbFiles);
/**
/*
* `free`s all object memory that was allocated.
*/
void obj_Cleanup(void);
#endif /* RGBDS_LINK_OBJECT_H */
#endif // RGBDS_LINK_OBJECT_H

View File

@@ -6,7 +6,7 @@
* SPDX-License-Identifier: MIT
*/
/* Outputting the result of linking */
// Outputting the result of linking
#ifndef RGBDS_LINK_OUTPUT_H
#define RGBDS_LINK_OUTPUT_H
@@ -14,22 +14,22 @@
#include "link/section.h"
/**
/*
* Registers a section for output.
* @param section The section to add
*/
void out_AddSection(struct Section const *section);
/**
/*
* Finds an assigned section overlapping another one.
* @param section The section that is being overlapped
* @return A section overlapping it
*/
struct Section const *out_OverlappingSection(struct Section const *section);
/**
/*
* Writes all output (bin, sym, map) files.
*/
void out_WriteFiles(void);
#endif /* RGBDS_LINK_OUTPUT_H */
#endif // RGBDS_LINK_OUTPUT_H

View File

@@ -6,7 +6,7 @@
* SPDX-License-Identifier: MIT
*/
/* Applying patches to SECTIONs */
// Applying patches to SECTIONs
#ifndef RGBDS_LINK_PATCH_H
#define RGBDS_LINK_PATCH_H
@@ -27,15 +27,15 @@ struct Assertion {
struct Assertion *next;
};
/**
/*
* Checks all assertions
* @return true if assertion failed
*/
void patch_CheckAssertions(struct Assertion *assertion);
/**
/*
* Applies all SECTIONs' patches to them
*/
void patch_ApplyPatches(void);
#endif /* RGBDS_LINK_PATCH_H */
#endif // RGBDS_LINK_PATCH_H

View File

@@ -6,31 +6,33 @@
* SPDX-License-Identifier: MIT
*/
/* Parsing a linker script */
// Parsing a linker script
#ifndef RGBDS_LINK_SCRIPT_H
#define RGBDS_LINK_SCRIPT_H
#include <stdint.h>
#include "linkdefs.h"
extern FILE * linkerScript;
struct SectionPlacement {
struct Section *section;
enum SectionType type;
uint16_t org;
uint32_t bank;
};
extern uint64_t script_lineNo;
/**
/*
* Parses the linker script to return the next section constraint
* @return A pointer to a struct, or NULL on EOF. The pointer shouldn't be freed
*/
struct SectionPlacement *script_NextSection(void);
/**
/*
* `free`s all assignment memory that was allocated.
*/
void script_Cleanup(void);
#endif /* RGBDS_LINK_SCRIPT_H */
#endif // RGBDS_LINK_SCRIPT_H

19
include/link/sdas_obj.h Normal file
View File

@@ -0,0 +1,19 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2022, Eldred Habert and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
// Assigning all sections a place
#ifndef RGBDS_LINK_SDAS_OBJ_H
#define RGBDS_LINK_SDAS_OBJ_H
#include <stdio.h>
struct FileStackNode;
void sdobj_ReadFile(struct FileStackNode const *fileName, FILE *file);
#endif // RGBDS_LINK_SDAS_OBJ_H

View File

@@ -6,11 +6,11 @@
* SPDX-License-Identifier: MIT
*/
/* Declarations manipulating symbols */
// Declarations manipulating symbols
#ifndef RGBDS_LINK_SECTION_H
#define RGBDS_LINK_SECTION_H
/* GUIDELINE: external code MUST NOT BE AWARE of the data structure used!! */
// GUIDELINE: external code MUST NOT BE AWARE of the data structure used!!
#include <stdint.h>
#include <stdbool.h>
@@ -41,27 +41,29 @@ struct Patch {
};
struct Section {
/* Info contained in the object files */
// Info contained in the object files
char *name;
uint16_t size;
uint16_t offset;
enum SectionType type;
enum SectionModifier modifier;
bool isAddressFixed;
// This `struct`'s address in ROM.
// Importantly for fragments, this does not include `offset`!
uint16_t org;
bool isBankFixed;
uint32_t bank;
bool isAlignFixed;
uint16_t alignMask;
uint16_t alignOfs;
uint8_t *data; /* Array of size `size`*/
uint8_t *data; // Array of size `size`
uint32_t nbPatches;
struct Patch *patches;
/* Extra info computed during linking */
// Extra info computed during linking
struct Symbol **fileSymbols;
uint32_t nbSymbols;
struct Symbol const **symbols;
struct Section *nextu; /* The next "component" of this unionized sect */
struct Symbol **symbols;
struct Section *nextu; // The next "component" of this unionized sect
};
/*
@@ -74,27 +76,27 @@ struct Section {
*/
void sect_ForEach(void (*callback)(struct Section *, void *), void *arg);
/**
/*
* Registers a section to be processed.
* @param section The section to register.
*/
void sect_AddSection(struct Section *section);
/**
/*
* Finds a section by its name.
* @param name The name of the section to look for
* @return A pointer to the section, or NULL if it wasn't found
*/
struct Section *sect_GetSection(char const *name);
/**
/*
* `free`s all section memory that was allocated.
*/
void sect_CleanupSections(void);
/**
/*
* Checks if all sections meet reasonable criteria, such as max size
*/
void sect_DoSanityChecks(void);
#endif /* RGBDS_LINK_SECTION_H */
#endif // RGBDS_LINK_SECTION_H

View File

@@ -6,11 +6,11 @@
* SPDX-License-Identifier: MIT
*/
/* Declarations manipulating symbols */
// Declarations manipulating symbols
#ifndef RGBDS_LINK_SYMBOL_H
#define RGBDS_LINK_SYMBOL_H
/* GUIDELINE: external code MUST NOT BE AWARE of the data structure used!! */
// GUIDELINE: external code MUST NOT BE AWARE of the data structure used!!
#include <stdint.h>
@@ -19,7 +19,7 @@
struct FileStackNode;
struct Symbol {
/* Info contained in the object files */
// Info contained in the object files
char *name;
enum ExportLevel type;
char const *objFileName;
@@ -27,10 +27,11 @@ struct Symbol {
int32_t lineNo;
int32_t sectionID;
union {
// Both types must be identical
int32_t offset;
int32_t value;
};
/* Extra info computed during linking */
// Extra info computed during linking
struct Section *section;
};
@@ -46,16 +47,16 @@ void sym_ForEach(void (*callback)(struct Symbol *, void *), void *arg);
void sym_AddSymbol(struct Symbol *symbol);
/**
/*
* Finds a symbol in all the defined symbols.
* @param name The name of the symbol to look for
* @return A pointer to the symbol, or NULL if not found.
*/
struct Symbol *sym_GetSymbol(char const *name);
/**
/*
* `free`s all symbol memory that was allocated.
*/
void sym_CleanupSymbols(void);
#endif /* RGBDS_LINK_SYMBOL_H */
#endif // RGBDS_LINK_SYMBOL_H

View File

@@ -9,11 +9,11 @@
#ifndef RGBDS_LINKDEFS_H
#define RGBDS_LINKDEFS_H
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#define RGBDS_OBJECT_VERSION_STRING "RGB%1u"
#define RGBDS_OBJECT_VERSION_NUMBER 9U
#define RGBDS_OBJECT_VERSION_STRING "RGB9"
#define RGBDS_OBJECT_REV 9U
enum AssertionType {
@@ -74,9 +74,50 @@ enum SectionType {
SECTTYPE_SRAM,
SECTTYPE_OAM,
// In RGBLINK, this is used for "indeterminate" sections; this is primarily for SDCC
// areas, which do not carry any section type info and must be told from the linker script
SECTTYPE_INVALID
};
// Nont-`const` members may be patched in RGBLINK depending on CLI flags
extern struct SectionTypeInfo {
char const *const name;
uint16_t const startAddr;
uint16_t size;
uint32_t const firstBank;
uint32_t lastBank;
} sectionTypeInfo[SECTTYPE_INVALID];
/*
* Tells whether a section has data in its object file definition,
* depending on type.
* @param type The section's type
* @return `true` if the section's definition includes data
*/
static inline bool sect_HasData(enum SectionType type)
{
assert(type != SECTTYPE_INVALID);
return type == SECTTYPE_ROM0 || type == SECTTYPE_ROMX;
}
/*
* Computes a memory region's end address (last byte), eg. 0x7FFF
* @return The address of the last byte in that memory region
*/
static inline uint16_t endaddr(enum SectionType type)
{
return sectionTypeInfo[type].startAddr + sectionTypeInfo[type].size - 1;
}
/*
* Computes a memory region's number of banks
* @return The number of banks, 1 for regions without banking
*/
static inline uint32_t nbbanks(enum SectionType type)
{
return sectionTypeInfo[type].lastBank - sectionTypeInfo[type].firstBank + 1;
}
enum SectionModifier {
SECTION_NORMAL,
SECTION_UNION,
@@ -85,17 +126,6 @@ enum SectionModifier {
extern char const * const sectionModNames[];
/**
* Tells whether a section has data in its object file definition,
* depending on type.
* @param type The section's type
* @return `true` if the section's definition includes data
*/
static inline bool sect_HasData(enum SectionType type)
{
return type == SECTTYPE_ROM0 || type == SECTTYPE_ROMX;
}
enum ExportLevel {
SYMTYPE_LOCAL,
SYMTYPE_IMPORT,
@@ -111,45 +141,4 @@ enum PatchType {
PATCHTYPE_INVALID
};
#define BANK_MIN_ROM0 0
#define BANK_MAX_ROM0 0
#define BANK_MIN_ROMX 1
#define BANK_MAX_ROMX 511
#define BANK_MIN_VRAM 0
#define BANK_MAX_VRAM 1
#define BANK_MIN_SRAM 0
#define BANK_MAX_SRAM 15
#define BANK_MIN_WRAM0 0
#define BANK_MAX_WRAM0 0
#define BANK_MIN_WRAMX 1
#define BANK_MAX_WRAMX 7
#define BANK_MIN_OAM 0
#define BANK_MAX_OAM 0
#define BANK_MIN_HRAM 0
#define BANK_MAX_HRAM 0
extern uint16_t startaddr[];
extern uint16_t maxsize[];
extern uint32_t bankranges[][2];
/**
* Computes a memory region's end address (last byte), eg. 0x7FFF
* @return The address of the last byte in that memory region
*/
static inline uint16_t endaddr(enum SectionType type)
{
return startaddr[type] + maxsize[type] - 1;
}
/**
* Computes a memory region's number of banks
* @return The number of banks, 1 for regions without banking
*/
static inline uint32_t nbbanks(enum SectionType type)
{
return bankranges[type][1] - bankranges[type][0] + 1;
}
extern char const * const typeNames[SECTTYPE_INVALID];
#endif /* RGBDS_LINKDEFS_H */
#endif // RGBDS_LINKDEFS_H

View File

@@ -18,4 +18,4 @@ int32_t op_shift_left(int32_t value, int32_t amount);
int32_t op_shift_right(int32_t value, int32_t amount);
int32_t op_shift_right_unsigned(int32_t value, int32_t amount);
#endif /* RGBDS_OP_MATH_H */
#endif // RGBDS_OP_MATH_H

View File

@@ -6,7 +6,7 @@
* SPDX-License-Identifier: MIT
*/
/* platform-specific hacks */
// platform-specific hacks
#ifndef RGBDS_PLATFORM_H
#define RGBDS_PLATFORM_H
@@ -20,20 +20,20 @@
# include <strings.h>
#endif
/* MSVC has deprecated strdup in favor of _strdup */
// MSVC has deprecated strdup in favor of _strdup
#ifdef _MSC_VER
# define strdup _strdup
#endif
/* MSVC prefixes the names of S_* macros with underscores,
and doesn't define any S_IS* macros. Define them ourselves */
// MSVC prefixes the names of S_* macros with underscores,
// and doesn't define any S_IS* macros; define them ourselves
#ifdef _MSC_VER
# define S_IFMT _S_IFMT
# define S_IFDIR _S_IFDIR
# define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
#endif
/* MSVC doesn't use POSIX types or defines for `read` */
// MSVC doesn't use POSIX types or defines for `read`
#ifdef _MSC_VER
# include <io.h>
# define STDIN_FILENO 0
@@ -46,7 +46,7 @@
# include <unistd.h>
#endif
/* MSVC doesn't support `[static N]` for array arguments from C99 or C11 */
// MSVC doesn't support `[static N]` for array arguments from C99 or C11
#ifdef _MSC_VER
# define MIN_NB_ELMS(N)
# define ARR_QUALS(...)
@@ -75,4 +75,4 @@
# define setmode(fd, mode) ((void)0)
#endif
#endif /* RGBDS_PLATFORM_H */
#endif // RGBDS_PLATFORM_H

View File

@@ -16,7 +16,7 @@ extern "C" {
#define PACKAGE_VERSION_MAJOR 0
#define PACKAGE_VERSION_MINOR 6
#define PACKAGE_VERSION_PATCH 0
#define PACKAGE_VERSION_RC 1
#define PACKAGE_VERSION_RC 2
char const *get_package_version_string(void);
@@ -24,4 +24,4 @@ char const *get_package_version_string(void);
}
#endif
#endif /* EXTERN_VERSION_H */
#endif // EXTERN_VERSION_H

View File

@@ -171,8 +171,8 @@ and
.It Sx JP HL
.It Sx JP n16
.It Sx JP cc,n16
.It Sx JR e8
.It Sx JR cc,e8
.It Sx JR n16
.It Sx JR cc,n16
.It Sx RET cc
.It Sx RET
.It Sx RETI
@@ -754,22 +754,34 @@ Cycles: 1
Bytes: 1
.Pp
Flags: None affected.
.Ss JR e8
Relative Jump by adding
.Ar e8
to the address of the instruction following the
.Sy JR .
To clarify, an operand of 0 is equivalent to no jumping.
.Ss JR n16
Relative Jump to address
.Ar n16 .
The address is encoded as a signed 8-bit offset from the address immediately following the
.Ic JR
instruction, so the target address
.Ar n16
must be between
.Sy -128
and
.Sy 127
bytes away.
For example:
.Bd -literal -offset indent
JR Label ; no-op; encoded offset of 0
Label:
JR Label ; infinite loop; encoded offset of -2
.Ed
.Pp
Cycles: 3
.Pp
Bytes: 2
.Pp
Flags: None affected.
.Ss JR cc,e8
Relative Jump by adding
.Ar e8
to the current address if condition
.Ss JR cc,n16
Relative Jump to address
.Ar n16
if condition
.Ar cc
is met.
.Pp

View File

@@ -13,7 +13,7 @@
.Nd Game Boy assembler
.Sh SYNOPSIS
.Nm
.Op Fl EhLVvw
.Op Fl EHhLlVvw
.Op Fl b Ar chars
.Op Fl D Ar name Ns Op = Ns Ar value
.Op Fl g Ar chars
@@ -25,6 +25,7 @@
.Op Fl MQ Ar target_file
.Op Fl o Ar out_file
.Op Fl p Ar pad_value
.Op Fl Q Ar fix_precision
.Op Fl r Ar recursion_depth
.Op Fl W Ar warning
.Ar
@@ -66,25 +67,43 @@ Export all labels, including unreferenced and local labels.
.It Fl g Ar chars , Fl Fl gfx-chars Ar chars
Change the four characters used for gfx constants.
The defaults are 0123.
.It Fl h , Fl Fl halt-without-nop
.It Fl H , Fl Fl nop-after-halt
By default,
.Nm
inserts a
.Ic nop
instruction immediately after any
.Ic halt
instruction.
instruction,
but this has been deprecated and prints a warning message the first time it occurs.
The
.Fl h
option disables this behavior.
.Fl H
option opts into this insertion,
so no warning will be printed.
.It Fl h , Fl Fl halt-without-nop
Disables inserting a
.Ic nop
instruction immediately after any
.Ic halt
instruction.
.It Fl i Ar path , Fl Fl include Ar path
Add an include path.
.It Fl L , Fl Fl preserve-ld
Disable the optimization that turns loads of the form
By default,
.Nm
optimizes loads of the form
.Ic LD [$FF00+n8],A
into the opcode
.Ic LDH [$FF00+n8],A
in order to have full control of the result in the final ROM.
.Ic LDH [$FF00+n8],A ,
but this has been deprecated and prints a warning message the first time it occurs.
The
.Fl L
option disables this optimization.
.It Fl l , Fl Fl auto-ldh
Optimize loads of the form
.Ic LD [$FF00+n8],A
into the opcode
.Ic LDH [$FF00+n8],A .
.It Fl M Ar depend_file , Fl Fl dependfile Ar depend_file
Print
.Xr make 1
@@ -130,8 +149,16 @@ Write an object file to the given filename.
.It Fl p Ar pad_value , Fl Fl pad-value Ar pad_value
When padding an image, pad with this value.
The default is 0x00.
.It Fl Q Ar fix_precision , Fl Fl q-precision Ar fix_precision
Use this as the precision of fixed-point numbers after the decimal point, unless they specify their own precision.
The default is 16, so fixed-point numbers are Q16.16 (since they are 32-bit integers).
The argument may start with a
.Ql \&.
to match the Q notation, for example,
.Ql Fl Q Ar .16 .
.It Fl r Ar recursion_depth , Fl Fl recursion-depth Ar recursion_depth
Specifies the recursion depth at which RGBASM will assume being in an infinite loop.
Specifies the recursion depth past which RGBASM will assume being in an infinite loop.
The default is 64.
.It Fl V , Fl Fl version
Print the version of the program and exit.
.It Fl v , Fl Fl verbose
@@ -274,6 +301,12 @@ warns when an N-bit value's absolute value is 2**N or greater.
or just
.Fl Wtruncation
also warns when an N-bit value is less than -2**(N-1), which will not fit in two's complement encoding.
.It Fl Wunmapped-char
Warn when a character goes through charmap conversion but has no defined mapping.
This warning is always disabled if the active charmap is empty, and/or is the default charmap
.Sq main .
This warning is enabled by
.Fl Wall .
.It Fl Wno-user
Warn when the
.Ic WARN

View File

@@ -208,13 +208,14 @@ section.
The instructions in the macro-language generally require constant expressions.
.Ss Numeric formats
There are a number of numeric formats.
.Bl -column -offset indent "Fixed point (Q16.16)" "Prefix"
.Bl -column -offset indent "Precise fixed-point" "Prefix"
.It Sy Format type Ta Sy Prefix Ta Sy Accepted characters
.It Hexadecimal Ta $ Ta 0123456789ABCDEF
.It Decimal Ta none Ta 0123456789
.It Octal Ta & Ta 01234567
.It Binary Ta % Ta 01
.It Fixed point (Q16.16) Ta none Ta 01234.56789
.It Fixed-point Ta none Ta 01234.56789
.It Precise fixed-point Ta none Ta 12.34q8
.It Character constant Ta none Ta \(dqABYZ\(dq
.It Gameboy graphics Ta \` Ta 0123
.El
@@ -301,9 +302,19 @@ and
.Ic \&!
returns 1 if the operand was 0, and 0 otherwise.
.Ss Fixed-point expressions
Fixed-point numbers are basically normal (32-bit) integers, which count 65536ths instead of entire units, offering better precision than integers but limiting the range of values.
The upper 16 bits are used for the integer part and the lower 16 bits are used for the fraction (65536ths).
Since they are still akin to integers, you can use them in normal integer expressions, and some integer operators like
Fixed-point numbers are basically normal (32-bit) integers, which count fractions instead of whole numbers.
They offer better precision than integers but limit the range of values.
By default, the upper 16 bits are used for the integer part and the lower 16 bits are used for the fraction (65536ths).
The default number of fractional bits can be changed with the
.Fl Q
command-line option.
You can also specify a precise fixed-point value by appending a
.Dq q
to it followed by the number of fractional bits, such as
.Ql 12.34q8 .
.Pp
Since fixed-point values are still just integers, you can use them in normal integer expressions.
Some integer operators like
.Sq +
and
.Sq -
@@ -317,8 +328,9 @@ delim $$
.EN
.Bl -column -offset indent "ATAN2(x, y)"
.It Sy Name Ta Sy Operation
.It Fn DIV x y Ta $x \[di] y$
.It Fn MUL x y Ta $x \[mu] y$
.It Fn DIV x y Ta Fixed-point division $( x \[di] y ) \[mu] ( 2 ^ precision )$
.It Fn MUL x y Ta Fixed-point multiplication $( x \[mu] y ) \[di] ( 2 ^ precision )$
.It Fn FMOD x y Ta Fixed-point modulo $( x % y ) \[di] ( 2 ^ precision )$
.It Fn POW x y Ta $x$ to the $y$ power
.It Fn LOG x y Ta Logarithm of $x$ to the base $y$
.It Fn ROUND x Ta Round $x$ to the nearest integer
@@ -945,9 +957,9 @@ assuming the section ends up at
.Ad $80C0 :
.Bd -literal -offset indent
SECTION "Player tiles", VRAM
PlayerTiles:
vPlayerTiles:
ds 6 * 16
.end
\&.end
.Ed
.Pp
A label's location (and thus value) is usually not determined until the linking stage, so labels usually cannot be used as constants.
@@ -1213,14 +1225,16 @@ The example above defines
.Ql MyMacro
as a new macro.
String constants are not expanded within the name of the macro.
You may use the older syntax
.Pp
(Using the
.Em deprecated
older syntax
.Ql MyMacro: MACRO
instead of
.Ql MACRO MyMacro ,
with a single colon
.Ql \&:
following the macro's name.
With the older syntax, string constants may be expanded for the name.
following the macro's name, string constants may be expanded for the name.)
.Pp
Macros can't be exported or imported.
.Pp
@@ -1324,7 +1338,7 @@ DEF AOLer EQUS "Me too"
String constants are not expanded within the symbol names.
.Ss Predeclared symbols
The following symbols are defined by the assembler:
.Bl -column -offset indent "EQUS" "__ISO_8601_LOCAL__"
.Bl -column -offset indent "__ISO_8601_LOCAL__" "EQUS"
.It Sy Name Ta Sy Type Ta Sy Contents
.It Dv @ Ta Ic EQU Ta PC value (essentially, the current memory address)
.It Dv _RS Ta Ic = Ta _RS Counter
@@ -1804,11 +1818,29 @@ The
value will be updated by
.Ar step
until it reaches or exceeds
.Ar stop .
.Ar stop ,
i.e. it covers the half-open range from
.Ar start
(inclusive) to
.Ar stop
(exclusive).
The variable
.Ar V
will be assigned this value at the beginning of each new iteration; any changes made to it within the
.Ic FOR
loop's body will be overwritten.
So the symbol
.Ar V
need not be already defined before any iterations of the
.Ic FOR
loop, but it must be a variable
.Pq Sx Variables
if so.
For example:
.Bd -literal -offset indent
FOR V, 4, 25, 5
PRINT "{d:V} "
DEF V *= 2
ENDR
PRINTLN "done {d:V}"
.Ed
@@ -2013,17 +2045,15 @@ POPO
The options that
.Ic OPT
can modify are currently:
.Cm b , g , p , r , h , L ,
.Cm b , g , p , Q , r , h , L ,
and
.Cm W .
The Boolean flag options
.Cm h
.Cm H , h , L ,
and
.Cm L
can be negated as
.Ql OPT !h
and
.Ql OPT !L
.Cm l
can be negated like
.Ql OPT !H
to act like omitting them from the command-line.
.Pp
.Ic POPO

View File

@@ -16,251 +16,381 @@ This is the description of the object files used by
.Xr rgbasm 1
and
.Xr rgblink 1 .
.Em Please note that the specifications may change .
This toolchain is in development and new features may require adding more information to the current format, or modifying some fields, which would break compatibility with older versions.
.Em Please note that the specification is not stable yet.
RGBDS is still in active development, and some new features require adding more information to the object file, or modifying some fields, both of which break compatibility with older versions.
.Sh FILE STRUCTURE
The following types are used:
.Pp
.Ar LONG
.Cm LONG
is a 32-bit integer stored in little-endian format.
.Ar BYTE
.Cm BYTE
is an 8-bit integer.
.Ar STRING
.Cm STRING
is a 0-terminated string of
.Ar BYTE .
.Bd -literal
; Header
BYTE ID[4] ; "RGB9"
LONG RevisionNumber ; The format's revision number this file uses.
LONG NumberOfSymbols ; The number of symbols used in this file.
LONG NumberOfSections ; The number of sections used in this file.
; File info
LONG NumberOfNodes ; The number of nodes contained in this file.
REPT NumberOfNodes ; IMPORTANT NOTE: the nodes are actually written in
; **reverse** order, meaning the node with ID 0 is
; the last one in the file!
LONG ParentID ; ID of the parent node, -1 means this is the root.
LONG ParentLineNo ; Line at which the parent context was exited.
; Meaningless on the root node.
BYTE Type ; 0 = REPT node
; 1 = File node
; 2 = Macro node
IF Type != 0 ; If the node is not a REPT...
STRING Name ; The node's name: either a file name, or macro name
; prefixed by its definition file name.
ELSE ; If the node is a REPT, it also contains the iter
; counts of all the parent REPTs.
LONG Depth ; Size of the array below.
LONG Iter[Depth] ; The number of REPT iterations by increasing depth.
ENDC
ENDR
; Symbols
REPT NumberOfSymbols ; Number of symbols defined in this object file.
STRING Name ; The name of this symbol. Local symbols are stored
; as "Scope.Symbol".
BYTE Type ; 0 = LOCAL symbol only used in this file.
; 1 = IMPORT this symbol from elsewhere
; 2 = EXPORT this symbol to other objects.
IF (Type & 0x7F) != 1 ; If symbol is defined in this object file.
LONG SourceFile ; File where the symbol is defined.
LONG LineNum ; Line number in the file where the symbol is defined.
LONG SectionID ; The section number (of this object file) in which
; this symbol is defined. If it doesn't belong to any
; specific section (like a constant), this field has
; the value -1.
LONG Value ; The symbols value. It's the offset into that
; symbol's section.
ENDC
ENDR
; Sections
REPT NumberOfSections
STRING Name ; Name of the section
LONG Size ; Size in bytes of this section
BYTE Type ; 0 = WRAM0
; 1 = VRAM
; 2 = ROMX
; 3 = ROM0
; 4 = HRAM
; 5 = WRAMX
; 6 = SRAM
; 7 = OAM
; Bits 7 and 6 are independent from the above value:
; Bit 7 encodes whether the section is unionized
; Bit 6 encodes whether the section is a fragment
; Bits 6 and 7 may not be both set at the same time!
LONG Org ; Address to fix this section at. -1 if the linker should
; decide (floating address).
LONG Bank ; Bank to load this section into. -1 if the linker should
; decide (floating bank). This field is only valid for ROMX,
; VRAM, WRAMX and SRAM sections.
BYTE Align ; Alignment of this section, as N bits. 0 when not specified.
LONG Ofs ; Offset relative to the alignment specified above.
; Must be below 1 << Align.
IF (Type == ROMX) || (Type == ROM0) ; Sections that can contain data.
BYTE Data[Size] ; Raw data of the section.
LONG NumberOfPatches ; Number of patches to apply.
REPT NumberOfPatches
LONG SourceFile ; ID of the source file node (for printing
; error messages).
LONG LineNo ; Line at which the patch was created.
LONG Offset ; Offset into the section where patch should
; be applied (in bytes).
LONG PCSectionID ; Index within the file of the section in which
; PC is located.
; This is usually the same section that the
; patch should be applied into, except e.g.
; with LOAD blocks.
LONG PCOffset ; PC's offset into the above section.
; Used because the section may be floating, so
; PC's value is not known to RGBASM.
BYTE Type ; 0 = BYTE patch.
; 1 = little endian WORD patch.
; 2 = little endian LONG patch.
; 3 = JR offset value BYTE patch.
LONG RPNSize ; Size of the buffer with the RPN.
; expression.
BYTE RPN[RPNSize] ; RPN expression. Definition below.
ENDR
ENDC
ENDR
; Assertions
LONG NumberOfAssertions
REPT NumberOfAssertions
LONG SourceFile ; ID of the source file node (for printing the failure).
LONG LineNo ; Line at which the assertion was created.
LONG Offset ; Offset into the section where the assertion is located.
LONG SectionID ; Index within the file of the section in which PC is
; located, or -1 if defined outside a section.
LONG PCOffset ; PC's offset into the above section.
; Used because the section may be floating, so PC's value
; is not known to RGBASM.
BYTE Type ; 0 = Prints the message but allows linking to continue
; 1 = Prints the message and evaluates other assertions,
; but linking fails afterwards
; 2 = Prints the message and immediately fails linking
LONG RPNSize ; Size of the RPN expression's buffer.
BYTE RPN[RPNSize] ; RPN expression, same as patches. Assert fails if == 0.
STRING Message ; A message displayed when the assert fails. If set to
; the empty string, a generic message is printed instead.
ENDR
.Ed
.Ss RPN DATA
Expressions in the object file are stored as RPN.
This is an expression of the form
.Dq 2 5 + .
This will first push the value
.Do 2 Dc to the stack, then
.Cm BYTE .
Brackets after a type
.Pq e.g. Cm LONG Ns Bq Ar n
indicate
.Ar n
consecutive elements
.Pq here, Cm LONG Ns s .
All items are contiguous, with no padding anywhere\(emthis also means that they may not be aligned in the file!
.Pp
.Cm REPT Ar n
indicates that the fields between the
.Cm REPT
and corresponding
.Cm ENDR
are repeated
.Ar n
times.
.Pp
All IDs refer to objects within the file; for example, symbol ID $0001 refers to the second symbol defined in
.Em this
object file's
.Sx Symbols
array.
The only exception is the
.Sx Source file info
nodes, whose IDs are backwards, i.e. source node ID $0000 refers to the
.Em last
node in the array, not the first one.
References to other object files are made by imports (symbols), by name (sections), etc.\(embut never by ID.
.Ss Header
.Bl -tag -width Ds -compact
.It Cm BYTE Ar Magic[4]
"RGB9"
.It Cm LONG Ar RevisionNumber
The format's revision number this file uses.
.Pq This is always in the same place in all revisions.
.It Cm LONG Ar NumberOfSymbols
How many symbols are defined in this object file.
.It Cm LONG Ar NumberOfSections
How many sections are defined in this object file.
.El
.Ss Source file info
.Bl -tag -width Ds -compact
.It Cm LONG Ar NumberOfNodes
The number of source context nodes contained in this file.
.It Cm REPT Ar NumberOfNodes
.Bl -tag -width Ds -compact
.It Cm LONG Ar ParentID
ID of the parent node, -1 meaning that this is the root node.
.Pp
.Sy Important :
the nodes are actually written in
.Sy reverse
order, meaning the node with ID 0 is the last one in the list!
.It Cm LONG Ar ParentLineNo
Line at which the parent node's context was exited; meaningless for the root node.
.It Cm BYTE Ar Type
.Bl -column "Value" -compact
.It Sy Value Ta Sy Meaning
.It 0 Ta REPT node
.It 1 Ta File node
.It 2 Ta Macro node
.El
.It Cm IF Ar Type No \(!= 0
If the node is not a REPT node...
.Pp
.Bl -tag -width Ds -compact
.It Cm STRING Ar Name
The node's name: either a file name, or the macro's name prefixes by its definition's file name
.Pq e.g. Ql src/includes/defines.asm::error .
.El
.It Cm ELSE
If the node is a REPT, it also contains the iteration counter of all parent REPTs.
.Pp
.Bl -tag -width Ds -compact
.It Cm LONG Ar Depth
.It Cm LONG Ar Iter Ns Bq Ar Depth
The number of REPT iterations, by increasing depth.
.El
.It Cm ENDC
.El
.It Cm ENDR
.El
.Ss Symbols
.Bl -tag -width Ds -compact
.It Cm REPT Ar NumberOfSymbols
.Bl -tag -width Ds -compact
.It Cm STRING Ar Name
This symbol's name.
Local symbols are stored as their full name
.Pq Ql Scope.symbol .
.It Cm BYTE Ar Type
.Bl -column "Value" -compact
.It Sy Value Ta Sy Meaning
.It 0 Ta Sy Local No symbol only used in this file.
.It 1 Ta Sy Import No of an exported symbol (by name) from another object file.
.It 2 Ta Sy Exported No symbol visible from other object files.
.El
.It Cm IF Ar Type No \(!= 1
If the symbol is defined in this object file...
.Pp
.Bl -tag -width Ds -compact
.It Cm LONG Ar NodeID
Context in which the symbol was defined.
.It Cm LONG Ar LineNo
Line number in the context at which the symbol was defined.
.It Cm LONG Ar SectionID
The ID of the section in which the symbol is defined.
If the symbol doesn't belong to any specific section (i.e. it's a constant), this field contains -1.
.It Cm LONG Ar Value
The symbol's value.
If the symbol belongs to a section, this is the offset within that symbol's section.
.El
.It Cm ENDC
.El
.It Cm ENDR
.El
.Ss Sections
.Bl -tag -width Ds -compact
.It Cm REPT Ar NumberOfSections
.Bl -tag -width Ds -compact
.It Cm STRING Ar Name
The section's name.
.It Cm LONG Ar Size
The section's size, in bytes.
.It Cm BYTE Ar Type
Bits 0\(en2 indicate the section's type:
.Bl -column "Value" -compact
.It Sy Value Ta Sy Meaning
.It 0 Ta WRAM0
.It 1 Ta VRAM
.It 2 Ta ROMX
.It 3 Ta ROM0
.It 4 Ta HRAM
.It 5 Ta WRAMX
.It 6 Ta SRAM
.It 7 Ta OAM
.El
.Pp
Bit\ 7 being set means that the section is a "union"
.Pq see Do Unionized sections Dc in Xr rgbasm 5 .
Bit\ 6 being set means that the section is a "fragment"
.Pq see Do Section fragments Dc in Xr rgbasm 5 .
These two bits are mutually exclusive.
.It Cm LONG Ar Address
Address this section must be placed at.
This must either be valid for the section's
.Ar Type
(as affected by flags like
.Fl t
or
.Fl d
in
.Xr rgblink 1 ) ,
or -1 to indicate that the linker should automatically decide
.Pq the section is Dq floating .
.It Cm LONG Ar Bank
ID of the bank this section must be placed in.
This must either be valid for the section's
.Ar Type
(with the same caveats as for the
.Ar Address ) ,
or -1 to indicate that the linker should automatically decide.
.It Cm BYTE Ar Alignment
How many bits of the section's address should be equal to
.Ar AlignOfs ,
starting from the least-significant bit.
.It Cm LONG Ar AlignOfs
Alignment offset.
Must be strictly less than
.Ql 1 << Ar Alignment .
.It Cm IF Ar Type No \(eq 2 || Ar Type No \(eq 3
If the section has ROM type, it contains data.
.Pp
.Bl -tag -width Ds -compact
.It Cm BYTE Ar Data Ns Bq Size
The section's raw data.
Bytes that will be patched over must be present, even though their contents will be overwritten.
.It Cm LONG Ar NumberOfPatches
How many patches must be applied to this section's
.Ar Data .
.It Cm REPT Ar NumberOfPatches
.Bl -tag -width Ds -compact
.It Cm LONG Ar NodeID
Context in which the patch was defined.
.It Cm LONG Ar LineNo
Line number in the context at which the patch was defined.
.It Cm LONG Ar Offset
Offset within the section's
.Ar Data
at which the patch should be applied.
Must not be greater than the section's
.Ar Size
minus the patch's size
.Pq see Ar Type No below .
.It Cm LONG Ar PCSectionID
ID of the section in which PC is located.
(This is usually the same section within which the patch is applied, except for e.g.\&
.Ql LOAD
blocks, see
.Do RAM code Dc in Xr rgbasm 5 . )
.It Cm LONG Ar PCOffset
Offset of the PC symbol within the section designated by
.Ar PCSectionID .
It is expected that PC points to the instruction's first byte for instruction operands (i.e.\&
.Ql jp @
must be an infinite loop), and to the patch's first byte otherwise
.Ql ( db ,
.Ql dw ,
.Ql dl ) .
.It Cm BYTE Ar Type
.Bl -column "Value" -compact
.It Sy Value Ta Sy Meaning
.It 0 Ta Single-byte patch
.It 1 Ta Little-endian two-byte patch
.It 2 Ta Little-endian four-byte patch
.It 3 Ta Single-byte Ql jr
patch; the patch's value will be subtracted to PC + 2 (i.e.\&
.Ql jr @
must be the infinite loop
.Ql 18 FE ) .
.El
.It Cm LONG Ar RPNSize
Size of the
.Ar RPNExpr
below.
.It Cm BYTE Ar RPNExpr Ns Bq RPNSize
The patch's value, encoded as a RPN expression
.Pq see Sx RPN EXPRESSIONS .
.El
.It Cm ENDR
.El
.It Cm ENDC
.El
.El
.Ss Assertions
.Bl -tag -width Ds -compact
.It Cm LONG Ar NumberOfAssertions
How many assertions this object file contains.
.It Cm REPT Ar NumberOfAssertions
Assertions are essentially patches with a message.
.Pp
.Bl -tag -width Ds -compact
.It Cm LONG Ar NodeID
Context in which the assertions was defined.
.It Cm LONG Ar LineNo
Line number in the context at which the assertion was defined.
.It Cm LONG Ar Offset
Unused leftover from the patch structure.
.It Cm LONG Ar PCSectionID
ID of the section in which PC is located.
.It Cm LONG Ar PCOffset
Offset of the PC symbol within the section designated by
.Ar PCSectionID .
.It Cm BYTE Ar Type
Describes what should happen if the expression evaluates to a non-zero value.
.Bl -column "Value" -compact
.It Sy Value Ta Sy Meaning
.It 0 Ta Print a warning message, and continue linking normally.
.It 1 Ta Print an error message, so linking will fail, but allow other assertions to be evaluated.
.It 2 Ta Print a fatal error message, and abort immediately.
.El
.It Cm LONG Ar RPNSize
Size of the
.Ar RPNExpr
below.
.It Cm BYTE Ar RPNExpr Ns Bq RPNSize
The patch's value, encoded as a RPN expression
.Pq see Sx RPN EXPRESSIONS .
.It Cm STRING Ar Message
The message displayed if the expression evaluates to a non-zero value.
If empty, a generic message is displayed instead.
.El
.It Cm ENDR
.El
.Ss RPN EXPRESSIONS
Expressions in the object file are stored as RPN, or
.Dq Reverse Polish Notation ,
which is a notation that allows computing arbitrary expressions with just a simple stack.
For example, the expression
.Ql 2 5 -
will first push the value
.Dq 2
to the stack, then
.Dq 5 .
The
.Do + Dc operator pops two arguments from the stack, adds them, and then pushes the result on the stack, effectively replacing the two top arguments with their sum.
In the RGB format, RPN expressions are stored as
.Ar BYTE Ns s
with some bytes being special prefixes for integers and symbols.
.Bl -column -offset indent "Sy String" "Sy String"
.Ql -
operator pops two arguments from the stack, subtracts them, and then pushes back the result
.Pq Dq 3
on the stack.
A well-formed RPN expression never tries to pop from an empty stack, and leaves exactly one value in it at the end.
.Pp
RGBDS encodes RPN expressions as an array of
.Cm BYTE Ns s .
The first byte encodes either an operator, or a literal, which consumes more
.Cm BYTE Ns s
after it.
.Bl -column -offset Ds "Value"
.It Sy Value Ta Sy Meaning
.It Li $00 Ta Li + operator
.It Li $01 Ta Li - operator
.It Li $02 Ta Li * operator
.It Li $03 Ta Li / operator
.It Li $04 Ta Li % operator
.It Li $05 Ta Li unary -
.It Li $06 Ta Li ** operator
.It Li $10 Ta Li \&| operator
.It Li $11 Ta Li & operator
.It Li $12 Ta Li ^ operator
.It Li $13 Ta Li unary ~
.It Li $21 Ta Li && comparison
.It Li $22 Ta Li || comparison
.It Li $23 Ta Li unary \&!
.It Li $30 Ta Li == comparison
.It Li $31 Ta Li != comparison
.It Li $32 Ta Li > comparison
.It Li $33 Ta Li < comparison
.It Li $34 Ta Li >= comparison
.It Li $35 Ta Li <= comparison
.It Li $40 Ta Li << operator
.It Li $41 Ta Li >> operator
.It Li $42 Ta Li >>> operator
.It Li $50 Ta Li BANK(symbol) ,
a
.Ar LONG
Symbol ID follows, where -1 means PC
.It Li $51 Ta Li BANK(section_name) ,
a null-terminated string follows.
.It Li $52 Ta Li Current BANK()
.It Li $53 Ta Li SIZEOF(section_name) ,
a null-terminated string follows.
.It Li $54 Ta Li STARTOF(section_name) ,
a null-terminated string follows.
.It Li $60 Ta Li HRAMCheck .
Checks if the value is in HRAM, ANDs it with 0xFF.
.It Li $61 Ta Li RSTCheck .
Checks if the value is a RST vector, ORs it with 0xC7.
.It Li $80 Ta Ar LONG
integer follows.
.It Li $81 Ta Ar LONG
symbol ID follows.
.It Li $00 Ta Addition operator Pq Ql +
.It Li $01 Ta Subtraction operator Pq Ql -
.It Li $02 Ta Multiplication operator Pq Ql *
.It Li $03 Ta Division operator Pq Ql /
.It Li $04 Ta Modulo operator Pq Ql %
.It Li $05 Ta Negation Pq unary Ql -
.It Li $06 Ta Exponent operator Pq Ql **
.It Li $10 Ta Bitwise OR operator Pq Ql \&|
.It Li $11 Ta Bitwise AND operator Pq Ql &
.It Li $12 Ta Bitwise XOR operator Pq Ql ^
.It Li $13 Ta Bitwise complement operator Pq unary Ql ~
.It Li $21 Ta Logical AND operator Pq Ql &&
.It Li $22 Ta Logical OR operator Pq Ql ||
.It Li $23 Ta Logical complement operator Pq unary Ql \&!
.It Li $30 Ta Equality operator Pq Ql ==
.It Li $31 Ta Non-equality operator Pq Ql !=
.It Li $32 Ta Greater-than operator Pq Ql >
.It Li $33 Ta Less-than operator Pq Ql <
.It Li $34 Ta Greater-than-or-equal operator Pq Ql >=
.It Li $35 Ta Less-than-or-equal operator Pq Ql <=
.It Li $40 Ta Left shift operator Pq Ql <<
.It Li $41 Ta Arithmetic/signed right shift operator Pq Ql >>
.It Li $42 Ta Logical/unsigned right shift operator Pq Ql >>>
.It Li $50 Ta Fn BANK symbol ,
followed by the
.Ar symbol Ap s Cm LONG
ID.
.It Li $51 Ta Fn BANK section ,
followed by the
.Ar section Ap s Cm STRING
name.
.It Li $52 Ta PC's Fn BANK Pq i.e. Ql BANK(@) .
.It Li $53 Ta Fn SIZEOF section ,
followed by the
.Ar section Ap s Cm STRING
name.
.It Li $54 Ta Fn STARTOF section ,
followed by the
.Ar section Ap s Cm STRING
name.
.It Li $60 Ta Ql ldh
check.
Checks if the value is a valid
.Ql ldh
operand
.Pq see Do Load Instructions Dc in Xr gbz80 7 ,
i.e. that it is between either $00 and $FF, or $FF00 and $FFFF, both inclusive.
The value is then ANDed with $00FF
.Pq Ql & $FF .
.It Li $61 Ta Ql rst
check.
Checks if the value is a valid
.Ql rst
.Pq see Do RST vec Dc in Xr gbz80 7
vector, that is one of $00, $08, $10, $18, $20, $28, $30, or $38.
The value is then ORed with $C7
.Pq Ql \&| $C7 .
.It Li $80 Ta Integer literal.
Followed by the
.Cm LONG
integer.
.It Li $81 Ta A symbol's value.
Followed by the symbol's
.Cm LONG
ID.
.El
.Sh SEE ALSO
.Xr rgbasm 1 ,

View File

@@ -421,7 +421,7 @@ be
.Em exactly
the same.
.It
If none of the above apply, colors are sorted from lightest to darkest.
If none of the above apply, colors are sorted from lightest (first) to darkest (last).
The definition of luminance that
.Nm
uses is
@@ -472,7 +472,7 @@ delim off
.EN
Note that
.Fl n
only puts a limit on the amount of palettes, but does not fix this file's size.
only caps how many palettes are generated (and thus this file's size), but fewer may be generated still.
.Ss Tile map data
A tile map is an array of tile IDs, with one byte per tile ID.
The first byte always corresponds to the ID of the tile in top-left corner of the input image; the second byte is either the ID of the tile to its right (by default), or below it

View File

@@ -13,7 +13,7 @@
.Nd Game Boy linker
.Sh SYNOPSIS
.Nm
.Op Fl dtVvwx
.Op Fl dMtVvwx
.Op Fl l Ar linker_script
.Op Fl m Ar map_file
.Op Fl n Ar sym_file
@@ -73,6 +73,8 @@ The attributes assigned in the linker script must be consistent with any assigne
See
.Xr rgblink 5
for more information about the linker script format.
.It Fl M , Fl Fl no-sym-in-map
If specified, the map file will not list symbols, only sections.
.It Fl m Ar map_file , Fl Fl map Ar map_file
Write a map file to the given filename, listing how sections and symbols were assigned.
.It Fl n Ar sym_file , Fl Fl sym Ar sym_file

View File

@@ -14,18 +14,22 @@
.Sh DESCRIPTION
The linker script is an external file that allows the user to specify the order of sections at link time and in a centralized manner.
.Pp
A linker script consists on a series of banks followed by a list of sections and, optionally, commands.
They can be lowercase or uppercase, it is ignored.
A linker script consists of a series of bank declarations, each optionally followed by a list of section names (in double quotes) or commands.
All reserved keywords (bank types and command names) are case-insensitive; all section names are case-sensitive.
.Pp
Any line can contain a comment starting with
.Ql \&;
that ends at the end of the line:
that ends at the end of the line.
.Pp
.Bd -literal -offset indent
ROMX $F ; This is a comment
"Functions to read array"
ALIGN 8
"Array aligned to 256 bytes"
; This line is a comment
ROMX $F ; start a bank
"Some functions" ; a section name
ALIGN 8 ; a command
"Some array"
WRAMX 2
WRAMX 2 ; start another bank
org $d123 ; another command
"Some variables"
.Ed
.Pp
@@ -47,6 +51,19 @@ and
.Cm WRAMX ,
it is needed to specify a bank number after the type.
.Pp
Section names in double quotes support the same character escape sequences as strings in
.Xr rgbasm 5 ,
specifically
.Ql \[rs]\[rs] ,
.Ql \[rs]" ,
.Ql \[rs]n ,
.Ql \[rs]r ,
and
.Ql \[rs]t .
Other backslash escape sequences in
.Xr rgbasm 5
are only relevant to assembly code and do not apply in section names.
.Pp
When a new bank statement is found, sections found after it will be placed right from the beginning of that bank.
If the linker script switches to a different bank and then comes back to a previous one, it will continue from the last address that was used.
.Pp

View File

@@ -81,6 +81,7 @@ set(rgblink_src
"link/output.c"
"link/patch.c"
"link/script.c"
"link/sdas_obj.c"
"link/section.c"
"link/symbol.c"
"hashmap.c"

View File

@@ -21,33 +21,29 @@
#include "hashmap.h"
/*
* Charmaps are stored using a structure known as "trie".
* Essentially a tree, where each nodes stores a single character's worth of info:
* whether there exists a mapping that ends at the current character,
*/
// Charmaps are stored using a structure known as "trie".
// Essentially a tree, where each nodes stores a single character's worth of info:
// whether there exists a mapping that ends at the current character,
struct Charnode {
bool isTerminal; /* Whether there exists a mapping that ends here */
uint8_t value; /* If the above is true, its corresponding value */
/* This MUST be indexes and not pointers, because pointers get invalidated by `realloc`!! */
size_t next[255]; /* Indexes of where to go next, 0 = nowhere */
bool isTerminal; // Whether there exists a mapping that ends here
uint8_t value; // If the above is true, its corresponding value
// This MUST be indexes and not pointers, because pointers get invalidated by `realloc`!!
size_t next[255]; // Indexes of where to go next, 0 = nowhere
};
#define INITIAL_CAPACITY 32
struct Charmap {
char *name;
size_t usedNodes; /* How many nodes are being used */
size_t capacity; /* How many nodes have been allocated */
struct Charnode nodes[]; /* first node is reserved for the root node */
size_t usedNodes; // How many nodes are being used
size_t capacity; // How many nodes have been allocated
struct Charnode nodes[]; // first node is reserved for the root node
};
static HashMap charmaps;
/*
* Store pointers to hashmap nodes, so that there is only one pointer to the memory block
* that gets reallocated.
*/
// Store pointers to hashmap nodes, so that there is only one pointer to the memory block
// that gets reallocated.
static struct Charmap **currentCharmap;
struct CharmapStackEntry {
@@ -96,7 +92,7 @@ struct Charmap *charmap_New(char const *name, char const *baseName)
return charmap;
}
/* Init the new charmap's fields */
// Init the new charmap's fields
if (base) {
resizeCharmap(&charmap, base->capacity);
charmap->usedNodes = base->usedNodes;
@@ -105,7 +101,7 @@ struct Charmap *charmap_New(char const *name, char const *baseName)
} else {
resizeCharmap(&charmap, INITIAL_CAPACITY);
charmap->usedNodes = 1;
initNode(&charmap->nodes[0]); /* Init the root node */
initNode(&charmap->nodes[0]); // Init the root node
}
charmap->name = strdup(name);
@@ -169,16 +165,16 @@ void charmap_Add(char *mapping, uint8_t value)
if (node->next[c]) {
node = &charmap->nodes[node->next[c]];
} else {
/* Register next available node */
// Register next available node
node->next[c] = charmap->usedNodes;
/* If no more nodes are available, get new ones */
// If no more nodes are available, get new ones
if (charmap->usedNodes == charmap->capacity) {
charmap->capacity *= 2;
resizeCharmap(currentCharmap, charmap->capacity);
charmap = *currentCharmap;
}
/* Switch to and init new node */
// Switch to and init new node
node = &charmap->nodes[charmap->usedNodes++];
initNode(node);
}
@@ -203,12 +199,10 @@ size_t charmap_Convert(char const *input, uint8_t *output)
size_t charmap_ConvertNext(char const **input, uint8_t **output)
{
/*
* The goal is to match the longest mapping possible.
* For that, advance through the trie with each character read.
* If that would lead to a dead end, rewind characters until the last match, and output.
* If no match, read a UTF-8 codepoint and output that.
*/
// The goal is to match the longest mapping possible.
// For that, advance through the trie with each character read.
// If that would lead to a dead end, rewind characters until the last match, and output.
// If no match, read a UTF-8 codepoint and output that.
struct Charmap const *charmap = *currentCharmap;
struct Charnode const *node = &charmap->nodes[0];
struct Charnode const *match = NULL;
@@ -242,6 +236,7 @@ size_t charmap_ConvertNext(char const **input, uint8_t **output)
return 1;
} else if (**input) { // No match found, but there is some input left
int firstChar = **input;
// This will write the codepoint's value to `output`, little-endian
size_t codepointLen = readUTF8Char(output ? *output : NULL,
*input);
@@ -254,6 +249,12 @@ size_t charmap_ConvertNext(char const **input, uint8_t **output)
if (output)
*output += codepointLen;
// Check if the character map is not the default "main" one, or if
// it has any mappings defined
if (strcmp(charmap->name, "main") || charmap->usedNodes > 1)
warning(WARNING_UNMAPPED_CHAR,
"Unmapped character %s\n", printChar(firstChar));
return codepointLen;
} else { // End of input

View File

@@ -6,9 +6,7 @@
* SPDX-License-Identifier: MIT
*/
/*
* Fixed-point math routines
*/
// Fixed-point math routines
#include <inttypes.h>
#include <math.h>
@@ -19,20 +17,24 @@
#include "asm/symbol.h"
#include "asm/warning.h"
#define fix2double(i) ((double)((i) / 65536.0))
#define double2fix(d) ((int32_t)round((d) * 65536.0))
// pi radians == 32768 fixed-point "degrees"
#define fdeg2rad(f) ((f) * (M_PI / 32768.0))
#define rad2fdeg(r) ((r) * (32768.0 / M_PI))
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
/*
* Print a fixed point value
*/
#define fix2double(i) ((double)((i) / fix_PrecisionFactor()))
#define double2fix(d) ((int32_t)round((d) * fix_PrecisionFactor()))
// pi*2 radians == 2**fixPrecision fixed-point "degrees"
#define fdeg2rad(f) ((f) * (M_PI * 2) / fix_PrecisionFactor())
#define rad2fdeg(r) ((r) * fix_PrecisionFactor() / (M_PI * 2))
uint8_t fixPrecision;
double fix_PrecisionFactor(void)
{
return pow(2.0, fixPrecision);
}
void fix_Print(int32_t i)
{
uint32_t u = i;
@@ -43,117 +45,80 @@ void fix_Print(int32_t i)
sign = "-";
}
printf("%s%" PRIu32 ".%05" PRIu32, sign, u >> 16,
printf("%s%" PRIu32 ".%05" PRIu32, sign, u >> fixPrecision,
((uint32_t)(fix2double(u) * 100000 + 0.5)) % 100000);
}
/*
* Calculate sine
*/
int32_t fix_Sin(int32_t i)
{
return double2fix(sin(fdeg2rad(fix2double(i))));
}
/*
* Calculate cosine
*/
int32_t fix_Cos(int32_t i)
{
return double2fix(cos(fdeg2rad(fix2double(i))));
}
/*
* Calculate tangent
*/
int32_t fix_Tan(int32_t i)
{
return double2fix(tan(fdeg2rad(fix2double(i))));
}
/*
* Calculate arcsine
*/
int32_t fix_ASin(int32_t i)
{
return double2fix(rad2fdeg(asin(fix2double(i))));
}
/*
* Calculate arccosine
*/
int32_t fix_ACos(int32_t i)
{
return double2fix(rad2fdeg(acos(fix2double(i))));
}
/*
* Calculate arctangent
*/
int32_t fix_ATan(int32_t i)
{
return double2fix(rad2fdeg(atan(fix2double(i))));
}
/*
* Calculate atan2
*/
int32_t fix_ATan2(int32_t i, int32_t j)
{
return double2fix(rad2fdeg(atan2(fix2double(i), fix2double(j))));
}
/*
* Multiplication
*/
int32_t fix_Mul(int32_t i, int32_t j)
{
return double2fix(fix2double(i) * fix2double(j));
}
/*
* Division
*/
int32_t fix_Div(int32_t i, int32_t j)
{
return double2fix(fix2double(i) / fix2double(j));
}
/*
* Power
*/
int32_t fix_Mod(int32_t i, int32_t j)
{
return double2fix(fmod(fix2double(i), fix2double(j)));
}
int32_t fix_Pow(int32_t i, int32_t j)
{
return double2fix(pow(fix2double(i), fix2double(j)));
}
/*
* Logarithm
*/
int32_t fix_Log(int32_t i, int32_t j)
{
return double2fix(log(fix2double(i)) / log(fix2double(j)));
}
/*
* Round
*/
int32_t fix_Round(int32_t i)
{
return double2fix(round(fix2double(i)));
}
/*
* Ceil
*/
int32_t fix_Ceil(int32_t i)
{
return double2fix(ceil(fix2double(i)));
}
/*
* Floor
*/
int32_t fix_Floor(int32_t i)
{
return double2fix(floor(fix2double(i)));

View File

@@ -15,6 +15,7 @@
#include <stdlib.h>
#include <string.h>
#include "asm/fixpoint.h"
#include "asm/format.h"
#include "asm/warning.h"
@@ -46,7 +47,7 @@ void fmt_UseCharacter(struct FormatSpec *fmt, int c)
return;
switch (c) {
/* sign */
// sign
case ' ':
case '+':
if (fmt->state > FORMAT_SIGN)
@@ -55,7 +56,7 @@ void fmt_UseCharacter(struct FormatSpec *fmt, int c)
fmt->sign = c;
break;
/* prefix */
// prefix
case '#':
if (fmt->state > FORMAT_PREFIX)
goto invalid;
@@ -63,7 +64,7 @@ void fmt_UseCharacter(struct FormatSpec *fmt, int c)
fmt->prefix = true;
break;
/* align */
// align
case '-':
if (fmt->state > FORMAT_ALIGN)
goto invalid;
@@ -71,11 +72,11 @@ void fmt_UseCharacter(struct FormatSpec *fmt, int c)
fmt->alignLeft = true;
break;
/* pad and width */
// pad and width
case '0':
if (fmt->state < FORMAT_WIDTH)
fmt->padZero = true;
/* fallthrough */
// fallthrough
case '1':
case '2':
case '3':
@@ -104,7 +105,7 @@ void fmt_UseCharacter(struct FormatSpec *fmt, int c)
fmt->hasFrac = true;
break;
/* type */
// type
case 'd':
case 'u':
case 'X':
@@ -149,7 +150,7 @@ void fmt_PrintString(char *buf, size_t bufLen, struct FormatSpec const *fmt, cha
size_t len = strlen(value);
size_t totalLen = fmt->width > len ? fmt->width : len;
if (totalLen > bufLen - 1) { /* bufLen includes terminator */
if (totalLen > bufLen - 1) { // bufLen includes terminator
error("Formatted string value too long\n");
totalLen = bufLen - 1;
if (len > totalLen)
@@ -182,7 +183,7 @@ void fmt_PrintNumber(char *buf, size_t bufLen, struct FormatSpec const *fmt, uin
if (fmt->type == 's')
error("Formatting number as type 's'\n");
char sign = fmt->sign; /* 0 or ' ' or '+' */
char sign = fmt->sign; // 0 or ' ' or '+'
if (fmt->type == 'd' || fmt->type == 'f') {
int32_t v = value;
@@ -200,10 +201,10 @@ void fmt_PrintNumber(char *buf, size_t bufLen, struct FormatSpec const *fmt, uin
: fmt->type == 'o' ? '&'
: 0;
char valueBuf[262]; /* Max 5 digits + decimal + 255 fraction digits + terminator */
char valueBuf[262]; // Max 5 digits + decimal + 255 fraction digits + terminator
if (fmt->type == 'b') {
/* Special case for binary */
// Special case for binary
char *ptr = valueBuf;
do {
@@ -213,7 +214,7 @@ void fmt_PrintNumber(char *buf, size_t bufLen, struct FormatSpec const *fmt, uin
*ptr = '\0';
/* Reverse the digits */
// Reverse the digits
size_t valueLen = ptr - valueBuf;
for (size_t i = 0, j = valueLen - 1; i < j; i++, j--) {
@@ -223,9 +224,9 @@ void fmt_PrintNumber(char *buf, size_t bufLen, struct FormatSpec const *fmt, uin
valueBuf[j] = c;
}
} else if (fmt->type == 'f') {
/* Special case for fixed-point */
// Special case for fixed-point
/* Default fractional width (C's is 6 for "%f"; here 5 is enough) */
// Default fractional width (C's is 6 for "%f"; here 5 is enough for Q16.16)
size_t fracWidth = fmt->hasFrac ? fmt->fracWidth : 5;
if (fracWidth > 255) {
@@ -234,7 +235,8 @@ void fmt_PrintNumber(char *buf, size_t bufLen, struct FormatSpec const *fmt, uin
fracWidth = 255;
}
snprintf(valueBuf, sizeof(valueBuf), "%.*f", (int)fracWidth, value / 65536.0);
snprintf(valueBuf, sizeof(valueBuf), "%.*f", (int)fracWidth,
value / fix_PrecisionFactor());
} else {
char const *spec = fmt->type == 'd' ? "%" PRId32
: fmt->type == 'u' ? "%" PRIu32
@@ -250,7 +252,7 @@ void fmt_PrintNumber(char *buf, size_t bufLen, struct FormatSpec const *fmt, uin
size_t numLen = !!sign + !!prefix + len;
size_t totalLen = fmt->width > numLen ? fmt->width : numLen;
if (totalLen > bufLen - 1) { /* bufLen includes terminator */
if (totalLen > bufLen - 1) { // bufLen includes terminator
error("Formatted numeric value too long\n");
totalLen = bufLen - 1;
if (numLen > totalLen) {
@@ -273,7 +275,7 @@ void fmt_PrintNumber(char *buf, size_t bufLen, struct FormatSpec const *fmt, uin
buf[i] = ' ';
} else {
if (fmt->padZero) {
/* sign, then prefix, then zero padding */
// sign, then prefix, then zero padding
if (sign)
buf[pos++] = sign;
if (prefix)
@@ -281,7 +283,7 @@ void fmt_PrintNumber(char *buf, size_t bufLen, struct FormatSpec const *fmt, uin
for (size_t i = 0; i < padLen; i++)
buf[pos++] = '0';
} else {
/* space padding, then sign, then prefix */
// space padding, then sign, then prefix
for (size_t i = 0; i < padLen; i++)
buf[pos++] = ' ';
if (sign)

View File

@@ -19,7 +19,7 @@
#include "asm/main.h"
#include "asm/symbol.h"
#include "asm/warning.h"
#include "platform.h" /* S_ISDIR (stat macro) */
#include "platform.h" // S_ISDIR (stat macro)
#define MAXINCPATHS 128
@@ -28,7 +28,7 @@ struct Context {
struct FileStackNode *fileInfo;
struct LexerState *lexerState;
uint32_t uniqueID;
struct MacroArgs *macroArgs; /* Macro args are *saved* here */
struct MacroArgs *macroArgs; // Macro args are *saved* here
uint32_t nbReptIters;
int32_t forValue;
int32_t forStep;
@@ -37,7 +37,6 @@ struct Context {
static struct Context *contextStack;
static size_t contextDepth = 0;
#define DEFAULT_MAX_DEPTH 64
size_t maxRecursionDepth;
static unsigned int nbIncPaths = 0;
@@ -48,7 +47,7 @@ static const char *dumpNodeAndParents(struct FileStackNode const *node)
char const *name;
if (node->type == NODE_REPT) {
assert(node->parent); /* REPT nodes should always have a parent */
assert(node->parent); // REPT nodes should always have a parent
struct FileStackReptNode const *reptInfo = (struct FileStackReptNode const *)node;
name = dumpNodeAndParents(node->parent);
@@ -89,7 +88,7 @@ struct FileStackNode *fstk_GetFileStack(void)
struct FileStackNode *node = contextStack->fileInfo;
/* Mark node and all of its parents as referenced if not already so they don't get freed */
// Mark node and all of its parents as referenced if not already so they don't get freed
while (node && !node->referenced) {
node->ID = -1;
node->referenced = true;
@@ -100,7 +99,7 @@ struct FileStackNode *fstk_GetFileStack(void)
char const *fstk_GetFileName(void)
{
/* Iterating via the nodes themselves skips nested REPTs */
// Iterating via the nodes themselves skips nested REPTs
struct FileStackNode const *node = contextStack->fileInfo;
while (node->type != NODE_FILE)
@@ -121,7 +120,7 @@ void fstk_AddIncludePath(char const *path)
char *str = malloc(allocSize);
if (!str) {
/* Attempt to continue without that path */
// Attempt to continue without that path
error("Failed to allocate new include path: %s\n", strerror(errno));
return;
}
@@ -150,14 +149,14 @@ static bool isPathValid(char const *path)
if (stat(path, &statbuf) != 0)
return false;
/* Reject directories */
// Reject directories
return !S_ISDIR(statbuf.st_mode);
}
bool fstk_FindFile(char const *path, char **fullPath, size_t *size)
{
if (!*size) {
*size = 64; /* This is arbitrary, really */
*size = 64; // This is arbitrary, really
*fullPath = realloc(*fullPath, *size);
if (!*fullPath)
error("realloc error during include path search: %s\n",
@@ -175,8 +174,8 @@ bool fstk_FindFile(char const *path, char **fullPath, size_t *size)
break;
}
/* Oh how I wish `asnprintf` was standard... */
if ((size_t)len >= *size) { /* `len` doesn't include the terminator, `size` does */
// Oh how I wish `asnprintf` was standard...
if ((size_t)len >= *size) { // `size` includes the terminator, `len` doesn't
*size = len + 1;
*fullPath = realloc(*fullPath, *size);
if (!*fullPath) {
@@ -213,17 +212,18 @@ bool yywrap(void)
fatalerror("Ended block with %" PRIu32 " unterminated IF construct%s\n",
ifDepth, ifDepth == 1 ? "" : "s");
if (contextStack->fileInfo->type == NODE_REPT) { /* The context is a REPT block, which may loop */
if (contextStack->fileInfo->type == NODE_REPT) {
// The context is a REPT or FOR block, which may loop
struct FileStackReptNode *fileInfo = (struct FileStackReptNode *)contextStack->fileInfo;
/* If the node is referenced, we can't edit it; duplicate it */
// If the node is referenced, we can't edit it; duplicate it
if (contextStack->fileInfo->referenced) {
size_t size = sizeof(*fileInfo) + sizeof(fileInfo->iters[0]) * fileInfo->reptDepth;
struct FileStackReptNode *copy = malloc(size);
if (!copy)
fatalerror("Failed to duplicate REPT file node: %s\n", strerror(errno));
/* Copy all info but the referencing */
// Copy all info but the referencing
memcpy(copy, fileInfo, size);
copy->node.next = NULL;
copy->node.referenced = false;
@@ -232,19 +232,19 @@ bool yywrap(void)
contextStack->fileInfo = (struct FileStackNode *)fileInfo;
}
/* If this is a FOR, update the symbol value */
// If this is a FOR, update the symbol value
if (contextStack->forName && fileInfo->iters[0] <= contextStack->nbReptIters) {
contextStack->forValue += contextStack->forStep;
struct Symbol *sym = sym_AddVar(contextStack->forName,
contextStack->forValue);
/* This error message will refer to the current iteration */
// This error message will refer to the current iteration
if (sym->type != SYM_VAR)
fatalerror("Failed to update FOR symbol value\n");
}
/* Advance to the next iteration */
// Advance to the next iteration
fileInfo->iters[0]++;
/* If this wasn't the last iteration, wrap instead of popping */
// If this wasn't the last iteration, wrap instead of popping
if (fileInfo->iters[0] <= contextStack->nbReptIters) {
lexer_RestartRept(contextStack->fileInfo->lineNo);
contextStack->uniqueID = macro_UseNewUniqueID();
@@ -261,15 +261,15 @@ bool yywrap(void)
contextDepth--;
lexer_DeleteState(context->lexerState);
/* Restore args if a macro (not REPT) saved them */
// Restore args if a macro (not REPT) saved them
if (context->fileInfo->type == NODE_MACRO)
macro_UseNewArgs(contextStack->macroArgs);
/* Free the file stack node */
// Free the file stack node
if (!context->fileInfo->referenced)
free(context->fileInfo);
/* Free the FOR symbol name */
// Free the FOR symbol name
free(context->forName);
/* Free the entry and make its parent the current entry */
// Free the entry and make its parent the current entry
free(context);
lexer_SetState(contextStack->lexerState);
@@ -277,30 +277,30 @@ bool yywrap(void)
return false;
}
/*
* Make sure not to switch the lexer state before calling this, so the saved line no is correct
* BE CAREFUL!! This modifies the file stack directly, you should have set up the file info first
* Callers should set contextStack->lexerState after this so it is not NULL
*/
// Make sure not to switch the lexer state before calling this, so the saved line no is correct.
// BE CAREFUL!! This modifies the file stack directly, you should have set up the file info first.
// Callers should set contextStack->lexerState after this so it is not NULL.
static void newContext(struct FileStackNode *fileInfo)
{
++contextDepth;
fstk_NewRecursionDepth(maxRecursionDepth); // Only checks if the max depth was exceeded
// Save the current `\@` value, to be restored when this context ends
contextStack->uniqueID = macro_GetUniqueID();
struct Context *context = malloc(sizeof(*context));
if (!context)
fatalerror("Failed to allocate memory for new context: %s\n", strerror(errno));
fileInfo->parent = contextStack->fileInfo;
fileInfo->lineNo = 0; /* Init to a default value, see struct definition for info */
fileInfo->lineNo = 0; // Init to a default value, see struct definition for info
fileInfo->referenced = false;
fileInfo->lineNo = lexer_GetLineNo();
context->fileInfo = fileInfo;
context->forName = NULL;
/*
* Link new entry to its parent so it's reachable later
* ERRORS SHOULD NOT OCCUR AFTER THIS!!
*/
// Link new entry to its parent so it's reachable later
// ERRORS SHOULD NOT OCCUR AFTER THIS!!
context->parent = contextStack;
contextStack = context;
}
@@ -338,9 +338,8 @@ void fstk_RunInclude(char const *path)
if (!contextStack->lexerState)
fatalerror("Failed to set up lexer for file include\n");
lexer_SetStateAtEOL(contextStack->lexerState);
/* We're back at top-level, so most things are reset */
contextStack->uniqueID = 0;
macro_SetUniqueID(0);
// We're back at top-level, so most things are reset
contextStack->uniqueID = macro_UndefUniqueID();
}
void fstk_RunMacro(char const *macroName, struct MacroArgs *args)
@@ -357,16 +356,16 @@ void fstk_RunMacro(char const *macroName, struct MacroArgs *args)
}
contextStack->macroArgs = macro_GetCurrentArgs();
/* Compute total length of this node's name: <base name>::<macro> */
// Compute total length of this node's name: <base name>::<macro>
size_t reptNameLen = 0;
struct FileStackNode const *node = macro->src;
if (node->type == NODE_REPT) {
struct FileStackReptNode const *reptNode = (struct FileStackReptNode const *)node;
/* 4294967295 = 2^32 - 1, aka UINT32_MAX */
// 4294967295 = 2^32 - 1, aka UINT32_MAX
reptNameLen += reptNode->reptDepth * strlen("::REPT~4294967295");
/* Look for next named node */
// Look for next named node
do {
node = node->parent;
} while (node->type == NODE_REPT);
@@ -382,7 +381,7 @@ void fstk_RunMacro(char const *macroName, struct MacroArgs *args)
return;
}
fileInfo->node.type = NODE_MACRO;
/* Print the name... */
// Print the name...
char *dest = fileInfo->name;
memcpy(dest, baseNode->name, baseLen);
@@ -429,13 +428,13 @@ static bool newReptContext(int32_t reptLineNo, char *body, size_t size)
fileInfo->reptDepth = reptDepth + 1;
fileInfo->iters[0] = 1;
if (reptDepth)
/* Copy all parent iter counts */
// Copy all parent iter counts
memcpy(&fileInfo->iters[1],
((struct FileStackReptNode *)contextStack->fileInfo)->iters,
reptDepth * sizeof(fileInfo->iters[0]));
newContext((struct FileStackNode *)fileInfo);
/* Correct our line number, which currently points to the `ENDR` line */
// Correct our line number, which currently points to the `ENDR` line
contextStack->fileInfo->lineNo = reptLineNo;
contextStack->lexerState = lexer_OpenFileView("REPT", body, size, reptLineNo);
@@ -493,7 +492,7 @@ void fstk_RunFor(char const *symName, int32_t start, int32_t stop, int32_t step,
void fstk_StopRept(void)
{
/* Prevent more iterations */
// Prevent more iterations
contextStack->nbReptIters = 0;
}
@@ -510,7 +509,7 @@ bool fstk_Break(void)
void fstk_NewRecursionDepth(size_t newDepth)
{
if (contextDepth >= newDepth)
if (contextDepth > newDepth)
fatalerror("Recursion limit (%zu) exceeded\n", newDepth);
maxRecursionDepth = newDepth;
}
@@ -533,7 +532,7 @@ void fstk_Init(char const *mainPath, size_t maxDepth)
fatalerror("Failed to allocate memory for main file info: %s\n", strerror(errno));
context->fileInfo = (struct FileStackNode *)fileInfo;
/* lineNo and reptIter are unused on the top-level context */
// lineNo and reptIter are unused on the top-level context
context->fileInfo->parent = NULL;
context->fileInfo->lineNo = 0; // This still gets written to the object file, so init it
context->fileInfo->referenced = false;
@@ -542,20 +541,17 @@ void fstk_Init(char const *mainPath, size_t maxDepth)
context->parent = NULL;
context->lexerState = state;
context->uniqueID = 0;
macro_SetUniqueID(0);
context->uniqueID = macro_UndefUniqueID();
context->nbReptIters = 0;
context->forValue = 0;
context->forStep = 0;
context->forName = NULL;
/* Now that it's set up properly, register the context */
// Now that it's set up properly, register the context
contextStack = context;
/*
* Check that max recursion depth won't allow overflowing node `malloc`s
* This assumes that the rept node is larger
*/
// Check that max recursion depth won't allow overflowing node `malloc`s
// This assumes that the rept node is larger
#define DEPTH_LIMIT ((SIZE_MAX - sizeof(struct FileStackReptNode)) / sizeof(uint32_t))
if (maxDepth > DEPTH_LIMIT) {
error("Recursion depth may not be higher than %zu, defaulting to "
@@ -564,7 +560,7 @@ void fstk_Init(char const *mainPath, size_t maxDepth)
} else {
maxRecursionDepth = maxDepth;
}
/* Make sure that the default of 64 is OK, though */
// Make sure that the default of 64 is OK, though
assert(DEPTH_LIMIT >= DEFAULT_MAX_DEPTH);
#undef DEPTH_LIMIT
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,11 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2022, Eldred Habert and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <stdbool.h>
@@ -12,13 +18,11 @@
#define MAXMACROARGS 99999
/*
* Your average macro invocation does not go past the tens, but some go further
* This ensures that sane and slightly insane invocations suffer no penalties,
* and the rest is insane and thus will assume responsibility.
* Additionally, ~300 bytes (on x64) of memory per level of nesting has been
* deemed reasonable. (Halve that on x86.)
*/
// Your average macro invocation does not go past the tens, but some go further
// This ensures that sane and slightly insane invocations suffer no penalties,
// and the rest is insane and thus will assume responsibility.
// Additionally, ~300 bytes (on x64) of memory per level of nesting has been
// deemed reasonable. (Halve that on x86.)
#define INITIAL_ARG_SIZE 32
struct MacroArgs {
unsigned int nbArgs;
@@ -33,11 +37,9 @@ struct MacroArgs {
static struct MacroArgs *macroArgs = NULL;
static uint32_t uniqueID = 0;
static uint32_t maxUniqueID = 0;
/*
* The initialization is somewhat harmful, since it is never used, but it
* guarantees the size of the buffer will be correct. I was unable to find a
* better solution, but if you have one, please feel free!
*/
// The initialization is somewhat harmful, since it is never used, but it
// guarantees the size of the buffer will be correct. I was unable to find a
// better solution, but if you have one, please feel free!
static char uniqueIDBuf[] = "_u4294967295"; // UINT32_MAX
static char *uniqueIDPtr = NULL;
@@ -68,7 +70,7 @@ void macro_AppendArg(struct MacroArgs **argPtr, char *s)
error("A maximum of " EXPAND_AND_STR(MAXMACROARGS) " arguments is allowed\n");
if (macArgs->nbArgs >= macArgs->capacity) {
macArgs->capacity *= 2;
/* Check that overflow didn't roll us back */
// Check that overflow didn't roll us back
if (macArgs->capacity <= macArgs->nbArgs)
fatalerror("Failed to add new macro argument: capacity overflow\n");
macArgs = realloc(macArgs, SIZEOF_ARGS(macArgs->capacity));
@@ -112,9 +114,9 @@ char const *macro_GetAllArgs(void)
size_t len = 0;
for (uint32_t i = macroArgs->shift; i < macroArgs->nbArgs; i++)
len += strlen(macroArgs->args[i]) + 1; /* 1 for comma */
len += strlen(macroArgs->args[i]) + 1; // 1 for comma
char *str = malloc(len + 1); /* 1 for '\0' */
char *str = malloc(len + 1); // 1 for '\0'
char *ptr = str;
if (!str)
@@ -126,9 +128,9 @@ char const *macro_GetAllArgs(void)
memcpy(ptr, macroArgs->args[i], n);
ptr += n;
/* Commas go between args and after a last empty arg */
// Commas go between args and after a last empty arg
if (i < macroArgs->nbArgs - 1 || n == 0)
*ptr++ = ','; /* no space after comma */
*ptr++ = ','; // no space after comma
}
*ptr = '\0';
@@ -142,19 +144,21 @@ uint32_t macro_GetUniqueID(void)
char const *macro_GetUniqueIDStr(void)
{
// Generate a new unique ID on the first use of `\@`
if (uniqueID == 0)
macro_SetUniqueID(++maxUniqueID);
return uniqueIDPtr;
}
void macro_SetUniqueID(uint32_t id)
{
uniqueID = id;
if (id == 0) {
if (id == 0 || id == (uint32_t)-1) {
uniqueIDPtr = NULL;
} else {
if (uniqueID > maxUniqueID)
maxUniqueID = uniqueID;
/* The buffer is guaranteed to be the correct size */
/* This is a valid label fragment, but not a valid numeric */
// The buffer is guaranteed to be the correct size
// This is a valid label fragment, but not a valid numeric
sprintf(uniqueIDBuf, "_u%" PRIu32, id);
uniqueIDPtr = uniqueIDBuf;
}
@@ -162,8 +166,16 @@ void macro_SetUniqueID(uint32_t id)
uint32_t macro_UseNewUniqueID(void)
{
macro_SetUniqueID(++maxUniqueID);
return maxUniqueID;
// A new ID will be generated on the first use of `\@`
macro_SetUniqueID(0);
return uniqueID;
}
uint32_t macro_UndefUniqueID(void)
{
// No ID will be generated; use of `\@` is an error
macro_SetUniqueID((uint32_t)-1);
return uniqueID;
}
void macro_ShiftCurrentArgs(int32_t count)

View File

@@ -19,6 +19,7 @@
#include <time.h>
#include "asm/charmap.h"
#include "asm/fixpoint.h"
#include "asm/format.h"
#include "asm/fstack.h"
#include "asm/lexer.h"
@@ -39,8 +40,8 @@
#ifdef __clang__
#if __has_feature(address_sanitizer) && !defined(__SANITIZE_ADDRESS__)
#define __SANITIZE_ADDRESS__
#endif /* __has_feature(address_sanitizer) && !defined(__SANITIZE_ADDRESS__) */
#endif /* __clang__ */
#endif // __has_feature(address_sanitizer) && !defined(__SANITIZE_ADDRESS__)
#endif // __clang__
#ifdef __SANITIZE_ADDRESS__
// There are known, non-trivial to fix leaks. We would still like to have `make develop'
@@ -63,9 +64,9 @@ bool warnOnHaltNop;
bool optimizeLoads;
bool warnOnLdOpt;
bool verbose;
bool warnings; /* True to enable warnings, false to disable them. */
bool warnings; // True to enable warnings, false to disable them.
/* Escapes Make-special chars from a string */
// Escapes Make-special chars from a string
static char *make_escape(char const *str)
{
char * const escaped_str = malloc(strlen(str) * 2 + 1);
@@ -75,7 +76,7 @@ static char *make_escape(char const *str)
err("%s: Failed to allocate memory", __func__);
while (*str) {
/* All dollars needs to be doubled */
// All dollars needs to be doubled
if (*str == '$')
*dest++ = '$';
*dest++ = *str++;
@@ -85,22 +86,20 @@ static char *make_escape(char const *str)
return escaped_str;
}
/* Short options */
static const char *optstring = "b:D:Eg:Hhi:LlM:o:p:r:VvW:w";
// Short options
static const char *optstring = "b:D:Eg:Hhi:LlM:o:p:Q:r:VvW:w";
/* Variables for the long-only options */
static int depType; /* Variants of `-M` */
// Variables for the long-only options
static int depType; // Variants of `-M`
/*
* Equivalent long options
* Please keep in the same order as short opts
*
* Also, make sure long opts don't create ambiguity:
* A long opt's name should start with the same letter as its short opt,
* except if it doesn't create any ambiguity (`verbose` versus `version`).
* This is because long opt matching, even to a single char, is prioritized
* over short opt matching
*/
// Equivalent long options
// Please keep in the same order as short opts
//
// Also, make sure long opts don't create ambiguity:
// A long opt's name should start with the same letter as its short opt,
// except if it doesn't create any ambiguity (`verbose` versus `version`).
// This is because long opt matching, even to a single char, is prioritized
// over short opt matching
static struct option const longopts[] = {
{ "binary-digits", required_argument, NULL, 'b' },
{ "define", required_argument, NULL, 'D' },
@@ -118,6 +117,7 @@ static struct option const longopts[] = {
{ "MQ", required_argument, &depType, 'Q' },
{ "output", required_argument, NULL, 'o' },
{ "pad-value", required_argument, NULL, 'p' },
{ "q-precision", required_argument, NULL, 'Q' },
{ "recursion-depth", required_argument, NULL, 'r' },
{ "version", no_argument, NULL, 'V' },
{ "verbose", no_argument, NULL, 'v' },
@@ -128,9 +128,10 @@ static struct option const longopts[] = {
static void print_usage(void)
{
fputs(
"Usage: rgbasm [-EhLVvw] [-b chars] [-D name[=value]] [-g chars] [-i path]\n"
"Usage: rgbasm [-EHhLlVvw] [-b chars] [-D name[=value]] [-g chars] [-i path]\n"
" [-M depend_file] [-MG] [-MP] [-MT target_file] [-MQ target_file]\n"
" [-o out_file] [-p pad_value] [-r depth] [-W warning] <file>\n"
" [-o out_file] [-p pad_value] [-Q precision] [-r depth]\n"
" [-W warning] <file>\n"
"Useful options:\n"
" -E, --export-all export all labels\n"
" -M, --dependfile <path> set the output dependency file\n"
@@ -152,10 +153,8 @@ int main(int argc, char *argv[])
time_t now = time(NULL);
char const *sourceDateEpoch = getenv("SOURCE_DATE_EPOCH");
/*
* Support SOURCE_DATE_EPOCH for reproducible builds
* https://reproducible-builds.org/docs/source-date-epoch/
*/
// Support SOURCE_DATE_EPOCH for reproducible builds
// https://reproducible-builds.org/docs/source-date-epoch/
if (sourceDateEpoch)
now = (time_t)strtoul(sourceDateEpoch, NULL, 0);
@@ -174,6 +173,7 @@ int main(int argc, char *argv[])
opt_B("01");
opt_G("0123");
opt_P(0);
opt_Q(16);
haltnop = true;
warnOnHaltNop = true;
optimizeLoads = true;
@@ -181,7 +181,7 @@ int main(int argc, char *argv[])
verbose = false;
warnings = true;
sym_SetExportAll(false);
uint32_t maxDepth = 64;
uint32_t maxDepth = DEFAULT_MAX_DEPTH;
size_t targetFileNameLen = 0;
while ((ch = musl_getopt_long_only(argc, argv, optstring, longopts, NULL)) != -1) {
@@ -254,17 +254,34 @@ int main(int argc, char *argv[])
out_SetFileName(musl_optarg);
break;
unsigned long fill;
unsigned long padByte;
case 'p':
fill = strtoul(musl_optarg, &ep, 0);
padByte = strtoul(musl_optarg, &ep, 0);
if (musl_optarg[0] == '\0' || *ep != '\0')
errx("Invalid argument for option 'p'");
if (fill > 0xFF)
if (padByte > 0xFF)
errx("Argument for option 'p' must be between 0 and 0xFF");
opt_P(fill);
opt_P(padByte);
break;
unsigned long precision;
const char *precisionArg;
case 'Q':
precisionArg = musl_optarg;
if (precisionArg[0] == '.')
precisionArg++;
precision = strtoul(precisionArg, &ep, 0);
if (musl_optarg[0] == '\0' || *ep != '\0')
errx("Invalid argument for option 'Q'");
if (precision < 1 || precision > 31)
errx("Argument for option 'Q' must be between 1 and 31");
opt_Q(precision);
break;
case 'r':
@@ -277,6 +294,7 @@ int main(int argc, char *argv[])
case 'V':
printf("rgbasm %s\n", get_package_version_string());
exit(0);
case 'v':
verbose = true;
break;
@@ -289,7 +307,7 @@ int main(int argc, char *argv[])
warnings = false;
break;
/* Long-only options */
// Long-only options
case 0:
switch (depType) {
case 'G':
@@ -321,10 +339,10 @@ int main(int argc, char *argv[])
}
break;
/* Unrecognized options */
// Unrecognized options
default:
print_usage();
/* NOTREACHED */
// NOTREACHED
}
}
@@ -355,7 +373,7 @@ int main(int argc, char *argv[])
charmap_New("main", NULL);
// Init lexer and file stack, prodiving file info
// Init lexer and file stack, providing file info
lexer_Init();
fstk_Init(mainFileName, maxDepth);
@@ -376,7 +394,7 @@ int main(int argc, char *argv[])
if (failedOnMissingInclude)
return 0;
/* If no path specified, don't write file */
// If no path specified, don't write file
if (objectName != NULL)
out_WriteObject();
return 0;

View File

@@ -1,3 +1,11 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2022, RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
@@ -6,6 +14,7 @@
#include <stdlib.h>
#include <string.h>
#include "asm/fixpoint.h"
#include "asm/fstack.h"
#include "asm/lexer.h"
#include "asm/main.h"
@@ -15,7 +24,8 @@
struct OptStackEntry {
char binary[2];
char gbgfx[4];
int32_t fillByte;
uint8_t fixPrecision;
uint8_t fillByte;
bool haltnop;
bool warnOnHaltNop;
bool optimizeLoads;
@@ -39,9 +49,14 @@ void opt_G(char const chars[4])
lexer_SetGfxDigits(chars);
}
void opt_P(uint8_t fill)
void opt_P(uint8_t padByte)
{
fillByte = fill;
fillByte = padByte;
}
void opt_Q(uint8_t precision)
{
fixPrecision = precision;
}
void opt_R(size_t newDepth)
@@ -95,18 +110,41 @@ void opt_Parse(char *s)
case 'p':
if (strlen(&s[1]) <= 2) {
int result;
unsigned int fillchar;
unsigned int padByte;
result = sscanf(&s[1], "%x", &fillchar);
if (result != EOF && result != 1)
result = sscanf(&s[1], "%x", &padByte);
if (result != 1)
error("Invalid argument for option 'p'\n");
else if (padByte > 0xFF)
error("Argument for option 'p' must be between 0 and 0xFF\n");
else
opt_P(fillchar);
opt_P(padByte);
} else {
error("Invalid argument for option 'p'\n");
}
break;
const char *precisionArg;
case 'Q':
precisionArg = &s[1];
if (precisionArg[0] == '.')
precisionArg++;
if (strlen(precisionArg) <= 2) {
int result;
unsigned int precision;
result = sscanf(precisionArg, "%u", &precision);
if (result != 1)
error("Invalid argument for option 'Q'\n");
else if (precision < 1 || precision > 31)
error("Argument for option 'Q' must be between 1 and 31\n");
else
opt_Q(precision);
} else {
error("Invalid argument for option 'Q'\n");
}
break;
case 'r': {
++s; // Skip 'r'
while (isblank(*s))
@@ -167,6 +205,13 @@ void opt_Parse(char *s)
case '!': // negates flag options that do not take an argument
switch (s[1]) {
case 'H':
if (s[2] == '\0')
opt_H(true);
else
error("Option '!H' does not take an argument\n");
break;
case 'h':
if (s[2] == '\0')
opt_h(true);
@@ -181,6 +226,13 @@ void opt_Parse(char *s)
error("Option '!L' does not take an argument\n");
break;
case 'l':
if (s[2] == '\0')
opt_l(true);
else
error("Option '!l' does not take an argument\n");
break;
default:
error("Unknown option '!%c'\n", s[1]);
break;
@@ -209,6 +261,8 @@ void opt_Push(void)
entry->gbgfx[2] = gfxDigits[2];
entry->gbgfx[3] = gfxDigits[3];
entry->fixPrecision = fixPrecision; // Pulled from fixpoint.h
entry->fillByte = fillByte; // Pulled from section.h
entry->haltnop = haltnop; // Pulled from main.h
@@ -237,6 +291,7 @@ void opt_Pop(void)
opt_B(entry->binary);
opt_G(entry->gbgfx);
opt_P(entry->fillByte);
opt_Q(entry->fixPrecision);
opt_H(entry->warnOnHaltNop);
opt_h(entry->haltnop);
opt_L(entry->optimizeLoads);

View File

@@ -6,9 +6,7 @@
* SPDX-License-Identifier: MIT
*/
/*
* Outputs an objectfile
*/
// Outputs an objectfile
#include <assert.h>
#include <errno.h>
@@ -54,18 +52,16 @@ char *objectName;
struct Section *sectionList;
/* Linked list of symbols to put in the object file */
// Linked list of symbols to put in the object file
static struct Symbol *objectSymbols = NULL;
static struct Symbol **objectSymbolsTail = &objectSymbols;
static uint32_t nbSymbols = 0; /* Length of the above list */
static uint32_t nbSymbols = 0; // Length of the above list
static struct Assertion *assertions = NULL;
static struct FileStackNode *fileStackNodes = NULL;
/*
* Count the number of sections used in this object
*/
// Count the number of sections used in this object
static uint32_t countSections(void)
{
uint32_t count = 0;
@@ -76,9 +72,7 @@ static uint32_t countSections(void)
return count;
}
/*
* Count the number of patches used in this object
*/
// Count the number of patches used in this object
static uint32_t countPatches(struct Section const *sect)
{
uint32_t r = 0;
@@ -90,9 +84,7 @@ static uint32_t countPatches(struct Section const *sect)
return r;
}
/**
* Count the number of assertions used in this object
*/
// Count the number of assertions used in this object
static uint32_t countAsserts(void)
{
struct Assertion *assert = assertions;
@@ -105,9 +97,7 @@ static uint32_t countAsserts(void)
return count;
}
/*
* Write a long to a file (little-endian)
*/
// Write a long to a file (little-endian)
static void putlong(uint32_t i, FILE *f)
{
putc(i, f);
@@ -116,9 +106,7 @@ static void putlong(uint32_t i, FILE *f)
putc(i >> 24, f);
}
/*
* Write a NULL-terminated string to a file
*/
// Write a NULL-terminated string to a file
static void putstring(char const *s, FILE *f)
{
while (*s)
@@ -133,7 +121,7 @@ static uint32_t getNbFileStackNodes(void)
void out_RegisterNode(struct FileStackNode *node)
{
/* If node is not already registered, register it (and parents), and give it a unique ID */
// If node is not already registered, register it (and parents), and give it a unique ID
while (node->ID == (uint32_t)-1) {
node->ID = getNbFileStackNodes();
if (node->ID == (uint32_t)-1)
@@ -141,7 +129,7 @@ void out_RegisterNode(struct FileStackNode *node)
node->next = fileStackNodes;
fileStackNodes = node;
/* Also register the node's parents */
// Also register the node's parents
node = node->parent;
if (!node)
break;
@@ -156,25 +144,21 @@ This is code intended to replace a node, which is pretty useless until ref count
struct FileStackNode **ptr = &fileStackNodes;
/*
* The linked list is supposed to have decrementing IDs, so iterate with less memory reads,
* to hopefully hit the cache less. A debug check is added after, in case a change is made
* that breaks this assumption.
*/
// The linked list is supposed to have decrementing IDs, so iterate with less memory reads,
// to hopefully hit the cache less. A debug check is added after, in case a change is made
// that breaks this assumption.
for (uint32_t i = fileStackNodes->ID; i != node->ID; i--)
ptr = &(*ptr)->next;
assert((*ptr)->ID == node->ID);
node->next = (*ptr)->next;
assert(!node->next || node->next->ID == node->ID - 1); /* Catch inconsistencies early */
/* TODO: unreference the node */
assert(!node->next || node->next->ID == node->ID - 1); // Catch inconsistencies early
// TODO: unreference the node
*ptr = node;
#endif
}
/*
* Return a section's ID
*/
// Return a section's ID
static uint32_t getsectid(struct Section const *sect)
{
struct Section const *sec = sectionList;
@@ -195,9 +179,7 @@ static uint32_t getSectIDIfAny(struct Section const *sect)
return sect ? getsectid(sect) : (uint32_t)-1;
}
/*
* Write a patch to a file
*/
// Write a patch to a file
static void writepatch(struct Patch const *patch, FILE *f)
{
assert(patch->src->ID != (uint32_t)-1);
@@ -211,9 +193,7 @@ static void writepatch(struct Patch const *patch, FILE *f)
fwrite(patch->rpn, 1, patch->rpnSize, f);
}
/*
* Write a section to a file
*/
// Write a section to a file
static void writesection(struct Section const *sect, FILE *f)
{
putstring(sect->name, f);
@@ -255,9 +235,7 @@ static void freesection(struct Section const *sect)
}
}
/*
* Write a symbol to a file
*/
// Write a symbol to a file
static void writesymbol(struct Symbol const *sym, FILE *f)
{
putstring(sym->name, f);
@@ -285,10 +263,8 @@ static void registerSymbol(struct Symbol *sym)
sym->ID = nbSymbols++;
}
/*
* Returns a symbol's ID within the object file
* If the symbol does not have one, one is assigned by registering the symbol
*/
// Returns a symbol's ID within the object file
// If the symbol does not have one, one is assigned by registering the symbol
static uint32_t getSymbolID(struct Symbol *sym)
{
if (sym->ID == (uint32_t)-1 && !sym_IsPC(sym))
@@ -392,10 +368,8 @@ static void writerpn(uint8_t *rpnexpr, uint32_t *rpnptr, uint8_t *rpn,
}
}
/*
* Allocate a new patch structure and link it into the list
* WARNING: all patches are assumed to eventually be written, so the file stack node is registered
*/
// Allocate a new patch structure and link it into the list
// WARNING: all patches are assumed to eventually be written, so the file stack node is registered
static struct Patch *allocpatch(uint32_t type, struct Expression const *expr, uint32_t ofs)
{
struct Patch *patch = malloc(sizeof(struct Patch));
@@ -417,10 +391,10 @@ static struct Patch *allocpatch(uint32_t type, struct Expression const *expr, ui
patch->pcSection = sect_GetSymbolSection();
patch->pcOffset = sect_GetSymbolOffset();
/* If the rpnSize's value is known, output a constant RPN rpnSize directly */
// If the rpnSize's value is known, output a constant RPN rpnSize directly
if (expr->isKnown) {
patch->rpnSize = rpnSize;
/* Make sure to update `rpnSize` above if modifying this! */
// Make sure to update `rpnSize` above if modifying this!
patch->rpn[0] = RPN_CONST;
patch->rpn[1] = (uint32_t)(expr->val) & 0xFF;
patch->rpn[2] = (uint32_t)(expr->val) >> 8;
@@ -435,9 +409,7 @@ static struct Patch *allocpatch(uint32_t type, struct Expression const *expr, ui
return patch;
}
/*
* Create a new patch (includes the rpn expr)
*/
// Create a new patch (includes the rpn expr)
void out_CreatePatch(uint32_t type, struct Expression const *expr, uint32_t ofs, uint32_t pcShift)
{
struct Patch *patch = allocpatch(type, expr, ofs);
@@ -451,9 +423,7 @@ void out_CreatePatch(uint32_t type, struct Expression const *expr, uint32_t ofs,
currentSection->patches = patch;
}
/**
* Creates an assert that will be written to the object file
*/
// Creates an assert that will be written to the object file
bool out_CreateAssert(enum AssertionType type, struct Expression const *expr,
char const *message, uint32_t ofs)
{
@@ -499,7 +469,7 @@ static void writeFileStackNode(struct FileStackNode const *node, FILE *f)
struct FileStackReptNode const *reptNode = (struct FileStackReptNode const *)node;
putlong(reptNode->reptDepth, f);
/* Iters are stored by decreasing depth, so reverse the order for output */
// Iters are stored by decreasing depth, so reverse the order for output
for (uint32_t i = reptNode->reptDepth; i--; )
putlong(reptNode->iters[i], f);
}
@@ -515,9 +485,7 @@ static void registerUnregisteredSymbol(struct Symbol *symbol, void *arg)
}
}
/*
* Write an objectfile
*/
// Write an objectfile
void out_WriteObject(void)
{
FILE *f;
@@ -529,10 +497,10 @@ void out_WriteObject(void)
if (!f)
err("Couldn't write file '%s'", objectName);
/* Also write symbols that weren't written above */
// Also write symbols that weren't written above
sym_ForEach(registerUnregisteredSymbol, NULL);
fprintf(f, RGBDS_OBJECT_VERSION_STRING, RGBDS_OBJECT_VERSION_NUMBER);
fprintf(f, RGBDS_OBJECT_VERSION_STRING);
putlong(RGBDS_OBJECT_REV, f);
putlong(nbSymbols, f);
@@ -569,9 +537,7 @@ void out_WriteObject(void)
fclose(f);
}
/*
* Set the objectfilename
*/
// Set the objectfilename
void out_SetFileName(char *s)
{
objectName = s;

View File

@@ -36,7 +36,7 @@
#include "linkdefs.h"
#include "platform.h" // strncasecmp, strdup
static struct CaptureBody captureBody; /* Captures a REPT/FOR or MACRO */
static struct CaptureBody captureBody; // Captures a REPT/FOR or MACRO
static void upperstring(char *dest, char const *src)
{
@@ -104,14 +104,14 @@ static size_t strlenUTF8(char const *s)
case 1:
errorInvalidUTF8Byte(byte, "STRLEN");
state = 0;
/* fallthrough */
// fallthrough
case 0:
len++;
break;
}
}
/* Check for partial code point. */
// Check for partial code point.
if (state != 0)
error("STRLEN: Incomplete UTF-8 character\n");
@@ -127,13 +127,13 @@ static void strsubUTF8(char *dest, size_t destLen, char const *src, uint32_t pos
uint32_t curLen = 0;
uint32_t curPos = 1;
/* Advance to starting position in source string. */
// Advance to starting position in source string.
while (src[srcIndex] && curPos < pos) {
switch (decode(&state, &codep, src[srcIndex])) {
case 1:
errorInvalidUTF8Byte(src[srcIndex], "STRSUB");
state = 0;
/* fallthrough */
// fallthrough
case 0:
curPos++;
break;
@@ -141,21 +141,19 @@ static void strsubUTF8(char *dest, size_t destLen, char const *src, uint32_t pos
srcIndex++;
}
/*
* A position 1 past the end of the string is allowed, but will trigger the
* "Length too big" warning below if the length is nonzero.
*/
// A position 1 past the end of the string is allowed, but will trigger the
// "Length too big" warning below if the length is nonzero.
if (!src[srcIndex] && pos > curPos)
warning(WARNING_BUILTIN_ARG,
"STRSUB: Position %" PRIu32 " is past the end of the string\n", pos);
/* Copy from source to destination. */
// Copy from source to destination.
while (src[srcIndex] && destIndex < destLen - 1 && curLen < len) {
switch (decode(&state, &codep, src[srcIndex])) {
case 1:
errorInvalidUTF8Byte(src[srcIndex], "STRSUB");
state = 0;
/* fallthrough */
// fallthrough
case 0:
curLen++;
break;
@@ -166,7 +164,7 @@ static void strsubUTF8(char *dest, size_t destLen, char const *src, uint32_t pos
if (curLen < len)
warning(WARNING_BUILTIN_ARG, "STRSUB: Length too big: %" PRIu32 "\n", len);
/* Check for partial code point. */
// Check for partial code point.
if (state != 0)
error("STRSUB: Incomplete UTF-8 character\n");
@@ -187,7 +185,7 @@ static void charsubUTF8(char *dest, char const *src, uint32_t pos)
{
size_t charLen = 1;
/* Advance to starting position in source string. */
// Advance to starting position in source string.
for (uint32_t curPos = 1; charLen && curPos < pos; curPos++)
charLen = charmap_ConvertNext(&src, NULL);
@@ -197,7 +195,7 @@ static void charsubUTF8(char *dest, char const *src, uint32_t pos)
warning(WARNING_BUILTIN_ARG,
"CHARSUB: Position %" PRIu32 " is past the end of the string\n", pos);
/* Copy from source to destination. */
// Copy from source to destination.
memcpy(dest, start, src - start);
dest[src - start] = '\0';
@@ -205,10 +203,8 @@ static void charsubUTF8(char *dest, char const *src, uint32_t pos)
static uint32_t adjustNegativePos(int32_t pos, size_t len, char const *functionName)
{
/*
* STRSUB and CHARSUB adjust negative `pos` arguments the same way,
* such that position -1 is the last character of a string.
*/
// STRSUB and CHARSUB adjust negative `pos` arguments the same way,
// such that position -1 is the last character of a string.
if (pos < 0)
pos += len + 1;
if (pos < 1) {
@@ -545,7 +541,7 @@ enum {
%left T_OP_SHL T_OP_SHR T_OP_USHR
%left T_OP_MUL T_OP_DIV T_OP_MOD
%precedence NEG /* negation -- unary minus */
%precedence NEG // negation -- unary minus
%token T_OP_EXP "**"
%left T_OP_EXP
@@ -558,6 +554,7 @@ enum {
%token T_OP_ASIN "ASIN" T_OP_ACOS "ACOS" T_OP_ATAN "ATAN" T_OP_ATAN2 "ATAN2"
%token T_OP_FDIV "FDIV"
%token T_OP_FMUL "FMUL"
%token T_OP_FMOD "FMOD"
%token T_OP_POW "POW"
%token T_OP_LOG "LOG"
%token T_OP_ROUND "ROUND"
@@ -587,7 +584,6 @@ enum {
%type <symName> scoped_id
%type <symName> scoped_anon_id
%token T_POP_EQU "EQU"
%token T_POP_SET "SET"
%token T_POP_EQUAL "="
%token T_POP_EQUS "EQUS"
@@ -641,7 +637,7 @@ enum {
%type <forArgs> for_args
%token T_Z80_ADC "adc" T_Z80_ADD "add" T_Z80_AND "and"
%token T_Z80_BIT "bit" // There is no T_Z80_SET, only T_POP_SET
%token T_Z80_BIT "bit"
%token T_Z80_CALL "call" T_Z80_CCF "ccf" T_Z80_CP "cp" T_Z80_CPL "cpl"
%token T_Z80_DAA "daa" T_Z80_DEC "dec" T_Z80_DI "di"
%token T_Z80_EI "ei"
@@ -658,7 +654,7 @@ enum {
%token T_Z80_RES "res" T_Z80_RET "ret" T_Z80_RETI "reti" T_Z80_RST "rst"
%token T_Z80_RL "rl" T_Z80_RLA "rla" T_Z80_RLC "rlc" T_Z80_RLCA "rlca"
%token T_Z80_RR "rr" T_Z80_RRA "rra" T_Z80_RRC "rrc" T_Z80_RRCA "rrca"
%token T_Z80_SBC "sbc" T_Z80_SCF "scf" T_Z80_STOP "stop"
%token T_Z80_SBC "sbc" T_Z80_SCF "scf" T_Z80_SET "set" T_Z80_STOP "stop"
%token T_Z80_SLA "sla" T_Z80_SRA "sra" T_Z80_SRL "srl" T_Z80_SUB "sub"
%token T_Z80_SWAP "swap"
%token T_Z80_XOR "xor"
@@ -706,8 +702,8 @@ plain_directive : label
;
line : plain_directive endofline
| line_directive /* Directives that manage newlines themselves */
/* Continue parsing the next line on a syntax error */
| line_directive // Directives that manage newlines themselves
// Continue parsing the next line on a syntax error
| error {
lexer_SetMode(LEXER_NORMAL);
lexer_ToggleStringExpansion(true);
@@ -715,7 +711,7 @@ line : plain_directive endofline
fstk_StopRept();
yyerrok;
}
/* Hint about unindented macros parsed as labels */
// Hint about unindented macros parsed as labels
| T_LABEL error {
lexer_SetMode(LEXER_NORMAL);
lexer_ToggleStringExpansion(true);
@@ -730,19 +726,17 @@ line : plain_directive endofline
}
;
/*
* For "logistical" reasons, these directives must manage newlines themselves.
* This is because we need to switch the lexer's mode *after* the newline has been read,
* and to avoid causing some grammar conflicts (token reducing is finicky).
* This is DEFINITELY one of the more FRAGILE parts of the codebase, handle with care.
*/
// For "logistical" reasons, these directives must manage newlines themselves.
// This is because we need to switch the lexer's mode *after* the newline has been read,
// and to avoid causing some grammar conflicts (token reducing is finicky).
// This is DEFINITELY one of the more FRAGILE parts of the codebase, handle with care.
line_directive : macrodef
| rept
| for
| break
| include
| if
/* It's important that all of these require being at line start for `skipIfBlock` */
// It's important that all of these require being at line start for `skipIfBlock`
| elif
| else
;
@@ -853,7 +847,7 @@ macroargs : %empty {
}
;
/* These commands start with a T_LABEL. */
// These commands start with a T_LABEL.
assignment_directive : equ
| assignment
| rb
@@ -1099,6 +1093,7 @@ macrodef : T_POP_MACRO {
captureBody.size);
}
| T_LABEL T_COLON T_POP_MACRO T_NEWLINE {
warning(WARNING_OBSOLETE, "`%s: MACRO` is deprecated; use `MACRO %s`\n", $1, $1);
$<captureTerminated>$ = lexer_CaptureMacroBody(&captureBody);
} endofline {
if ($<captureTerminated>5)
@@ -1298,7 +1293,7 @@ constlist_8bit_entry : reloc_8bit_no_str {
sect_RelByte(&$1, 0);
}
| string {
uint8_t *output = malloc(strlen($1)); /* Cannot be larger than that */
uint8_t *output = malloc(strlen($1)); // Cannot be larger than that
size_t length = charmap_Convert($1, output);
sect_AbsByteGroup(output, length);
@@ -1314,7 +1309,7 @@ constlist_16bit_entry : reloc_16bit_no_str {
sect_RelWord(&$1, 0);
}
| string {
uint8_t *output = malloc(strlen($1)); /* Cannot be larger than that */
uint8_t *output = malloc(strlen($1)); // Cannot be larger than that
size_t length = charmap_Convert($1, output);
sect_AbsWordGroup(output, length);
@@ -1488,6 +1483,9 @@ relocexpr_no_str : scoped_anon_id { rpn_Symbol(&$$, $1); }
| T_OP_FMUL T_LPAREN const T_COMMA const T_RPAREN {
rpn_Number(&$$, fix_Mul($3, $5));
}
| T_OP_FMOD T_LPAREN const T_COMMA const T_RPAREN {
rpn_Number(&$$, fix_Mod($3, $5));
}
| T_OP_POW T_LPAREN const T_COMMA const T_RPAREN {
rpn_Number(&$$, fix_Pow($3, $5));
}
@@ -1676,7 +1674,7 @@ sectattrs : %empty {
$$.alignOfs = $7;
}
| sectattrs T_COMMA T_OP_BANK T_LBRACK uconst T_RBRACK {
/* We cannot check the validity of this now */
// We cannot check the validity of this now
$$.bank = $5;
}
;
@@ -1993,10 +1991,8 @@ z80_ld_ss : T_Z80_LD T_MODE_BC T_COMMA reloc_16bit {
sect_AbsByte(0x01 | (REG_DE << 4));
sect_RelWord(&$4, 1);
}
/*
* HL is taken care of in z80_ld_hl
* SP is taken care of in z80_ld_sp
*/
// HL is taken care of in z80_ld_hl
// SP is taken care of in z80_ld_sp
;
z80_nop : T_Z80_NOP { sect_AbsByte(0x00); }
@@ -2084,7 +2080,7 @@ z80_sbc : T_Z80_SBC op_a_n {
z80_scf : T_Z80_SCF { sect_AbsByte(0x37); }
;
z80_set : T_POP_SET const_3bit T_COMMA reg_r {
z80_set : T_Z80_SET const_3bit T_COMMA reg_r {
sect_AbsByte(0xCB);
sect_AbsByte(0xC0 | ($2 << 3) | $4);
}

View File

@@ -6,9 +6,7 @@
* SPDX-License-Identifier: MIT
*/
/*
* Controls RPN expressions for objectfiles
*/
// Controls RPN expressions for objectfiles
#include <assert.h>
#include <errno.h>
@@ -28,7 +26,7 @@
#include "opmath.h"
/* Makes an expression "not known", also setting its error message */
// Makes an expression "not known", also setting its error message
#define makeUnknown(expr_, ...) do { \
struct Expression *_expr = expr_; \
_expr->isKnown = false; \
@@ -47,17 +45,15 @@
static uint8_t *reserveSpace(struct Expression *expr, uint32_t size)
{
/* This assumes the RPN length is always less than the capacity */
// This assumes the RPN length is always less than the capacity
if (expr->rpnCapacity - expr->rpnLength < size) {
/* If there isn't enough room to reserve the space, realloc */
// If there isn't enough room to reserve the space, realloc
if (!expr->rpn)
expr->rpnCapacity = 256; /* Initial size */
expr->rpnCapacity = 256; // Initial size
while (expr->rpnCapacity - expr->rpnLength < size) {
if (expr->rpnCapacity >= MAXRPNLEN)
/*
* To avoid generating humongous object files, cap the
* size of RPN expressions
*/
// To avoid generating humongous object files, cap the
// size of RPN expressions
fatalerror("RPN expression cannot grow larger than "
EXPAND_AND_STR(MAXRPNLEN) " bytes\n");
else if (expr->rpnCapacity > MAXRPNLEN / 2)
@@ -77,9 +73,7 @@ static uint8_t *reserveSpace(struct Expression *expr, uint32_t size)
return ptr;
}
/*
* Init a RPN expression
*/
// Init a RPN expression
static void rpn_Init(struct Expression *expr)
{
expr->reason = NULL;
@@ -91,9 +85,7 @@ static void rpn_Init(struct Expression *expr)
expr->rpnPatchSize = 0;
}
/*
* Free the RPN expression
*/
// Free the RPN expression
void rpn_Free(struct Expression *expr)
{
free(expr->rpn);
@@ -101,9 +93,7 @@ void rpn_Free(struct Expression *expr)
rpn_Init(expr);
}
/*
* Add symbols, constants and operators to expression
*/
// Add symbols, constants and operators to expression
void rpn_Number(struct Expression *expr, uint32_t i)
{
rpn_Init(expr);
@@ -124,9 +114,9 @@ void rpn_Symbol(struct Expression *expr, char const *symName)
makeUnknown(expr, sym_IsPC(sym) ? "PC is not constant at assembly time"
: "'%s' is not constant at assembly time", symName);
sym = sym_Ref(symName);
expr->rpnPatchSize += 5; /* 1-byte opcode + 4-byte symbol ID */
expr->rpnPatchSize += 5; // 1-byte opcode + 4-byte symbol ID
size_t nameLen = strlen(sym->name) + 1; /* Don't forget NUL! */
size_t nameLen = strlen(sym->name) + 1; // Don't forget NUL!
uint8_t *ptr = reserveSpace(expr, nameLen + 1);
*ptr++ = RPN_SYM;
memcpy(ptr, sym->name, nameLen);
@@ -155,7 +145,7 @@ void rpn_BankSymbol(struct Expression *expr, char const *symName)
{
struct Symbol const *sym = sym_FindScopedSymbol(symName);
/* The @ symbol is treated differently. */
// The @ symbol is treated differently.
if (sym_IsPC(sym)) {
rpn_BankSelf(expr);
return;
@@ -169,13 +159,13 @@ void rpn_BankSymbol(struct Expression *expr, char const *symName)
assert(sym); // If the symbol didn't exist, it should have been created
if (sym_GetSection(sym) && sym_GetSection(sym)->bank != (uint32_t)-1) {
/* Symbol's section is known and bank is fixed */
// Symbol's section is known and bank is fixed
expr->val = sym_GetSection(sym)->bank;
} else {
makeUnknown(expr, "\"%s\"'s bank is not known", symName);
expr->rpnPatchSize += 5; /* opcode + 4-byte sect ID */
expr->rpnPatchSize += 5; // opcode + 4-byte sect ID
size_t nameLen = strlen(sym->name) + 1; /* Room for NUL! */
size_t nameLen = strlen(sym->name) + 1; // Room for NUL!
uint8_t *ptr = reserveSpace(expr, nameLen + 1);
*ptr++ = RPN_BANK_SYM;
memcpy(ptr, sym->name, nameLen);
@@ -194,7 +184,7 @@ void rpn_BankSection(struct Expression *expr, char const *sectionName)
} else {
makeUnknown(expr, "Section \"%s\"'s bank is not known", sectionName);
size_t nameLen = strlen(sectionName) + 1; /* Room for NUL! */
size_t nameLen = strlen(sectionName) + 1; // Room for NUL!
uint8_t *ptr = reserveSpace(expr, nameLen + 1);
expr->rpnPatchSize += nameLen + 1;
@@ -214,7 +204,7 @@ void rpn_SizeOfSection(struct Expression *expr, char const *sectionName)
} else {
makeUnknown(expr, "Section \"%s\"'s size is not known", sectionName);
size_t nameLen = strlen(sectionName) + 1; /* Room for NUL! */
size_t nameLen = strlen(sectionName) + 1; // Room for NUL!
uint8_t *ptr = reserveSpace(expr, nameLen + 1);
expr->rpnPatchSize += nameLen + 1;
@@ -234,7 +224,7 @@ void rpn_StartOfSection(struct Expression *expr, char const *sectionName)
} else {
makeUnknown(expr, "Section \"%s\"'s start is not known", sectionName);
size_t nameLen = strlen(sectionName) + 1; /* Room for NUL! */
size_t nameLen = strlen(sectionName) + 1; // Room for NUL!
uint8_t *ptr = reserveSpace(expr, nameLen + 1);
expr->rpnPatchSize += nameLen + 1;
@@ -252,7 +242,7 @@ void rpn_CheckHRAM(struct Expression *expr, const struct Expression *src)
expr->rpnPatchSize++;
*reserveSpace(expr, 1) = RPN_HRAM;
} else if (expr->val >= 0xFF00 && expr->val <= 0xFFFF) {
/* That range is valid, but only keep the lower byte */
// That range is valid, but only keep the lower byte
expr->val &= 0xFF;
} else if (expr->val < 0 || expr->val > 0xFF) {
error("Source address $%" PRIx32 " not between $FF00 to $FFFF\n", expr->val);
@@ -264,10 +254,10 @@ void rpn_CheckRST(struct Expression *expr, const struct Expression *src)
*expr = *src;
if (rpn_isKnown(expr)) {
/* A valid RST address must be masked with 0x38 */
// A valid RST address must be masked with 0x38
if (expr->val & ~0x38)
error("Invalid address $%" PRIx32 " for RST\n", expr->val);
/* The target is in the "0x38" bits, all other bits are set */
// The target is in the "0x38" bits, all other bits are set
expr->val |= 0xC7;
} else {
expr->rpnPatchSize++;
@@ -275,9 +265,7 @@ void rpn_CheckRST(struct Expression *expr, const struct Expression *src)
}
}
/*
* Checks that an RPN expression's value fits within N bits (signed or unsigned)
*/
// Checks that an RPN expression's value fits within N bits (signed or unsigned)
void rpn_CheckNBit(struct Expression const *expr, uint8_t n)
{
assert(n != 0); // That doesn't make sense
@@ -324,7 +312,7 @@ struct Symbol const *rpn_SymbolOf(struct Expression const *expr)
bool rpn_IsDiffConstant(struct Expression const *src, struct Symbol const *sym)
{
/* Check if both expressions only refer to a single symbol */
// Check if both expressions only refer to a single symbol
struct Symbol const *sym1 = rpn_SymbolOf(src);
if (!sym1 || !sym || sym1->type != SYM_LABEL || sym->type != SYM_LABEL)
@@ -341,7 +329,7 @@ static bool isDiffConstant(struct Expression const *src1,
return rpn_IsDiffConstant(src1, rpn_SymbolOf(src2));
}
/**
/*
* Attempts to compute a constant binary AND from non-constant operands
* This is possible if one operand is a symbol belonging to an `ALIGN[N]` section, and the other is
* a constant that only keeps (some of) the lower N bits.
@@ -387,12 +375,12 @@ void rpn_BinaryOp(enum RPNCommand op, struct Expression *expr,
expr->isSymbol = false;
int32_t constMaskVal;
/* First, check if the expression is known */
// First, check if the expression is known
expr->isKnown = src1->isKnown && src2->isKnown;
if (expr->isKnown) {
rpn_Init(expr); /* Init the expression to something sane */
rpn_Init(expr); // Init the expression to something sane
/* If both expressions are known, just compute the value */
// If both expressions are known, just compute the value
uint32_t uleft = src1->val, uright = src2->val;
switch (op) {
@@ -537,9 +525,9 @@ void rpn_BinaryOp(enum RPNCommand op, struct Expression *expr,
expr->val = constMaskVal;
expr->isKnown = true;
} else {
/* If it's not known, start computing the RPN expression */
// If it's not known, start computing the RPN expression
/* Convert the left-hand expression if it's constant */
// Convert the left-hand expression if it's constant
if (src1->isKnown) {
uint32_t lval = src1->val;
uint8_t bytes[] = {RPN_CONST, lval, lval >> 8,
@@ -551,11 +539,11 @@ void rpn_BinaryOp(enum RPNCommand op, struct Expression *expr,
memcpy(reserveSpace(expr, sizeof(bytes)), bytes,
sizeof(bytes));
/* Use the other expression's un-const reason */
// Use the other expression's un-const reason
expr->reason = src2->reason;
free(src1->reason);
} else {
/* Otherwise just reuse its RPN buffer */
// Otherwise just reuse its RPN buffer
expr->rpnPatchSize = src1->rpnPatchSize;
expr->rpn = src1->rpn;
expr->rpnCapacity = src1->rpnCapacity;
@@ -564,12 +552,12 @@ void rpn_BinaryOp(enum RPNCommand op, struct Expression *expr,
free(src2->reason);
}
/* Now, merge the right expression into the left one */
uint8_t *ptr = src2->rpn; /* Pointer to the right RPN */
uint32_t len = src2->rpnLength; /* Size of the right RPN */
// Now, merge the right expression into the left one
uint8_t *ptr = src2->rpn; // Pointer to the right RPN
uint32_t len = src2->rpnLength; // Size of the right RPN
uint32_t patchSize = src2->rpnPatchSize;
/* If the right expression is constant, merge a shim instead */
// If the right expression is constant, merge a shim instead
uint32_t rval = src2->val;
uint8_t bytes[] = {RPN_CONST, rval, rval >> 8, rval >> 16,
rval >> 24};
@@ -578,13 +566,13 @@ void rpn_BinaryOp(enum RPNCommand op, struct Expression *expr,
len = sizeof(bytes);
patchSize = sizeof(bytes);
}
/* Copy the right RPN and append the operator */
// Copy the right RPN and append the operator
uint8_t *buf = reserveSpace(expr, len + 1);
memcpy(buf, ptr, len);
buf[len] = op;
free(src2->rpn); /* If there was none, this is `free(NULL)` */
free(src2->rpn); // If there was none, this is `free(NULL)`
expr->rpnPatchSize += patchSize + 1;
}
}

View File

@@ -1,3 +1,10 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2022, RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#include <assert.h>
#include <errno.h>
@@ -16,6 +23,7 @@
#include "asm/warning.h"
#include "error.h"
#include "linkdefs.h"
#include "platform.h" // strdup
uint8_t fillByte;
@@ -29,7 +37,7 @@ struct UnionStackEntry {
struct SectionStackEntry {
struct Section *section;
struct Section *loadSection;
char const *scope; /* Section's symbol scope */
char const *scope; // Section's symbol scope
uint32_t offset;
int32_t loadOffset;
struct UnionStackEntry *unionStack;
@@ -37,14 +45,12 @@ struct SectionStackEntry {
};
struct SectionStackEntry *sectionStack;
uint32_t curOffset; /* Offset into the current section (see sect_GetSymbolOffset) */
uint32_t curOffset; // Offset into the current section (see sect_GetSymbolOffset)
struct Section *currentSection = NULL;
static struct Section *currentLoadSection = NULL;
int32_t loadOffset; /* Offset into the LOAD section's parent (see sect_GetOutputOffset) */
int32_t loadOffset; // Offset into the LOAD section's parent (see sect_GetOutputOffset)
/*
* A quick check to see if we have an initialized section
*/
// A quick check to see if we have an initialized section
attr_(warn_unused_result) static bool checksection(void)
{
if (currentSection)
@@ -54,10 +60,8 @@ attr_(warn_unused_result) static bool checksection(void)
return false;
}
/*
* A quick check to see if we have an initialized section that can contain
* this much initialized data
*/
// A quick check to see if we have an initialized section that can contain
// this much initialized data
attr_(warn_unused_result) static bool checkcodesection(void)
{
if (!checksection())
@@ -73,7 +77,7 @@ attr_(warn_unused_result) static bool checkcodesection(void)
attr_(warn_unused_result) static bool checkSectionSize(struct Section const *sect, uint32_t size)
{
uint32_t maxSize = maxsize[sect->type];
uint32_t maxSize = sectionTypeInfo[sect->type].size;
// If the new size is reasonable, keep going
if (size <= maxSize)
@@ -84,17 +88,13 @@ attr_(warn_unused_result) static bool checkSectionSize(struct Section const *sec
return false;
}
/*
* Check if the section has grown too much.
*/
// Check if the section has grown too much.
attr_(warn_unused_result) static bool reserveSpace(uint32_t delta_size)
{
/*
* This check is here to trap broken code that generates sections that are too big and to
* prevent the assembler from generating huge object files or trying to allocate too much
* memory.
* A check at the linking stage is still necessary.
*/
// This check is here to trap broken code that generates sections that are too big and to
// prevent the assembler from generating huge object files or trying to allocate too much
// memory.
// A check at the linking stage is still necessary.
// If the section has already overflowed, skip the check to avoid erroring out ad nauseam
if (currentSection->size != UINT32_MAX
@@ -132,15 +132,13 @@ static unsigned int mergeSectUnion(struct Section *sect, enum SectionType type,
assert(alignment < 16); // Should be ensured by the caller
unsigned int nbSectErrors = 0;
/*
* Unionized sections only need "compatible" constraints, and they end up with the strictest
* combination of both.
*/
// Unionized sections only need "compatible" constraints, and they end up with the strictest
// combination of both.
if (sect_HasData(type))
fail("Cannot declare ROM sections as UNION\n");
if (org != (uint32_t)-1) {
/* If both are fixed, they must be the same */
// If both are fixed, they must be the same
if (sect->org != (uint32_t)-1 && sect->org != org)
fail("Section already declared as fixed at different address $%04"
PRIx32 "\n", sect->org);
@@ -148,16 +146,16 @@ static unsigned int mergeSectUnion(struct Section *sect, enum SectionType type,
fail("Section already declared as aligned to %u bytes (offset %"
PRIu16 ")\n", 1U << sect->align, sect->alignOfs);
else
/* Otherwise, just override */
// Otherwise, just override
sect->org = org;
} else if (alignment != 0) {
/* Make sure any fixed address given is compatible */
// Make sure any fixed address given is compatible
if (sect->org != (uint32_t)-1) {
if ((sect->org - alignOffset) & mask(alignment))
fail("Section already declared as fixed at incompatible address $%04"
PRIx32 "\n", sect->org);
/* Check if alignment offsets are compatible */
// Check if alignment offsets are compatible
} else if ((alignOffset & mask(sect->align))
!= (sect->alignOfs & mask(alignment))) {
fail("Section already declared with incompatible %u"
@@ -180,15 +178,13 @@ static unsigned int mergeFragments(struct Section *sect, enum SectionType type,
assert(alignment < 16); // Should be ensured by the caller
unsigned int nbSectErrors = 0;
/*
* Fragments only need "compatible" constraints, and they end up with the strictest
* combination of both.
* The merging is however performed at the *end* of the original section!
*/
// Fragments only need "compatible" constraints, and they end up with the strictest
// combination of both.
// The merging is however performed at the *end* of the original section!
if (org != (uint32_t)-1) {
uint16_t curOrg = org - sect->size;
/* If both are fixed, they must be the same */
// If both are fixed, they must be the same
if (sect->org != (uint32_t)-1 && sect->org != curOrg)
fail("Section already declared as fixed at incompatible address $%04"
PRIx32 " (cur addr = %04" PRIx32 ")\n",
@@ -197,7 +193,7 @@ static unsigned int mergeFragments(struct Section *sect, enum SectionType type,
fail("Section already declared as aligned to %u bytes (offset %"
PRIu16 ")\n", 1U << sect->align, sect->alignOfs);
else
/* Otherwise, just override */
// Otherwise, just override
sect->org = curOrg;
} else if (alignment != 0) {
@@ -206,12 +202,12 @@ static unsigned int mergeFragments(struct Section *sect, enum SectionType type,
if (curOfs < 0)
curOfs += 1U << alignment;
/* Make sure any fixed address given is compatible */
// Make sure any fixed address given is compatible
if (sect->org != (uint32_t)-1) {
if ((sect->org - curOfs) & mask(alignment))
fail("Section already declared as fixed at incompatible address $%04"
PRIx32 "\n", sect->org);
/* Check if alignment offsets are compatible */
// Check if alignment offsets are compatible
} else if ((curOfs & mask(sect->align)) != (sect->alignOfs & mask(alignment))) {
fail("Section already declared with incompatible %u"
"-byte alignment (offset %" PRIu16 ")\n",
@@ -232,7 +228,7 @@ static void mergeSections(struct Section *sect, enum SectionType type, uint32_t
unsigned int nbSectErrors = 0;
if (type != sect->type)
fail("Section already exists but with type %s\n", typeNames[sect->type]);
fail("Section already exists but with type %s\n", sectionTypeInfo[sect->type].name);
if (sect->modifier != mod) {
fail("Section already declared as %s section\n", sectionModNames[sect->modifier]);
@@ -245,10 +241,10 @@ static void mergeSections(struct Section *sect, enum SectionType type, uint32_t
// Common checks
/* If the section's bank is unspecified, override it */
// If the section's bank is unspecified, override it
if (sect->bank == (uint32_t)-1)
sect->bank = bank;
/* If both specify a bank, it must be the same one */
// If both specify a bank, it must be the same one
else if (bank != (uint32_t)-1 && sect->bank != bank)
fail("Section already declared with different bank %" PRIu32 "\n",
sect->bank);
@@ -269,9 +265,7 @@ static void mergeSections(struct Section *sect, enum SectionType type, uint32_t
#undef fail
/*
* Create a new section, not yet in the list.
*/
// Create a new section, not yet in the list.
static struct Section *createSection(char const *name, enum SectionType type,
uint32_t org, uint32_t bank, uint8_t alignment,
uint16_t alignOffset, enum SectionModifier mod)
@@ -297,9 +291,9 @@ static struct Section *createSection(char const *name, enum SectionType type,
sect->next = NULL;
sect->patches = NULL;
/* It is only needed to allocate memory for ROM sections. */
// It is only needed to allocate memory for ROM sections.
if (sect_HasData(type)) {
sect->data = malloc(maxsize[type]);
sect->data = malloc(sectionTypeInfo[type].size);
if (sect->data == NULL)
fatalerror("Not enough memory for section: %s\n", strerror(errno));
} else {
@@ -309,9 +303,7 @@ static struct Section *createSection(char const *name, enum SectionType type,
return sect;
}
/*
* Find a section by name and type. If it doesn't exist, create it.
*/
// Find a section by name and type. If it doesn't exist, create it.
static struct Section *getSection(char const *name, enum SectionType type, uint32_t org,
struct SectionSpec const *attrs, enum SectionModifier mod)
{
@@ -325,14 +317,13 @@ static struct Section *getSection(char const *name, enum SectionType type, uint3
if (type != SECTTYPE_ROMX && type != SECTTYPE_VRAM
&& type != SECTTYPE_SRAM && type != SECTTYPE_WRAMX)
error("BANK only allowed for ROMX, WRAMX, SRAM, or VRAM sections\n");
else if (bank < bankranges[type][0]
|| bank > bankranges[type][1])
else if (bank < sectionTypeInfo[type].firstBank || bank > sectionTypeInfo[type].lastBank)
error("%s bank value $%04" PRIx32 " out of range ($%04" PRIx32 " to $%04"
PRIx32 ")\n", typeNames[type], bank,
bankranges[type][0], bankranges[type][1]);
PRIx32 ")\n", sectionTypeInfo[type].name, bank,
sectionTypeInfo[type].firstBank, sectionTypeInfo[type].lastBank);
} else if (nbbanks(type) == 1) {
// If the section type only has a single bank, implicitly force it
bank = bankranges[type][0];
bank = sectionTypeInfo[type].firstBank;
}
if (alignOffset >= 1 << alignment) {
@@ -342,10 +333,10 @@ static struct Section *getSection(char const *name, enum SectionType type, uint3
}
if (org != (uint32_t)-1) {
if (org < startaddr[type] || org > endaddr(type))
if (org < sectionTypeInfo[type].startAddr || org > endaddr(type))
error("Section \"%s\"'s fixed address %#" PRIx32
" is outside of range [%#" PRIx16 "; %#" PRIx16 "]\n",
name, org, startaddr[type], endaddr(type));
name, org, sectionTypeInfo[type].startAddr, endaddr(type));
}
if (alignment != 0) {
@@ -353,18 +344,18 @@ static struct Section *getSection(char const *name, enum SectionType type, uint3
error("Alignment must be between 0 and 16, not %u\n", alignment);
alignment = 16;
}
/* It doesn't make sense to have both alignment and org set */
// It doesn't make sense to have both alignment and org set
uint32_t mask = mask(alignment);
if (org != (uint32_t)-1) {
if ((org - alignOffset) & mask)
error("Section \"%s\"'s fixed address doesn't match its alignment\n",
name);
alignment = 0; /* Ignore it if it's satisfied */
} else if (startaddr[type] & mask) {
alignment = 0; // Ignore it if it's satisfied
} else if (sectionTypeInfo[type].startAddr & mask) {
error("Section \"%s\"'s alignment cannot be attained in %s\n",
name, typeNames[type]);
alignment = 0; /* Ignore it if it's unattainable */
name, sectionTypeInfo[type].name);
alignment = 0; // Ignore it if it's unattainable
org = 0;
} else if (alignment == 16) {
// Treat an alignment of 16 as being fixed at address 0
@@ -390,9 +381,7 @@ static struct Section *getSection(char const *name, enum SectionType type, uint3
return sect;
}
/*
* Set the current section
*/
// Set the current section
static void changeSection(void)
{
if (unionStack)
@@ -401,9 +390,7 @@ static void changeSection(void)
sym_SetCurrentSymbolScope(NULL);
}
/*
* Set the current section by name and type
*/
// Set the current section by name and type
void sect_NewSection(char const *name, uint32_t type, uint32_t org,
struct SectionSpec const *attribs, enum SectionModifier mod)
{
@@ -423,9 +410,7 @@ void sect_NewSection(char const *name, uint32_t type, uint32_t org,
currentSection = sect;
}
/*
* Set the current section by name and type
*/
// Set the current section by name and type
void sect_SetLoadSection(char const *name, uint32_t type, uint32_t org,
struct SectionSpec const *attribs, enum SectionModifier mod)
{
@@ -478,9 +463,7 @@ struct Section *sect_GetSymbolSection(void)
return currentLoadSection ? currentLoadSection : currentSection;
}
/*
* The offset into the section above
*/
// The offset into the section above
uint32_t sect_GetSymbolOffset(void)
{
return curOffset;
@@ -615,9 +598,7 @@ void sect_CheckUnionClosed(void)
error("Unterminated UNION construct!\n");
}
/*
* Output an absolute byte
*/
// Output an absolute byte
void sect_AbsByte(uint8_t b)
{
if (!checkcodesection())
@@ -661,9 +642,7 @@ void sect_AbsLongGroup(uint8_t const *s, size_t length)
writelong(*s++);
}
/*
* Skip this many bytes
*/
// Skip this many bytes
void sect_Skip(uint32_t skip, bool ds)
{
if (!checksection())
@@ -683,9 +662,7 @@ void sect_Skip(uint32_t skip, bool ds)
}
}
/*
* Output a NULL terminated string (excluding the NULL-character)
*/
// Output a NULL terminated string (excluding the NULL-character)
void sect_String(char const *s)
{
if (!checkcodesection())
@@ -697,10 +674,8 @@ void sect_String(char const *s)
writebyte(*s++);
}
/*
* Output a relocatable byte. Checking will be done to see if it
* is an absolute value in disguise.
*/
// Output a relocatable byte. Checking will be done to see if it
// is an absolute value in disguise.
void sect_RelByte(struct Expression *expr, uint32_t pcShift)
{
if (!checkcodesection())
@@ -717,10 +692,8 @@ void sect_RelByte(struct Expression *expr, uint32_t pcShift)
rpn_Free(expr);
}
/*
* Output several copies of a relocatable byte. Checking will be done to see if
* it is an absolute value in disguise.
*/
// Output several copies of a relocatable byte. Checking will be done to see if
// it is an absolute value in disguise.
void sect_RelBytes(uint32_t n, struct Expression *exprs, size_t size)
{
if (!checkcodesection())
@@ -743,10 +716,8 @@ void sect_RelBytes(uint32_t n, struct Expression *exprs, size_t size)
rpn_Free(&exprs[i]);
}
/*
* Output a relocatable word. Checking will be done to see if
* it's an absolute value in disguise.
*/
// Output a relocatable word. Checking will be done to see if
// it's an absolute value in disguise.
void sect_RelWord(struct Expression *expr, uint32_t pcShift)
{
if (!checkcodesection())
@@ -763,10 +734,8 @@ void sect_RelWord(struct Expression *expr, uint32_t pcShift)
rpn_Free(expr);
}
/*
* Output a relocatable longword. Checking will be done to see if
* is an absolute value in disguise.
*/
// Output a relocatable longword. Checking will be done to see if
// is an absolute value in disguise.
void sect_RelLong(struct Expression *expr, uint32_t pcShift)
{
if (!checkcodesection())
@@ -783,10 +752,8 @@ void sect_RelLong(struct Expression *expr, uint32_t pcShift)
rpn_Free(expr);
}
/*
* Output a PC-relative relocatable byte. Checking will be done to see if it
* is an absolute value in disguise.
*/
// Output a PC-relative relocatable byte. Checking will be done to see if it
// is an absolute value in disguise.
void sect_PCRelByte(struct Expression *expr, uint32_t pcShift)
{
if (!checkcodesection())
@@ -800,12 +767,12 @@ void sect_PCRelByte(struct Expression *expr, uint32_t pcShift)
writebyte(0);
} else {
struct Symbol const *sym = rpn_SymbolOf(expr);
/* The offset wraps (jump from ROM to HRAM, for example) */
// The offset wraps (jump from ROM to HRAM, for example)
int16_t offset;
/* Offset is relative to the byte *after* the operand */
// Offset is relative to the byte *after* the operand
if (sym == pc)
offset = -2; /* PC as operand to `jr` is lower than reference PC by 2 */
offset = -2; // PC as operand to `jr` is lower than reference PC by 2
else
offset = sym_GetValue(sym) - (sym_GetValue(pc) + 1);
@@ -820,9 +787,7 @@ void sect_PCRelByte(struct Expression *expr, uint32_t pcShift)
rpn_Free(expr);
}
/*
* Output a binary file
*/
// Output a binary file
void sect_BinaryFile(char const *s, int32_t startPos)
{
if (startPos < 0) {
@@ -869,7 +834,7 @@ void sect_BinaryFile(char const *s, int32_t startPos)
if (errno != ESPIPE)
error("Error determining size of INCBIN file '%s': %s\n",
s, strerror(errno));
/* The file isn't seekable, so we'll just skip bytes */
// The file isn't seekable, so we'll just skip bytes
while (startPos--)
(void)fgetc(f);
}
@@ -901,7 +866,7 @@ void sect_BinaryFileSlice(char const *s, int32_t start_pos, int32_t length)
if (!checkcodesection())
return;
if (length == 0) /* Don't even bother with 0-byte slices */
if (length == 0) // Don't even bother with 0-byte slices
return;
if (!reserveSpace(length))
return;
@@ -946,7 +911,7 @@ void sect_BinaryFileSlice(char const *s, int32_t start_pos, int32_t length)
if (errno != ESPIPE)
error("Error determining size of INCBIN file '%s': %s\n",
s, strerror(errno));
/* The file isn't seekable, so we'll just skip bytes */
// The file isn't seekable, so we'll just skip bytes
while (start_pos--)
(void)fgetc(f);
}
@@ -968,9 +933,7 @@ cleanup:
fclose(f);
}
/*
* Section stack routines
*/
// Section stack routines
void sect_PushSection(void)
{
struct SectionStackEntry *entry = malloc(sizeof(*entry));

View File

@@ -6,9 +6,7 @@
* SPDX-License-Identifier: MIT
*/
/*
* Symboltable and macroargs stuff
*/
// Symboltable and macroargs stuff
#include <assert.h>
#include <errno.h>
@@ -36,7 +34,7 @@
HashMap symbols;
static char const *labelScope; /* Current section's label scope */
static const char *labelScope; // Current section's label scope
static struct Symbol *PCSymbol;
static char savedTIME[256];
static char savedDATE[256];
@@ -85,36 +83,34 @@ static int32_t Callback__LINE__(void)
static char const *Callback__FILE__(void)
{
/*
* FIXME: this is dangerous, and here's why this is CURRENTLY okay. It's still bad, fix it.
* There are only two call sites for this; one copies the contents directly, the other is
* EQUS expansions, which cannot straddle file boundaries. So this should be fine.
*/
// FIXME: this is dangerous, and here's why this is CURRENTLY okay. It's still bad, fix it.
// There are only two call sites for this; one copies the contents directly, the other is
// EQUS expansions, which cannot straddle file boundaries. So this should be fine.
static char *buf = NULL;
static size_t bufsize = 0;
char const *fileName = fstk_GetFileName();
size_t j = 1;
assert(fileName[0]);
/* The assertion above ensures the loop runs at least once */
// The assertion above ensures the loop runs at least once
for (size_t i = 0; fileName[i]; i++, j++) {
/* Account for the extra backslash inserted below */
// Account for the extra backslash inserted below
if (fileName[i] == '"')
j++;
/* Ensure there will be enough room; DO NOT PRINT ANYTHING ABOVE THIS!! */
if (j + 2 >= bufsize) { /* Always keep room for 2 tail chars */
// Ensure there will be enough room; DO NOT PRINT ANYTHING ABOVE THIS!!
if (j + 2 >= bufsize) { // Always keep room for 2 tail chars
bufsize = bufsize ? bufsize * 2 : 64;
buf = realloc(buf, bufsize);
if (!buf)
fatalerror("Failed to grow buffer for file name: %s\n",
strerror(errno));
}
/* Escape quotes, since we're returning a string */
// Escape quotes, since we're returning a string
if (fileName[i] == '"')
buf[j - 1] = '\\';
buf[j] = fileName[i];
}
/* Write everything after the loop, to ensure the buffer has been allocated */
// Write everything after the loop, to ensure the buffer has been allocated
buf[0] = '"';
buf[j++] = '"';
buf[j] = '\0';
@@ -128,16 +124,14 @@ static int32_t CallbackPC(void)
return section ? section->org + sect_GetSymbolOffset() : 0;
}
/*
* Get the value field of a symbol
*/
// Get the value field of a symbol
int32_t sym_GetValue(struct Symbol const *sym)
{
if (sym_IsNumeric(sym) && sym->hasCallback)
return sym->numCallback();
if (sym->type == SYM_LABEL)
/* TODO: do not use section's org directly */
// TODO: do not use section's org directly
return sym->value + sym_GetSection(sym)->org;
return sym->value;
@@ -153,32 +147,26 @@ static void dumpFilename(struct Symbol const *sym)
fputs("<builtin>", stderr);
}
/*
* Set a symbol's definition filename and line
*/
// Set a symbol's definition filename and line
static void setSymbolFilename(struct Symbol *sym)
{
sym->src = fstk_GetFileStack();
sym->fileLine = sym->src ? lexer_GetLineNo() : 0; // This is (NULL, 1) for built-ins
}
/*
* Update a symbol's definition filename and line
*/
// Update a symbol's definition filename and line
static void updateSymbolFilename(struct Symbol *sym)
{
struct FileStackNode *oldSrc = sym->src;
setSymbolFilename(sym);
/* If the old node was referenced, ensure the new one is */
// If the old node was referenced, ensure the new one is
if (oldSrc && oldSrc->referenced && oldSrc->ID != (uint32_t)-1)
out_RegisterNode(sym->src);
/* TODO: unref the old node, and use `out_ReplaceNode` instead of deleting it */
// TODO: unref the old node, and use `out_ReplaceNode` instead of deleting it
}
/*
* Create a new symbol by name
*/
// Create a new symbol by name
static struct Symbol *createsymbol(char const *symName)
{
struct Symbol *sym = malloc(sizeof(*sym));
@@ -201,10 +189,8 @@ static struct Symbol *createsymbol(char const *symName)
return sym;
}
/*
* Creates the full name of a local symbol in a given scope, by prepending
* the name with the parent symbol's name.
*/
// Creates the full name of a local symbol in a given scope, by prepending
// the name with the parent symbol's name.
static void fullSymbolName(char *output, size_t outputSize,
char const *localName, char const *scopeName)
{
@@ -250,8 +236,8 @@ struct Symbol *sym_FindScopedSymbol(char const *symName)
if (strchr(localName + 1, '.'))
fatalerror("'%s' is a nonsensical reference to a nested local symbol\n",
symName);
/* If auto-scoped local label, expand the name */
if (localName == symName) { /* Meaning, the name begins with the dot */
// If auto-scoped local label, expand the name
if (localName == symName) { // Meaning, the name begins with the dot
char fullName[MAXSYMLEN + 1];
fullSymbolName(fullName, sizeof(fullName), symName, labelScope);
@@ -271,9 +257,7 @@ static bool isReferenced(struct Symbol const *sym)
return sym->ID != (uint32_t)-1;
}
/*
* Purge a symbol
*/
// Purge a symbol
void sym_Purge(char const *symName)
{
struct Symbol *sym = sym_FindScopedSymbol(symName);
@@ -285,16 +269,14 @@ void sym_Purge(char const *symName)
} else if (isReferenced(sym)) {
error("Symbol \"%s\" is referenced and thus cannot be purged\n", symName);
} else {
/* Do not keep a reference to the label's name after purging it */
// Do not keep a reference to the label's name after purging it
if (sym->name == labelScope)
sym_SetCurrentSymbolScope(NULL);
/*
* FIXME: this leaks sym->macro for SYM_EQUS and SYM_MACRO, but this can't
* free(sym->macro) because the expansion may be purging itself.
*/
// FIXME: this leaks sym->macro for SYM_EQUS and SYM_MACRO, but this can't
// free(sym->macro) because the expansion may be purging itself.
hash_RemoveElement(symbols, sym->name);
/* TODO: ideally, also unref the file stack nodes */
// TODO: ideally, also unref the file stack nodes
free(sym);
}
}
@@ -312,9 +294,7 @@ uint32_t sym_GetPCValue(void)
return 0;
}
/*
* Return a constant symbol's value, assuming it's defined
*/
// Return a constant symbol's value, assuming it's defined
uint32_t sym_GetConstantSymValue(struct Symbol const *sym)
{
if (sym == PCSymbol)
@@ -327,9 +307,7 @@ uint32_t sym_GetConstantSymValue(struct Symbol const *sym)
return 0;
}
/*
* Return a constant symbol's value
*/
// Return a constant symbol's value
uint32_t sym_GetConstantValue(char const *symName)
{
struct Symbol const *sym = sym_FindScopedSymbol(symName);
@@ -381,9 +359,7 @@ static struct Symbol *createNonrelocSymbol(char const *symName, bool numeric)
return sym;
}
/*
* Add an equated symbol
*/
// Add an equated symbol
struct Symbol *sym_AddEqu(char const *symName, int32_t value)
{
struct Symbol *sym = createNonrelocSymbol(symName, true);
@@ -465,18 +441,14 @@ struct Symbol *sym_RedefString(char const *symName, char const *value)
}
updateSymbolFilename(sym);
/*
* FIXME: this leaks the previous sym->macro value, but this can't
* free(sym->macro) because the expansion may be redefining itself.
*/
// FIXME: this leaks the previous sym->macro value, but this can't
// free(sym->macro) because the expansion may be redefining itself.
assignStringSymbol(sym, value);
return sym;
}
/*
* Alter a mutable symbol's value
*/
// Alter a mutable symbol's value
struct Symbol *sym_AddVar(char const *symName, int32_t value)
{
struct Symbol *sym = sym_FindExactSymbol(symName);
@@ -506,7 +478,7 @@ struct Symbol *sym_AddVar(char const *symName, int32_t value)
*/
static struct Symbol *addLabel(char const *symName)
{
assert(symName[0] != '.'); /* The symbol name must have been expanded prior */
assert(symName[0] != '.'); // The symbol name must have been expanded prior
struct Symbol *sym = sym_FindExactSymbol(symName);
if (!sym) {
@@ -519,7 +491,7 @@ static struct Symbol *addLabel(char const *symName)
} else {
updateSymbolFilename(sym);
}
/* If the symbol already exists as a ref, just "take over" it */
// If the symbol already exists as a ref, just "take over" it
sym->type = SYM_LABEL;
sym->value = sect_GetSymbolOffset();
if (exportall)
@@ -531,43 +503,41 @@ static struct Symbol *addLabel(char const *symName)
return sym;
}
/*
* Add a local (`.name` or `Parent.name`) relocatable symbol
*/
// Add a local (`.name` or `Parent.name`) relocatable symbol
struct Symbol *sym_AddLocalLabel(char const *symName)
{
if (!labelScope) {
error("Local label '%s' in main scope\n", symName);
return NULL;
}
assert(!strchr(labelScope, '.')); /* Assuming no dots in `labelScope` */
assert(!strchr(labelScope, '.')); // Assuming no dots in `labelScope`
char fullName[MAXSYMLEN + 1];
char const *localName = strchr(symName, '.');
assert(localName); /* There should be at least one dot in `symName` */
/* Check for something after the dot in `localName` */
assert(localName); // There should be at least one dot in `symName`
// Check for something after the dot in `localName`
if (localName[1] == '\0') {
fatalerror("'%s' is a nonsensical reference to an empty local label\n",
symName);
}
/* Check for more than one dot in `localName` */
// Check for more than one dot in `localName`
if (strchr(localName + 1, '.'))
fatalerror("'%s' is a nonsensical reference to a nested local label\n",
symName);
if (localName == symName) {
/* Expand `symName` to the full `labelScope.symName` name */
// Expand `symName` to the full `labelScope.symName` name
fullSymbolName(fullName, sizeof(fullName), symName, labelScope);
symName = fullName;
} else {
size_t i = 0;
/* Find where `labelScope` and `symName` first differ */
// Find where `labelScope` and `symName` first differ
while (labelScope[i] && symName[i] == labelScope[i])
i++;
/* Check that `symName` starts with `labelScope` and then a '.' */
// Check that `symName` starts with `labelScope` and then a '.'
if (labelScope[i] != '\0' || symName[i] != '.') {
size_t parentLen = localName - symName;
@@ -579,14 +549,12 @@ struct Symbol *sym_AddLocalLabel(char const *symName)
return addLabel(symName);
}
/*
* Add a relocatable symbol
*/
// Add a relocatable symbol
struct Symbol *sym_AddLabel(char const *symName)
{
struct Symbol *sym = addLabel(symName);
/* Set the symbol as the new scope */
// Set the symbol as the new scope
if (sym)
sym_SetCurrentSymbolScope(sym->name);
return sym;
@@ -594,9 +562,7 @@ struct Symbol *sym_AddLabel(char const *symName)
static uint32_t anonLabelID;
/*
* Add an anonymous label
*/
// Add an anonymous label
struct Symbol *sym_AddAnonLabel(void)
{
if (anonLabelID == UINT32_MAX) {
@@ -610,9 +576,7 @@ struct Symbol *sym_AddAnonLabel(void)
return addLabel(name);
}
/*
* Write an anonymous label's name to a buffer
*/
// Write an anonymous label's name to a buffer
void sym_WriteAnonLabelName(char buf[MIN_NB_ELMS(MAXSYMLEN + 1)], uint32_t ofs, bool neg)
{
uint32_t id = 0;
@@ -636,9 +600,7 @@ void sym_WriteAnonLabelName(char buf[MIN_NB_ELMS(MAXSYMLEN + 1)], uint32_t ofs,
sprintf(buf, "!%u", id);
}
/*
* Export a symbol
*/
// Export a symbol
void sym_Export(char const *symName)
{
if (symName[0] == '!') {
@@ -648,15 +610,13 @@ void sym_Export(char const *symName)
struct Symbol *sym = sym_FindScopedSymbol(symName);
/* If the symbol doesn't exist, create a ref that can be purged */
// If the symbol doesn't exist, create a ref that can be purged
if (!sym)
sym = sym_Ref(symName);
sym->isExported = true;
}
/*
* Add a macro definition
*/
// Add a macro definition
struct Symbol *sym_AddMacro(char const *symName, int32_t defLineNo, char *body, size_t size)
{
struct Symbol *sym = createNonrelocSymbol(symName, false);
@@ -667,20 +627,16 @@ struct Symbol *sym_AddMacro(char const *symName, int32_t defLineNo, char *body,
sym->type = SYM_MACRO;
sym->macroSize = size;
sym->macro = body;
setSymbolFilename(sym); /* TODO: is this really necessary? */
/*
* The symbol is created at the line after the `endm`,
* override this with the actual definition line
*/
setSymbolFilename(sym); // TODO: is this really necessary?
// The symbol is created at the line after the `endm`,
// override this with the actual definition line
sym->fileLine = defLineNo;
return sym;
}
/*
* Flag that a symbol is referenced in an RPN expression
* and create it if it doesn't exist yet
*/
// Flag that a symbol is referenced in an RPN expression
// and create it if it doesn't exist yet
struct Symbol *sym_Ref(char const *symName)
{
struct Symbol *sym = sym_FindScopedSymbol(symName);
@@ -702,9 +658,7 @@ struct Symbol *sym_Ref(char const *symName)
return sym;
}
/*
* Set whether to export all relocatable symbols by default
*/
// Set whether to export all relocatable symbols by default
void sym_SetExportAll(bool set)
{
exportall = set;
@@ -721,9 +675,7 @@ static struct Symbol *createBuiltinSymbol(char const *symName)
return sym;
}
/*
* Initialize the symboltable
*/
// Initialize the symboltable
void sym_Init(time_t now)
{
PCSymbol = createBuiltinSymbol("@");
@@ -761,7 +713,7 @@ void sym_Init(time_t now)
if (now == (time_t)-1) {
warn("Couldn't determine current time");
/* Fall back by pretending we are at the Epoch */
// Fall back by pretending we are at the Epoch
now = 0;
}

View File

@@ -44,7 +44,7 @@ char const *printChar(int c)
buf[2] = 't';
break;
default: /* Print as hex */
default: // Print as hex
buf[0] = '0';
buf[1] = 'x';
snprintf(&buf[2], 3, "%02hhX", (uint8_t)c); // includes the '\0'

View File

@@ -38,6 +38,7 @@ static const enum WarningState defaultWarnings[ARRAY_SIZE(warningStates)] = {
[WARNING_OBSOLETE] = WARNING_ENABLED,
[WARNING_SHIFT] = WARNING_DISABLED,
[WARNING_SHIFT_AMOUNT] = WARNING_DISABLED,
[WARNING_UNMAPPED_CHAR] = WARNING_ENABLED,
[WARNING_USER] = WARNING_ENABLED,
[WARNING_NUMERIC_STRING_1] = WARNING_ENABLED,
@@ -48,19 +49,19 @@ static const enum WarningState defaultWarnings[ARRAY_SIZE(warningStates)] = {
enum WarningState warningStates[ARRAY_SIZE(warningStates)];
bool warningsAreErrors; /* Set if `-Werror` was specified */
bool warningsAreErrors; // Set if `-Werror` was specified
static enum WarningState warningState(enum WarningID id)
{
/* Check if warnings are globally disabled */
// Check if warnings are globally disabled
if (!warnings)
return WARNING_DISABLED;
/* Get the actual state */
// Get the actual state
enum WarningState state = warningStates[id];
if (state == WARNING_DEFAULT)
/* The state isn't set, grab its default state */
// The state isn't set, grab its default state
state = defaultWarnings[id];
if (warningsAreErrors && state == WARNING_ENABLED)
@@ -85,6 +86,7 @@ static const char * const warningFlags[NB_WARNINGS] = {
"obsolete",
"shift",
"shift-amount",
"unmapped-char",
"user",
// Parametric warnings
@@ -93,10 +95,10 @@ static const char * const warningFlags[NB_WARNINGS] = {
"truncation",
"truncation",
/* Meta warnings */
// Meta warnings
"all",
"extra",
"everything", /* Especially useful for testing */
"everything", // Especially useful for testing
};
static const struct {
@@ -149,7 +151,7 @@ enum MetaWarningCommand {
META_WARNING_DONE = NB_WARNINGS
};
/* Warnings that probably indicate an error */
// Warnings that probably indicate an error
static uint8_t const _wallCommands[] = {
WARNING_BACKWARDS_FOR,
WARNING_BUILTIN_ARG,
@@ -160,11 +162,12 @@ static uint8_t const _wallCommands[] = {
WARNING_LONG_STR,
WARNING_NESTED_COMMENT,
WARNING_OBSOLETE,
WARNING_UNMAPPED_CHAR,
WARNING_NUMERIC_STRING_1,
META_WARNING_DONE
};
/* Warnings that are less likely to indicate an error */
// Warnings that are less likely to indicate an error
static uint8_t const _wextraCommands[] = {
WARNING_EMPTY_MACRO_ARG,
WARNING_MACRO_SHIFT,
@@ -176,7 +179,7 @@ static uint8_t const _wextraCommands[] = {
META_WARNING_DONE
};
/* Literally everything. Notably useful for testing */
// Literally everything. Notably useful for testing
static uint8_t const _weverythingCommands[] = {
WARNING_BACKWARDS_FOR,
WARNING_BUILTIN_ARG,
@@ -191,11 +194,12 @@ static uint8_t const _weverythingCommands[] = {
WARNING_OBSOLETE,
WARNING_SHIFT,
WARNING_SHIFT_AMOUNT,
WARNING_UNMAPPED_CHAR,
WARNING_NUMERIC_STRING_1,
WARNING_NUMERIC_STRING_2,
WARNING_TRUNCATION_1,
WARNING_TRUNCATION_2,
/* WARNING_USER, */
// WARNING_USER,
META_WARNING_DONE
};
@@ -209,18 +213,18 @@ void processWarningFlag(char *flag)
{
static bool setError = false;
/* First, try to match against a "meta" warning */
// First, try to match against a "meta" warning
for (enum WarningID id = META_WARNINGS_START; id < NB_WARNINGS; id++) {
/* TODO: improve the matching performance? */
// TODO: improve the matching performance?
if (!strcmp(flag, warningFlags[id])) {
/* We got a match! */
// We got a match!
if (setError)
errx("Cannot make meta warning \"%s\" into an error",
flag);
for (uint8_t const *ptr = metaWarningCommands[id - META_WARNINGS_START];
*ptr != META_WARNING_DONE; ptr++) {
/* Warning flag, set without override */
// Warning flag, set without override
if (warningStates[*ptr] == WARNING_DEFAULT)
warningStates[*ptr] = WARNING_ENABLED;
}
@@ -229,31 +233,31 @@ void processWarningFlag(char *flag)
}
}
/* If it's not a meta warning, specially check against `-Werror` */
// If it's not a meta warning, specially check against `-Werror`
if (!strncmp(flag, "error", strlen("error"))) {
char *errorFlag = flag + strlen("error");
switch (*errorFlag) {
case '\0':
/* `-Werror` */
// `-Werror`
warningsAreErrors = true;
return;
case '=':
/* `-Werror=XXX` */
// `-Werror=XXX`
setError = true;
processWarningFlag(errorFlag + 1); /* Skip the `=` */
processWarningFlag(errorFlag + 1); // Skip the `=`
setError = false;
return;
/* Otherwise, allow parsing as another flag */
// Otherwise, allow parsing as another flag
}
}
/* Well, it's either a normal warning or a mistake */
// Well, it's either a normal warning or a mistake
enum WarningState state = setError ? WARNING_ERROR :
/* Not an error, then check if this is a negation */
// Not an error, then check if this is a negation
strncmp(flag, "no-", strlen("no-")) ? WARNING_ENABLED
: WARNING_DISABLED;
char const *rootFlag = state == WARNING_DISABLED ? flag + strlen("no-") : flag;
@@ -304,10 +308,10 @@ void processWarningFlag(char *flag)
}
}
/* Try to match the flag against a "normal" flag */
// Try to match the flag against a "normal" flag
for (enum WarningID id = 0; id < NB_PLAIN_WARNINGS; id++) {
if (!strcmp(rootFlag, warningFlags[id])) {
/* We got a match! */
// We got a match!
warningStates[id] = state;
return;
}
@@ -370,7 +374,7 @@ void warning(enum WarningID id, char const *fmt, ...)
case WARNING_DEFAULT:
unreachable_();
/* Not reached */
// Not reached
case WARNING_ENABLED:
break;

View File

@@ -29,7 +29,7 @@
#define BANK_SIZE 0x4000
/* Short options */
// Short options
static const char *optstring = "Ccf:i:jk:l:m:n:Op:r:st:Vv";
/*
@@ -191,7 +191,7 @@ static void printAcceptedMBCNames(void)
static uint8_t tpp1Rev[2];
/**
/*
* @return False on failure
*/
static bool readMBCSlice(char const **name, char const *expected)
@@ -837,7 +837,7 @@ static ssize_t writeBytes(int fd, void *buf, size_t len)
return total;
}
/**
/*
* @param rom0 A pointer to rom0
* @param addr What address to check
* @param fixedByte The fixed byte at the address
@@ -853,7 +853,7 @@ static void overwriteByte(uint8_t *rom0, uint16_t addr, uint8_t fixedByte, char
rom0[addr] = fixedByte;
}
/**
/*
* @param rom0 A pointer to rom0
* @param startAddr What address to begin checking from
* @param fixed The fixed bytes at the address
@@ -878,7 +878,7 @@ static void overwriteBytes(uint8_t *rom0, uint16_t startAddr, uint8_t const *fix
memcpy(&rom0[startAddr], fixed, size);
}
/**
/*
* @param input File descriptor to be used for reading
* @param output File descriptor to be used for writing, may be equal to `input`
* @param name The file's name, to be displayed for error output

View File

@@ -153,7 +153,7 @@ static void printUsage(void) {
exit(1);
}
/**
/*
* Parses a number at the beginning of a string, moving the pointer to skip the parsed characters
* Returns the provided errVal on error
*/
@@ -179,7 +179,7 @@ static uint16_t parseNumber(char *&string, char const *errPrefix, uint16_t errVa
}
}
/**
/*
* Turns a digit into its numeric value in the current base, if it has one.
* Maximum is inclusive. The string_view is modified to "consume" all digits.
* Returns 255 on parse failure (including wrong char for base), in which case
@@ -248,7 +248,7 @@ static void registerInput(char const *arg) {
}
}
/**
/*
* Turn an "at-file"'s contents into an argv that `getopt` can handle
* @param argPool Argument characters will be appended to this vector, for storage purposes.
*/
@@ -317,7 +317,7 @@ static std::vector<size_t> readAtFile(std::string const &path, std::vector<char>
} while (c != '\n' && c != EOF); // End if we reached EOL
}
}
/**
/*
* Parses an arg vector, modifying `options` as options are read.
* The three booleans are for the "auto path" flags, since their processing must be deferred to the
* end of option parsing.
@@ -785,7 +785,7 @@ void Palette::addColor(uint16_t color) {
}
}
/**
/*
* Returns the ID of the color in the palette, or `size()` if the color is not in
*/
uint8_t Palette::indexOf(uint16_t color) const {

View File

@@ -39,12 +39,12 @@ namespace packing {
// Tile | Proto-palette
// Page | Palette
/**
/*
* A reference to a proto-palette, and attached attributes for sorting purposes
*/
struct ProtoPalAttrs {
size_t const protoPalIndex;
/**
/*
* Pages from which we are banned (to prevent infinite loops)
* This is dynamic because we wish not to hard-cap the amount of palettes
*/
@@ -62,7 +62,7 @@ struct ProtoPalAttrs {
}
};
/**
/*
* A collection of proto-palettes assigned to a palette
* Does not contain the actual color indices because we need to be able to remove elements
*/
@@ -139,7 +139,7 @@ public:
}
const_iterator end() const { return const_iterator{&_assigned, _assigned.end()}; }
/**
/*
* Assigns a new ProtoPalAttrs in a free slot, assuming there is one
* Args are passed to the `ProtoPalAttrs`'s constructor
*/
@@ -198,7 +198,7 @@ private:
return colors;
}
public:
/**
/*
* Returns the number of distinct colors
*/
size_t volume() const { return uniqueColors().size(); }
@@ -208,7 +208,7 @@ public:
return colors.size() <= options.maxOpaqueColors();
}
/**
/*
* Computes the "relative size" of a proto-palette on this palette
*/
double relSizeOf(ProtoPalette const &protoPal) const {
@@ -227,7 +227,7 @@ public:
return relSize;
}
/**
/*
* Computes the "relative size" of a set of proto-palettes on this palette
*/
template<typename Iter>
@@ -237,7 +237,7 @@ public:
addUniqueColors(colors, std::forward<Iter>(begin), end, protoPals);
return colors.size();
}
/**
/*
* Computes the "relative size" of a set of colors on this palette
*/
template<typename Iter>

View File

@@ -1,3 +1,10 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2022, Eldred Habert and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#include "gfx/pal_sorting.hpp"
@@ -97,7 +104,7 @@ void rgb(std::vector<Palette> &palettes) {
for (Palette &pal : palettes) {
std::sort(pal.begin(), pal.end(), [](uint16_t lhs, uint16_t rhs) {
return legacyLuminance(lhs) < legacyLuminance(rhs);
return legacyLuminance(lhs) > legacyLuminance(rhs);
});
}
}

View File

@@ -165,7 +165,7 @@ void parseInlinePalSpec(char const * const rawArg) {
}
}
/**
/*
* Tries to read some magic bytes from the provided `file`.
* Returns whether the magic was correctly read.
*/
@@ -191,7 +191,7 @@ static T readBE(U const *bytes) {
return val;
}
/**
/*
* **Appends** the first line read from `file` to the end of the provided `buffer`.
*/
static void readLine(std::filebuf &file, std::string &buffer) {
@@ -214,7 +214,7 @@ static void readLine(std::filebuf &file, std::string &buffer) {
}
// FIXME: Normally we'd use `std::from_chars`, but that's not available with GCC 7
/**
/*
* Parses the initial part of a string_view, advancing the "read index" as it does
*/
static uint16_t parseDec(std::string const &str, std::string::size_type &n) {

View File

@@ -42,7 +42,7 @@ class ImagePalette {
public:
ImagePalette() = default;
/**
/*
* Registers a color in the palette.
* If the newly inserted color "conflicts" with another one (different color, but same CGB
* color), then the other color is returned. Otherwise, `nullptr` is returned.
@@ -164,7 +164,7 @@ public:
return true;
}
/**
/*
* Reads a PNG and notes all of its colors
*
* This code is more complicated than strictly necessary, but that's because of the API
@@ -254,8 +254,8 @@ public:
}
};
options.verbosePrint(Options::VERB_INTERM,
"Input image: %" PRIu32 "x%" PRIu32 " pixels, %dbpp %s, %s\n", height,
width, bitDepth, colorTypeName(), interlaceTypeName());
"Input image: %" PRIu32 "x%" PRIu32 " pixels, %dbpp %s, %s\n", width,
height, bitDepth, colorTypeName(), interlaceTypeName());
if (png_get_PLTE(png, info, &embeddedPal, &nbColors) != 0) {
int nbTransparentEntries;
@@ -466,7 +466,7 @@ public:
};
class RawTiles {
/**
/*
* A tile which only contains indices into the image's global palette
*/
class RawTile {
@@ -481,7 +481,7 @@ private:
std::vector<RawTile> _tiles;
public:
/**
/*
* Creates a new raw tile, and returns a reference to it so it can be filled in
*/
RawTile &newTile() {
@@ -491,7 +491,7 @@ public:
};
struct AttrmapEntry {
/**
/*
* This field can either be a proto-palette ID, or `transparent` to indicate that the
* corresponding tile is fully transparent. If you are looking to get the palette ID for this
* attrmap entry while correctly handling the above, use `getPalID`.
@@ -831,7 +831,7 @@ struct UniqueTiles {
UniqueTiles(UniqueTiles const &) = delete;
UniqueTiles(UniqueTiles &&) = default;
/**
/*
* Adds a tile to the collection, and returns its ID
*/
std::tuple<uint16_t, TileData::MatchType> addTile(Png::TilesVisitor::Tile const &tile,
@@ -857,7 +857,7 @@ struct UniqueTiles {
auto end() const { return tiles.end(); }
};
/**
/*
* Generate tile data while deduplicating unique tiles (via mirroring if enabled)
* Additionally, while we have the info handy, convert from the 16-bit "global" tile IDs to
* 8-bit tile IDs + the bank bit; this will save the work when we output the data later (potentially
@@ -986,16 +986,17 @@ void process() {
protoPalettes[n] = tileColors; // Override them
// Remove any other proto-palettes that we encompass
// (Example [(0, 1), (0, 2)], inserting (0, 1, 2))
/* The following code does its job, except that references to the removed
/*
* The following code does its job, except that references to the removed
* proto-palettes are not updated, causing issues.
* TODO: overlap might not be detrimental to the packing algorithm.
* Investigation is necessary, especially if pathological cases are found.
for (size_t i = protoPalettes.size(); --i != n;) {
if (tileColors.compare(protoPalettes[i]) == ProtoPalette::WE_BIGGER) {
protoPalettes.erase(protoPalettes.begin() + i);
}
}
*
* for (size_t i = protoPalettes.size(); --i != n;) {
* if (tileColors.compare(protoPalettes[i]) == ProtoPalette::WE_BIGGER) {
* protoPalettes.erase(protoPalettes.begin() + i);
* }
* }
*/
[[fallthrough]];

View File

@@ -28,7 +28,9 @@
static DefaultInitVec<uint8_t> readInto(std::string path) {
std::filebuf file;
file.open(path, std::ios::in | std::ios::binary);
if (!file.open(path, std::ios::in | std::ios::binary)) {
fatal("Failed to open \"%s\": %s", path.c_str(), strerror(errno));
}
DefaultInitVec<uint8_t> data(128 * 16); // Begin with some room pre-allocated
size_t curSize = 0;
@@ -117,8 +119,12 @@ void reverse() {
if (!options.tilemap.empty()) {
tilemap = readInto(options.tilemap);
nbTileInstances = tilemap->size();
options.verbosePrint(Options::VERB_INTERM, "Read %zu tilemap entries.\n", nbTileInstances);
}
if (nbTileInstances == 0) {
fatal("Cannot generate empty image");
}
if (nbTileInstances > options.maxNbTiles[0] + options.maxNbTiles[1]) {
warning("Read %zu tiles, more than the limit of %zu + %zu", nbTileInstances,
options.maxNbTiles[0], options.maxNbTiles[1]);
@@ -268,7 +274,7 @@ void reverse() {
uint8_t attribute = attrmap.has_value() ? (*attrmap)[index] : 0x00;
bool bank = attribute & 0x08;
// Get the tile ID at this location
uint8_t tileID = index;
size_t tileID = index;
if (tilemap.has_value()) {
tileID =
(*tilemap)[index] - options.baseTileIDs[bank] + bank * options.maxNbTiles[0];

View File

@@ -1,3 +1,11 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2022, Eldred Habert and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#include "gfx/rgba.hpp"
#include <assert.h>

View File

@@ -15,10 +15,8 @@
#include "error.h"
#include "hashmap.h"
/*
* The lower half of the hash is used to index the "master" table,
* the upper half is used to help resolve collisions more quickly
*/
// The lower half of the hash is used to index the "master" table,
// the upper half is used to help resolve collisions more quickly
#define UINT_BITS_(NB_BITS) uint##NB_BITS##_t
#define UINT_BITS(NB_BITS) UINT_BITS_(NB_BITS)
typedef UINT_BITS(HASH_NB_BITS) HashType;
@@ -34,7 +32,7 @@ struct HashMapEntry {
#define FNV_OFFSET_BASIS 0x811c9dc5
#define FNV_PRIME 16777619
/* FNV-1a hash */
// FNV-1a hash
static HashType hash(char const *str)
{
HashType hash = FNV_OFFSET_BASIS;

View File

@@ -17,11 +17,11 @@
#include "link/symbol.h"
#include "link/object.h"
#include "link/main.h"
#include "link/script.h"
#include "link/output.h"
#include "error.h"
#include "helpers.h"
#include "linkdefs.h"
struct MemoryLocation {
uint16_t address;
@@ -34,14 +34,12 @@ struct FreeSpace {
struct FreeSpace *next, *prev;
};
/* Table of free space for each bank */
// Table of free space for each bank
struct FreeSpace *memory[SECTTYPE_INVALID];
uint64_t nbSectionsToAssign;
/**
* Init the free space-modelling structs
*/
// Init the free space-modelling structs
static void initFreeSpace(void)
{
for (enum SectionType type = 0; type < SECTTYPE_INVALID; type++) {
@@ -55,54 +53,15 @@ static void initFreeSpace(void)
if (!memory[type][bank].next)
err("Failed to init free space for region %d bank %" PRIu32,
type, bank);
memory[type][bank].next->address = startaddr[type];
memory[type][bank].next->size = maxsize[type];
memory[type][bank].next->address = sectionTypeInfo[type].startAddr;
memory[type][bank].next->size = sectionTypeInfo[type].size;
memory[type][bank].next->next = NULL;
memory[type][bank].next->prev = &memory[type][bank];
}
}
}
/**
* Alter sections' attributes based on the linker script
*/
static void processLinkerScript(void)
{
if (!linkerScriptName)
return;
verbosePrint("Reading linker script...\n");
linkerScript = openFile(linkerScriptName, "r");
/* Modify all sections according to the linker script */
struct SectionPlacement *placement;
while ((placement = script_NextSection())) {
struct Section *section = placement->section;
/* Check if this doesn't conflict with what the code says */
if (section->isBankFixed && placement->bank != section->bank)
error(NULL, 0, "Linker script contradicts \"%s\"'s bank placement",
section->name);
if (section->isAddressFixed && placement->org != section->org)
error(NULL, 0, "Linker script contradicts \"%s\"'s address placement",
section->name);
if (section->isAlignFixed
&& (placement->org & section->alignMask) != 0)
error(NULL, 0, "Linker script contradicts \"%s\"'s alignment",
section->name);
section->isAddressFixed = true;
section->org = placement->org;
section->isBankFixed = true;
section->bank = placement->bank;
section->isAlignFixed = false; /* The alignment is satisfied */
}
fclose(linkerScript);
}
/**
/*
* Assigns a section to a given memory location
* @param section The section to assign
* @param location The location to assign the section to
@@ -124,7 +83,7 @@ static void assignSection(struct Section *section, struct MemoryLocation const *
out_AddSection(section);
}
/**
/*
* Checks whether a given location is suitable for placing a given section
* This checks not only that the location has enough room for the section, but
* also that the constraints (alignment...) are respected.
@@ -150,7 +109,7 @@ static bool isLocationSuitable(struct Section const *section,
<= freeSpace->address + freeSpace->size;
}
/**
/*
* Finds a suitable location to place a section at.
* @param section The section to be placed
* @param location A pointer to a location struct that will be filled
@@ -180,74 +139,70 @@ static struct FreeSpace *getPlacement(struct Section const *section,
if (curScrambleSRAM > scrambleSRAM)
curScrambleSRAM = 0;
} else {
location->bank = bankranges[section->type][0];
location->bank = sectionTypeInfo[section->type].firstBank;
}
struct FreeSpace *space;
for (;;) {
/* Switch to the beginning of the next bank */
#define BANK_INDEX (location->bank - bankranges[section->type][0])
// Switch to the beginning of the next bank
#define BANK_INDEX (location->bank - sectionTypeInfo[section->type].firstBank)
space = memory[section->type][BANK_INDEX].next;
if (space)
location->address = space->address;
/* Process locations in that bank */
// Process locations in that bank
while (space) {
/* If that location is OK, return it */
// If that location is OK, return it
if (isLocationSuitable(section, space, location))
return space;
/* Go to the next *possible* location */
// Go to the next *possible* location
if (section->isAddressFixed) {
/*
* If the address is fixed, there can be only
* one candidate block per bank; if we already
* reached it, give up.
*/
// If the address is fixed, there can be only
// one candidate block per bank; if we already
// reached it, give up.
if (location->address < section->org)
location->address = section->org;
else
/* Try again in next bank */
// Try again in next bank
space = NULL;
} else if (section->isAlignFixed) {
/* Move to next aligned location */
/* Move back to alignment boundary */
// Move to next aligned location
// Move back to alignment boundary
location->address -= section->alignOfs;
/* Ensure we're there (e.g. on first check) */
// Ensure we're there (e.g. on first check)
location->address &= ~section->alignMask;
/* Go to next align boundary and add offset */
// Go to next align boundary and add offset
location->address += section->alignMask + 1
+ section->alignOfs;
} else {
/* Any location is fine, so, next free block */
// Any location is fine, so, next free block
space = space->next;
if (space)
location->address = space->address;
}
/*
* If that location is past the current block's end,
* go forwards until that is no longer the case.
*/
// If that location is past the current block's end,
// go forwards until that is no longer the case.
while (space && location->address >=
space->address + space->size)
space = space->next;
/* Try again with the new location/free space combo */
// Try again with the new location/free space combo
}
if (section->isBankFixed)
return NULL;
/* Try again in the next bank */
// Try again in the next bank
location->bank++;
if (location->bank > bankranges[section->type][1])
if (location->bank > sectionTypeInfo[section->type].lastBank)
return NULL;
#undef BANK_INDEX
}
}
/**
/*
* Places a section in a suitable location, or error out if it fails to.
* @warning Due to the implemented algorithm, this should be called with
* sections of decreasing size.
@@ -257,76 +212,70 @@ static void placeSection(struct Section *section)
{
struct MemoryLocation location;
/* Specially handle 0-byte SECTIONs, as they can't overlap anything */
// Specially handle 0-byte SECTIONs, as they can't overlap anything
if (section->size == 0) {
/*
* Unless the SECTION's address was fixed, the starting address
* is fine for any alignment, as checked in sect_DoSanityChecks.
*/
// Unless the SECTION's address was fixed, the starting address
// is fine for any alignment, as checked in sect_DoSanityChecks.
location.address = section->isAddressFixed
? section->org
: startaddr[section->type];
: sectionTypeInfo[section->type].startAddr;
location.bank = section->isBankFixed
? section->bank
: bankranges[section->type][0];
: sectionTypeInfo[section->type].firstBank;
assignSection(section, &location);
return;
}
/*
* Place section using first-fit decreasing algorithm
* https://en.wikipedia.org/wiki/Bin_packing_problem#First-fit_algorithm
*/
// Place section using first-fit decreasing algorithm
// https://en.wikipedia.org/wiki/Bin_packing_problem#First-fit_algorithm
struct FreeSpace *freeSpace = getPlacement(section, &location);
if (freeSpace) {
assignSection(section, &location);
/* Split the free space */
// Split the free space
bool noLeftSpace = freeSpace->address == section->org;
bool noRightSpace = freeSpace->address + freeSpace->size
== section->org + section->size;
if (noLeftSpace && noRightSpace) {
/* The free space is entirely deleted */
// The free space is entirely deleted
freeSpace->prev->next = freeSpace->next;
if (freeSpace->next)
freeSpace->next->prev = freeSpace->prev;
/*
* If the space is the last one on the list, set its
* size to 0 so it doesn't get picked, but don't free()
* it as it will be freed when cleaning up
*/
// If the space is the last one on the list, set its
// size to 0 so it doesn't get picked, but don't free()
// it as it will be freed when cleaning up
free(freeSpace);
} else if (!noLeftSpace && !noRightSpace) {
/* The free space is split in two */
// The free space is split in two
struct FreeSpace *newSpace = malloc(sizeof(*newSpace));
if (!newSpace)
err("Failed to split new free space");
/* Append the new space after the chosen one */
// Append the new space after the chosen one
newSpace->prev = freeSpace;
newSpace->next = freeSpace->next;
if (freeSpace->next)
freeSpace->next->prev = newSpace;
freeSpace->next = newSpace;
/* Set its parameters */
// Set its parameters
newSpace->address = section->org + section->size;
newSpace->size = freeSpace->address + freeSpace->size -
newSpace->address;
/* Set the original space's new parameters */
// Set the original space's new parameters
freeSpace->size = section->org - freeSpace->address;
/* address is unmodified */
// address is unmodified
} else {
/* The amount of free spaces doesn't change: resize! */
// The amount of free spaces doesn't change: resize!
freeSpace->size -= section->size;
if (noLeftSpace)
/* The free space is moved *and* resized */
// The free space is moved *and* resized
freeSpace->address += section->size;
}
return;
}
/* Please adjust depending on longest message below */
// Please adjust depending on longest message below
char where[64];
if (section->isBankFixed && nbbanks(section->type) != 1) {
@@ -351,19 +300,19 @@ static void placeSection(struct Section *section)
strcpy(where, "anywhere");
}
/* If a section failed to go to several places, nothing we can report */
// If a section failed to go to several places, nothing we can report
if (!section->isBankFixed || !section->isAddressFixed)
errx("Unable to place \"%s\" (%s section) %s",
section->name, typeNames[section->type], where);
/* If the section just can't fit the bank, report that */
section->name, sectionTypeInfo[section->type].name, where);
// If the section just can't fit the bank, report that
else if (section->org + section->size > endaddr(section->type) + 1)
errx("Unable to place \"%s\" (%s section) %s: section runs past end of region ($%04x > $%04x)",
section->name, typeNames[section->type], where,
section->name, sectionTypeInfo[section->type].name, where,
section->org + section->size, endaddr(section->type) + 1);
/* Otherwise there is overlap with another section */
// Otherwise there is overlap with another section
else
errx("Unable to place \"%s\" (%s section) %s: section overlaps with \"%s\"",
section->name, typeNames[section->type], where,
section->name, sectionTypeInfo[section->type].name, where,
out_OverlappingSection(section)->name);
}
@@ -378,7 +327,7 @@ struct UnassignedSection {
static struct UnassignedSection *unassignedSections[1 << 3] = {0};
static struct UnassignedSection *sections;
/**
/*
* Categorize a section depending on how constrained it is
* This is so the most-constrained sections are placed first
* @param section The section to categorize
@@ -393,13 +342,13 @@ static void categorizeSection(struct Section *section, void *arg)
constraints |= BANK_CONSTRAINED;
if (section->isAddressFixed)
constraints |= ORG_CONSTRAINED;
/* Can't have both! */
// Can't have both!
else if (section->isAlignFixed)
constraints |= ALIGN_CONSTRAINED;
struct UnassignedSection **ptr = &unassignedSections[constraints];
/* Insert section while keeping the list sorted by decreasing size */
// Insert section while keeping the list sorted by decreasing size
while (*ptr && (*ptr)->section->size > section->size)
ptr = &(*ptr)->next;
@@ -414,24 +363,21 @@ void assign_AssignSections(void)
{
verbosePrint("Beginning assignment...\n");
/** Initialize assignment **/
// Initialize assignment
/* Generate linked lists of sections to assign */
// Generate linked lists of sections to assign
sections = malloc(sizeof(*sections) * nbSectionsToAssign + 1);
if (!sections)
err("Failed to allocate memory for section assignment");
initFreeSpace();
/* Process linker script, if any */
processLinkerScript();
nbSectionsToAssign = 0;
sect_ForEach(categorizeSection, NULL);
/** Place sections, starting with the most constrained **/
// Place sections, starting with the most constrained
/* Specially process fully-constrained sections because of overlaying */
// Specially process fully-constrained sections because of overlaying
struct UnassignedSection *sectionPtr =
unassignedSections[BANK_CONSTRAINED | ORG_CONSTRAINED];
@@ -441,11 +387,11 @@ void assign_AssignSections(void)
sectionPtr = sectionPtr->next;
}
/* If all sections were fully constrained, we have nothing left to do */
// If all sections were fully constrained, we have nothing left to do
if (!nbSectionsToAssign)
return;
/* Overlaying requires only fully-constrained sections */
// Overlaying requires only fully-constrained sections
verbosePrint("Assigning other sections...\n");
if (overlayFileName) {
fprintf(stderr, "FATAL: All sections must be fixed when using an overlay file");
@@ -469,7 +415,7 @@ max_out:
exit(1);
}
/* Assign all remaining sections by decreasing constraint order */
// Assign all remaining sections by decreasing constraint order
for (int8_t constraints = BANK_CONSTRAINED | ALIGN_CONSTRAINED;
constraints >= 0; constraints--) {
sectionPtr = unassignedSections[constraints];
@@ -505,6 +451,4 @@ void assign_Cleanup(void)
}
free(sections);
script_Cleanup();
}

View File

@@ -18,46 +18,48 @@
#include <sys/stat.h>
#include <sys/types.h>
#include "link/object.h"
#include "link/symbol.h"
#include "link/section.h"
#include "link/assign.h"
#include "link/patch.h"
#include "link/object.h"
#include "link/output.h"
#include "link/patch.h"
#include "link/section.h"
#include "link/script.h"
#include "link/symbol.h"
#include "extern/getopt.h"
#include "error.h"
#include "linkdefs.h"
#include "platform.h"
#include "version.h"
bool isDmgMode; /* -d */
char *linkerScriptName; /* -l */
char const *mapFileName; /* -m */
char const *symFileName; /* -n */
char const *overlayFileName; /* -O */
char const *outputFileName; /* -o */
uint8_t padValue; /* -p */
bool isDmgMode; // -d
char *linkerScriptName; // -l
char const *mapFileName; // -m
bool noSymInMap; // -M
char const *symFileName; // -n
char const *overlayFileName; // -O
char const *outputFileName; // -o
uint8_t padValue; // -p
// Setting these three to 0 disables the functionality
uint16_t scrambleROMX = 0; /* -S */
uint16_t scrambleROMX = 0; // -S
uint8_t scrambleWRAMX = 0;
uint8_t scrambleSRAM = 0;
bool is32kMode; /* -t */
bool beVerbose; /* -v */
bool isWRA0Mode; /* -w */
bool disablePadding; /* -x */
bool is32kMode; // -t
bool beVerbose; // -v
bool isWRA0Mode; // -w
bool disablePadding; // -x
static uint32_t nbErrors = 0;
/***** Helper function to dump a file stack to stderr *****/
// Helper function to dump a file stack to stderr
char const *dumpFileStack(struct FileStackNode const *node)
{
char const *lastName;
if (node->parent) {
lastName = dumpFileStack(node->parent);
/* REPT nodes use their parent's name */
// REPT nodes use their parent's name
if (node->type != NODE_REPT)
lastName = node->name;
fprintf(stderr, "(%" PRIu32 ") -> %s", node->lineNo, lastName);
@@ -162,8 +164,8 @@ FILE *openFile(char const *fileName, char const *mode)
return file;
}
/* Short options */
static const char *optstring = "dl:m:n:O:o:p:S:s:tVvWwx";
// Short options
static const char *optstring = "dl:m:Mn:O:o:p:S:s:tVvWwx";
/*
* Equivalent long options
@@ -179,6 +181,7 @@ static struct option const longopts[] = {
{ "dmg", no_argument, NULL, 'd' },
{ "linkerscript", required_argument, NULL, 'l' },
{ "map", required_argument, NULL, 'm' },
{ "no-sym-in-map", no_argument, NULL, 'M' },
{ "sym", required_argument, NULL, 'n' },
{ "overlay", required_argument, NULL, 'O' },
{ "output", required_argument, NULL, 'o' },
@@ -193,13 +196,11 @@ static struct option const longopts[] = {
{ NULL, no_argument, NULL, 0 }
};
/**
* Prints the program's usage to stdout.
*/
// Prints the program's usage to stdout.
static void printUsage(void)
{
fputs(
"Usage: rgblink [-dtVvwx] [-l script] [-m map_file] [-n sym_file]\n"
"Usage: rgblink [-dMtVvwx] [-l script] [-m map_file] [-n sym_file]\n"
" [-O overlay_file] [-o out_file] [-p pad_value]\n"
" [-S spec] [-s symbol] <file> ...\n"
"Useful options:\n"
@@ -215,10 +216,8 @@ static void printUsage(void)
stderr);
}
/**
* Cleans up what has been done
* Mostly here to please tools such as `valgrind` so actual errors can be seen
*/
// Cleans up what has been done
// Mostly here to please tools such as `valgrind` so actual errors can be seen
static void cleanup(void)
{
obj_Cleanup();
@@ -349,13 +348,19 @@ next:
}
}
_Noreturn void reportErrors(void) {
fprintf(stderr, "Linking failed with %" PRIu32 " error%s\n",
nbErrors, nbErrors == 1 ? "" : "s");
exit(1);
}
int main(int argc, char *argv[])
{
int optionChar;
char *endptr; /* For error checking with `strtoul` */
unsigned long value; /* For storing `strtoul`'s return value */
char *endptr; // For error checking with `strtoul`
unsigned long value; // For storing `strtoul`'s return value
/* Parse options */
// Parse options
while ((optionChar = musl_getopt_long_only(argc, argv, optstring,
longopts, NULL)) != -1) {
switch (optionChar) {
@@ -366,6 +371,9 @@ int main(int argc, char *argv[])
case 'l':
linkerScriptName = musl_optarg;
break;
case 'M':
noSymInMap = true;
break;
case 'm':
mapFileName = musl_optarg;
break;
@@ -394,7 +402,7 @@ int main(int argc, char *argv[])
parseScrambleSpec(musl_optarg);
break;
case 's':
/* FIXME: nobody knows what this does, figure it out */
// FIXME: nobody knows what this does, figure it out
(void)musl_optarg;
warning(NULL, 0, "Nobody has any idea what `-s` does");
break;
@@ -412,7 +420,7 @@ int main(int argc, char *argv[])
break;
case 'x':
disablePadding = true;
/* implies tiny mode */
// implies tiny mode
is32kMode = true;
break;
default:
@@ -423,42 +431,90 @@ int main(int argc, char *argv[])
int curArgIndex = musl_optind;
/* If no input files were specified, the user must have screwed up */
// If no input files were specified, the user must have screwed up
if (curArgIndex == argc) {
fputs("FATAL: no input files\n", stderr);
printUsage();
exit(1);
}
/* Patch the size array depending on command-line options */
// Patch the size array depending on command-line options
if (!is32kMode)
maxsize[SECTTYPE_ROM0] = 0x4000;
sectionTypeInfo[SECTTYPE_ROM0].size = 0x4000;
if (!isWRA0Mode)
maxsize[SECTTYPE_WRAM0] = 0x1000;
sectionTypeInfo[SECTTYPE_WRAM0].size = 0x1000;
/* Patch the bank ranges array depending on command-line options */
// Patch the bank ranges array depending on command-line options
if (isDmgMode)
bankranges[SECTTYPE_VRAM][1] = BANK_MIN_VRAM;
sectionTypeInfo[SECTTYPE_VRAM].lastBank = 0;
/* Read all object files first, */
// Read all object files first,
for (obj_Setup(argc - curArgIndex); curArgIndex < argc; curArgIndex++)
obj_ReadFile(argv[curArgIndex], argc - curArgIndex - 1);
/* then process them, */
// apply the linker script's modifications,
if (linkerScriptName) {
verbosePrint("Reading linker script...\n");
linkerScript = openFile(linkerScriptName, "r");
// Modify all sections according to the linker script
struct SectionPlacement *placement;
while ((placement = script_NextSection())) {
struct Section *section = placement->section;
assert(section->offset == 0);
// Check if this doesn't conflict with what the code says
if (section->type == SECTTYPE_INVALID) {
for (struct Section *sect = section; sect; sect = sect->nextu)
sect->type = placement->type; // SDCC "unknown" sections
} else if (section->type != placement->type) {
error(NULL, 0, "Linker script contradicts \"%s\"'s type",
section->name);
}
if (section->isBankFixed && placement->bank != section->bank)
error(NULL, 0, "Linker script contradicts \"%s\"'s bank placement",
section->name);
if (section->isAddressFixed && placement->org != section->org)
error(NULL, 0, "Linker script contradicts \"%s\"'s address placement",
section->name);
if (section->isAlignFixed
&& (placement->org & section->alignMask) != 0)
error(NULL, 0, "Linker script contradicts \"%s\"'s alignment",
section->name);
section->isAddressFixed = true;
section->org = placement->org;
section->isBankFixed = true;
section->bank = placement->bank;
section->isAlignFixed = false; // The alignment is satisfied
}
fclose(linkerScript);
script_Cleanup();
// If the linker script produced any errors, some sections may be in an invalid state
if (nbErrors != 0)
reportErrors();
}
// then process them,
obj_DoSanityChecks();
if (nbErrors != 0)
reportErrors();
assign_AssignSections();
obj_CheckAssertions();
assign_Cleanup();
/* and finally output the result. */
// and finally output the result.
patch_ApplyPatches();
if (nbErrors) {
fprintf(stderr, "Linking failed with %" PRIu32 " error%s\n",
nbErrors, nbErrors == 1 ? "" : "s");
exit(1);
}
if (nbErrors != 0)
reportErrors();
out_WriteFiles();
/* Do cleanup before quitting, though. */
// Do cleanup before quitting, though.
cleanup();
}

View File

@@ -18,6 +18,7 @@
#include "link/main.h"
#include "link/object.h"
#include "link/patch.h"
#include "link/sdas_obj.h"
#include "link/section.h"
#include "link/symbol.h"
@@ -38,12 +39,10 @@ static struct {
} *nodes;
static struct Assertion *assertions;
/***** Helper functions for reading object files *****/
// Helper functions for reading object files
/*
* Internal, DO NOT USE.
* For helper wrapper macros defined below, such as `tryReadlong`
*/
// Internal, DO NOT USE.
// For helper wrapper macros defined below, such as `tryReadlong`
#define tryRead(func, type, errval, var, file, ...) \
do { \
FILE *tmpFile = file; \
@@ -57,7 +56,7 @@ static struct Assertion *assertions;
var = tmpVal; \
} while (0)
/**
/*
* Reads an unsigned long (32-bit) value from a file.
* @param file The file to read from. This will read 4 bytes from the file.
* @return The value read, cast to a int64_t, or -1 on failure.
@@ -66,25 +65,24 @@ static int64_t readlong(FILE *file)
{
uint32_t value = 0;
/* Read the little-endian value byte by byte */
// Read the little-endian value byte by byte
for (uint8_t shift = 0; shift < sizeof(value) * CHAR_BIT; shift += 8) {
int byte = getc(file);
if (byte == EOF)
return INT64_MAX;
/* This must be casted to `unsigned`, not `uint8_t`. Rationale:
* the type of the shift is the type of `byte` after undergoing
* integer promotion, which would be `int` if this was casted to
* `uint8_t`, because int is large enough to hold a byte. This
* however causes values larger than 127 to be too large when
* shifted, potentially triggering undefined behavior.
*/
// This must be casted to `unsigned`, not `uint8_t`. Rationale:
// the type of the shift is the type of `byte` after undergoing
// integer promotion, which would be `int` if this was casted to
// `uint8_t`, because int is large enough to hold a byte. This
// however causes values larger than 127 to be too large when
// shifted, potentially triggering undefined behavior.
value |= (unsigned int)byte << shift;
}
return value;
}
/**
/*
* Helper macro for reading longs from a file, and errors out if it fails to.
* Not as a function to avoid overhead in the general case.
* @param var The variable to stash the number into
@@ -95,9 +93,9 @@ static int64_t readlong(FILE *file)
#define tryReadlong(var, file, ...) \
tryRead(readlong, int64_t, INT64_MAX, var, file, __VA_ARGS__)
/* There is no `readbyte`, just use `fgetc` or `getc`. */
// There is no `readbyte`, just use `fgetc` or `getc`.
/**
/*
* Helper macro for reading bytes from a file, and errors out if it fails to.
* Differs from `tryGetc` in that the backing function is fgetc(1).
* Not as a function to avoid overhead in the general case.
@@ -109,7 +107,7 @@ static int64_t readlong(FILE *file)
#define tryFgetc(var, file, ...) \
tryRead(fgetc, int, EOF, var, file, __VA_ARGS__)
/**
/*
* Helper macro for reading bytes from a file, and errors out if it fails to.
* Differs from `tryGetc` in that the backing function is fgetc(1).
* Not as a function to avoid overhead in the general case.
@@ -121,7 +119,7 @@ static int64_t readlong(FILE *file)
#define tryGetc(var, file, ...) \
tryRead(getc, int, EOF, var, file, __VA_ARGS__)
/**
/*
* Reads a '\0'-terminated string from a file.
* @param file The file to read from. The file position will be advanced.
* @return The string read, or NULL on failure.
@@ -129,26 +127,26 @@ static int64_t readlong(FILE *file)
*/
static char *readstr(FILE *file)
{
/* Default buffer size, have it close to the average string length */
// Default buffer size, have it close to the average string length
size_t capacity = 32 / 2;
size_t index = -1;
/* Force the first iteration to allocate */
// Force the first iteration to allocate
char *str = NULL;
do {
/* Prepare going to next char */
// Prepare going to next char
index++;
/* If the buffer isn't suitable to write the next char... */
// If the buffer isn't suitable to write the next char...
if (index >= capacity || !str) {
capacity *= 2;
str = realloc(str, capacity);
/* End now in case of error */
// End now in case of error
if (!str)
return NULL;
}
/* Read char */
// Read char
int byte = getc(file);
if (byte == EOF) {
@@ -160,7 +158,7 @@ static char *readstr(FILE *file)
return str;
}
/**
/*
* Helper macro for reading bytes from a file, and errors out if it fails to.
* Not as a function to avoid overhead in the general case.
* @param var The variable to stash the string into
@@ -171,9 +169,9 @@ static char *readstr(FILE *file)
#define tryReadstr(var, file, ...) \
tryRead(readstr, char*, NULL, var, file, __VA_ARGS__)
/***** Functions to parse object files *****/
// Functions to parse object files
/**
/*
* Reads a file stack node form a file.
* @param file The file to read from
* @param nodes The file's array of nodes
@@ -216,7 +214,7 @@ static void readFileStackNode(FILE *file, struct FileStackNode fileNodes[], uint
}
}
/**
/*
* Reads a symbol from a file.
* @param file The file to read from
* @param symbol The struct to fill
@@ -229,7 +227,7 @@ static void readSymbol(FILE *file, struct Symbol *symbol,
fileName);
tryGetc(symbol->type, file, "%s: Cannot read \"%s\"'s type: %s",
fileName, symbol->name);
/* If the symbol is defined in this file, read its definition */
// If the symbol is defined in this file, read its definition
if (symbol->type != SYMTYPE_IMPORT) {
symbol->objFileName = fileName;
uint32_t nodeID;
@@ -252,7 +250,7 @@ static void readSymbol(FILE *file, struct Symbol *symbol,
}
}
/**
/*
* Reads a patch from a file.
* @param file The file to read from
* @param patch The struct to fill
@@ -302,7 +300,7 @@ static void readPatch(FILE *file, struct Patch *patch, char const *fileName, cha
feof(file) ? "Unexpected end of file" : strerror(errno));
}
/**
/*
* Sets a patch's pcSection from its pcSectionID.
* @param patch The struct to fix
*/
@@ -312,7 +310,7 @@ static void linkPatchToPCSect(struct Patch *patch, struct Section *fileSections[
: fileSections[patch->pcSectionID];
}
/**
/*
* Reads a section from a file.
* @param file The file to read from
* @param section The struct to fill
@@ -371,7 +369,7 @@ static void readSection(FILE *file, struct Section *section, char const *fileNam
section->alignOfs = tmp;
if (sect_HasData(section->type)) {
/* Ensure we never allocate 0 bytes */
// Ensure we never allocate 0 bytes
uint8_t *data = malloc(sizeof(*data) * section->size + 1);
if (!data)
@@ -403,12 +401,12 @@ static void readSection(FILE *file, struct Section *section, char const *fileNam
}
}
/**
/*
* Links a symbol to a section, keeping the section's symbol list sorted.
* @param symbol The symbol to link
* @param section The section to link
*/
static void linkSymToSect(struct Symbol const *symbol, struct Section *section)
static void linkSymToSect(struct Symbol *symbol, struct Section *section)
{
uint32_t a = 0, b = section->nbSymbols;
@@ -421,7 +419,7 @@ static void linkSymToSect(struct Symbol const *symbol, struct Section *section)
a = c + 1;
}
struct Symbol const *tmp = symbol;
struct Symbol *tmp = symbol;
for (uint32_t i = a; i <= section->nbSymbols; i++) {
symbol = tmp;
@@ -432,7 +430,7 @@ static void linkSymToSect(struct Symbol const *symbol, struct Section *section)
section->nbSymbols++;
}
/**
/*
* Reads an assertion from a file
* @param file The file to read from
* @param assert The struct to fill
@@ -466,20 +464,48 @@ void obj_ReadFile(char const *fileName, unsigned int fileID)
if (!file)
err("Could not open file %s", fileName);
/* Begin by reading the magic bytes and version number */
unsigned versionNumber;
int matchedElems = fscanf(file, RGBDS_OBJECT_VERSION_STRING,
&versionNumber);
// First, check if the object is a RGBDS object or a SDCC one. If the first byte is 'R',
// we'll assume it's a RGBDS object file, and otherwise, that it's a SDCC object file.
int c = getc(file);
if (matchedElems != 1)
ungetc(c, file); // Guaranteed to work
switch (c) {
case EOF:
fatal(NULL, 0, "File \"%s\" is empty!", fileName);
case 'R':
break;
default: // This is (probably) a SDCC object file, defer the rest of detection to it
// Since SDCC does not provide line info, everything will be reported as coming from the
// object file. It's better than nothing.
nodes[fileID].nbNodes = 1;
nodes[fileID].nodes = malloc(sizeof(nodes[fileID].nodes[0]) * nodes[fileID].nbNodes);
if (!nodes[fileID].nodes)
err("Failed to get memory for %s's nodes", fileName);
struct FileStackNode *where = &nodes[fileID].nodes[0];
if (!where)
fatal(NULL, 0, "Failed to alloc fstack node for \"%s\": %s", fileName, strerror(errno));
where->parent = NULL;
where->type = NODE_FILE;
where->name = strdup(fileName);
if (!where->name)
fatal(NULL, 0, "Failed to duplicate \"%s\"'s name: %s", fileName, strerror(errno));
sdobj_ReadFile(where, file);
return;
}
// Begin by reading the magic bytes
int matchedElems;
if (fscanf(file, RGBDS_OBJECT_VERSION_STRING "%n", &matchedElems) == 1
&& matchedElems != strlen(RGBDS_OBJECT_VERSION_STRING))
errx("\"%s\" is not a RGBDS object file", fileName);
verbosePrint("Reading object file %s, version %u\n",
fileName, versionNumber);
if (versionNumber != RGBDS_OBJECT_VERSION_NUMBER)
errx("\"%s\" is an incompatible version %u object file",
fileName, versionNumber);
verbosePrint("Reading object file %s\n",
fileName);
uint32_t revNum;
@@ -507,9 +533,8 @@ void obj_ReadFile(char const *fileName, unsigned int fileID)
for (uint32_t i = nodes[fileID].nbNodes; i--; )
readFileStackNode(file, nodes[fileID].nodes, i, fileName);
/* This file's symbols, kept to link sections to them */
struct Symbol **fileSymbols =
malloc(sizeof(*fileSymbols) * nbSymbols + 1);
// This file's symbols, kept to link sections to them
struct Symbol **fileSymbols = malloc(sizeof(*fileSymbols) * nbSymbols + 1);
if (!fileSymbols)
err("Failed to get memory for %s's symbols", fileName);
@@ -528,7 +553,7 @@ void obj_ReadFile(char const *fileName, unsigned int fileID)
verbosePrint("Reading %" PRIu32 " symbols...\n", nbSymbols);
for (uint32_t i = 0; i < nbSymbols; i++) {
/* Read symbol */
// Read symbol
struct Symbol *symbol = malloc(sizeof(*symbol));
if (!symbol)
@@ -542,13 +567,13 @@ void obj_ReadFile(char const *fileName, unsigned int fileID)
nbSymPerSect[symbol->sectionID]++;
}
/* This file's sections, stored in a table to link symbols to them */
// This file's sections, stored in a table to link symbols to them
struct Section **fileSections = malloc(sizeof(*fileSections)
* (nbSections ? nbSections : 1));
verbosePrint("Reading %" PRIu32 " sections...\n", nbSections);
for (uint32_t i = 0; i < nbSections; i++) {
/* Read section */
// Read section
fileSections[i] = malloc(sizeof(*fileSections[i]));
if (!fileSections[i])
err("%s: Couldn't create new section", fileName);
@@ -572,7 +597,7 @@ void obj_ReadFile(char const *fileName, unsigned int fileID)
free(nbSymPerSect);
/* Give patches' PC section pointers to their sections */
// Give patches' PC section pointers to their sections
for (uint32_t i = 0; i < nbSections; i++) {
if (sect_HasData(fileSections[i]->type)) {
for (uint32_t j = 0; j < fileSections[i]->nbPatches; j++)
@@ -580,7 +605,7 @@ void obj_ReadFile(char const *fileName, unsigned int fileID)
}
}
/* Give symbols' section pointers to their sections */
// Give symbols' section pointers to their sections
for (uint32_t i = 0; i < nbSymbols; i++) {
int32_t sectionID = fileSymbols[i]->sectionID;
@@ -589,12 +614,12 @@ void obj_ReadFile(char const *fileName, unsigned int fileID)
} else {
struct Section *section = fileSections[sectionID];
/* Give the section a pointer to the symbol as well */
// Give the section a pointer to the symbol as well
linkSymToSect(fileSymbols[i], section);
if (section->modifier != SECTION_NORMAL) {
if (section->modifier == SECTION_FRAGMENT)
/* Add the fragment's offset to the symbol's */
// Add the fragment's offset to the symbol's
fileSymbols[i]->offset += section->offset;
section = getMainSection(section);
}

View File

@@ -9,6 +9,7 @@
#include <assert.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "link/output.h"
@@ -46,7 +47,7 @@ static struct {
} *banks;
} sections[SECTTYPE_INVALID];
/* Defines the order in which types are output to the sym and map files */
// Defines the order in which types are output to the sym and map files
static enum SectionType typeMap[SECTTYPE_INVALID] = {
SECTTYPE_ROM0,
SECTTYPE_ROMX,
@@ -71,7 +72,7 @@ void out_AddSection(struct Section const *section)
[SECTTYPE_HRAM] = 1
};
uint32_t targetBank = section->bank - bankranges[section->type][0];
uint32_t targetBank = section->bank - sectionTypeInfo[section->type].firstBank;
uint32_t minNbBanks = targetBank + 1;
if (minNbBanks > maxNbBanks[section->type])
@@ -112,7 +113,7 @@ struct Section const *out_OverlappingSection(struct Section const *section)
{
struct SortedSections *banks = sections[section->type].banks;
struct SortedSection *ptr =
banks[section->bank - bankranges[section->type][0]].sections;
banks[section->bank - sectionTypeInfo[section->type].firstBank].sections;
while (ptr) {
if (ptr->section->org < section->org + section->size
@@ -123,7 +124,7 @@ struct Section const *out_OverlappingSection(struct Section const *section)
return NULL;
}
/**
/*
* Performs sanity checks on the overlay file.
* @return The number of ROM banks in the overlay file
*/
@@ -139,7 +140,7 @@ static uint32_t checkOverlaySize(void)
long overlaySize = ftell(overlayFile);
/* Reset back to beginning */
// Reset back to beginning
fseek(overlayFile, 0, SEEK_SET);
if (overlaySize % BANK_SIZE)
@@ -156,7 +157,7 @@ static uint32_t checkOverlaySize(void)
return nbOverlayBanks;
}
/**
/*
* Expand sections[SECTTYPE_ROMX].banks to cover all the overlay banks.
* This ensures that writeROM will output each bank, even if some are not
* covered by any sections.
@@ -164,9 +165,9 @@ static uint32_t checkOverlaySize(void)
*/
static void coverOverlayBanks(uint32_t nbOverlayBanks)
{
/* 2 if is32kMode, 1 otherwise */
uint32_t nbRom0Banks = maxsize[SECTTYPE_ROM0] / BANK_SIZE;
/* Discount ROM0 banks to avoid outputting too much */
// 2 if is32kMode, 1 otherwise
uint32_t nbRom0Banks = sectionTypeInfo[SECTTYPE_ROM0].size / BANK_SIZE;
// Discount ROM0 banks to avoid outputting too much
uint32_t nbUncoveredBanks = nbOverlayBanks - nbRom0Banks > sections[SECTTYPE_ROMX].nbBanks
? nbOverlayBanks - nbRom0Banks
: 0;
@@ -185,7 +186,7 @@ static void coverOverlayBanks(uint32_t nbOverlayBanks)
}
}
/**
/*
* Write a ROM bank's sections to the output file.
* @param bankSections The bank's sections, ordered by increasing address
* @param baseOffset The address of the bank's first byte in GB address space
@@ -199,18 +200,19 @@ static void writeBank(struct SortedSection *bankSections, uint16_t baseOffset,
while (bankSections) {
struct Section const *section = bankSections->section;
/* Output padding up to the next SECTION */
assert(section->offset == 0);
// Output padding up to the next SECTION
while (offset + baseOffset < section->org) {
putc(overlayFile ? getc(overlayFile) : padValue,
outputFile);
offset++;
}
/* Output the section itself */
// Output the section itself
fwrite(section->data, sizeof(*section->data), section->size,
outputFile);
if (overlayFile) {
/* Skip bytes even with pipes */
// Skip bytes even with pipes
for (uint16_t i = 0; i < section->size; i++)
getc(overlayFile);
}
@@ -229,9 +231,7 @@ static void writeBank(struct SortedSection *bankSections, uint16_t baseOffset,
}
}
/**
* Writes a ROM file to the output.
*/
// Writes a ROM file to the output.
static void writeROM(void)
{
outputFile = openFile(outputFileName, "wb");
@@ -245,18 +245,18 @@ static void writeROM(void)
if (outputFile) {
writeBank(sections[SECTTYPE_ROM0].banks ? sections[SECTTYPE_ROM0].banks[0].sections
: NULL,
startaddr[SECTTYPE_ROM0], maxsize[SECTTYPE_ROM0]);
sectionTypeInfo[SECTTYPE_ROM0].startAddr, sectionTypeInfo[SECTTYPE_ROM0].size);
for (uint32_t i = 0 ; i < sections[SECTTYPE_ROMX].nbBanks; i++)
writeBank(sections[SECTTYPE_ROMX].banks[i].sections,
startaddr[SECTTYPE_ROMX], maxsize[SECTTYPE_ROMX]);
sectionTypeInfo[SECTTYPE_ROMX].startAddr, sectionTypeInfo[SECTTYPE_ROMX].size);
}
closeFile(outputFile);
closeFile(overlayFile);
}
/**
/*
* Get the lowest section by address out of the two
* @param s1 One choice
* @param s2 The other
@@ -273,10 +273,8 @@ static struct SortedSection const **nextSection(struct SortedSection const **s1,
return (*s1)->section->org < (*s2)->section->org ? s1 : s2;
}
/*
* Comparator function for `qsort` to sort symbols
* Symbols are ordered by address, or else by original index for a stable sort
*/
// Comparator function for `qsort` to sort symbols
// Symbols are ordered by address, or else by original index for a stable sort
static int compareSymbols(void const *a, void const *b)
{
struct SortedSymbol const *sym1 = (struct SortedSymbol const *)a;
@@ -288,7 +286,7 @@ static int compareSymbols(void const *a, void const *b)
return sym1->idx < sym2->idx ? -1 : sym1->idx > sym2->idx ? 1 : 0;
}
/**
/*
* Write a bank's contents to the sym file
* @param bankSections The bank's sections
*/
@@ -343,7 +341,7 @@ static void writeSymBank(struct SortedSections const *bankSections,
qsort(symList, nbSymbols, sizeof(*symList), compareSymbols);
uint32_t symBank = bank + bankranges[type][0];
uint32_t symBank = bank + sectionTypeInfo[type].firstBank;
for (uint32_t i = 0; i < nbSymbols; i++) {
struct SortedSymbol *sym = &symList[i];
@@ -355,7 +353,7 @@ static void writeSymBank(struct SortedSections const *bankSections,
free(symList);
}
/**
/*
* Write a bank's contents to the map file
* @param bankSections The bank's sections
* @return The bank's used space
@@ -369,10 +367,11 @@ static uint16_t writeMapBank(struct SortedSections const *sectList,
struct SortedSection const *section = sectList->sections;
struct SortedSection const *zeroLenSection = sectList->zeroLenSections;
fprintf(mapFile, "%s bank #%" PRIu32 ":\n", typeNames[type],
bank + bankranges[type][0]);
fprintf(mapFile, "%s bank #%" PRIu32 ":\n", sectionTypeInfo[type].name,
bank + sectionTypeInfo[type].firstBank);
uint16_t used = 0;
uint16_t prevEndAddr = sectionTypeInfo[type].startAddr;
while (section || zeroLenSection) {
struct SortedSection const **pickedSection =
@@ -380,45 +379,69 @@ static uint16_t writeMapBank(struct SortedSections const *sectList,
struct Section const *sect = (*pickedSection)->section;
used += sect->size;
assert(sect->offset == 0);
if (prevEndAddr < sect->org) {
uint16_t empty = sect->org - prevEndAddr;
fprintf(mapFile, " EMPTY: $%04" PRIx16 " byte%s\n", empty,
empty == 1 ? "" : "s");
}
prevEndAddr = sect->org + sect->size;
if (sect->size != 0)
fprintf(mapFile, " SECTION: $%04" PRIx16 "-$%04x ($%04" PRIx16
" byte%s) [\"%s\"]\n",
sect->org, sect->org + sect->size - 1,
sect->org, prevEndAddr - 1,
sect->size, sect->size == 1 ? "" : "s",
sect->name);
else
fprintf(mapFile, " SECTION: $%04" PRIx16 " (0 bytes) [\"%s\"]\n",
sect->org, sect->name);
uint16_t org = sect->org;
if (!noSymInMap) {
uint16_t org = sect->org;
while (sect) {
for (size_t i = 0; i < sect->nbSymbols; i++)
fprintf(mapFile, " $%04" PRIx32 " = %s\n",
sect->symbols[i]->offset + org,
sect->symbols[i]->name);
while (sect) {
if (sect->modifier == SECTION_UNION)
fprintf(mapFile, " ; New union\n");
else if (sect->modifier == SECTION_FRAGMENT)
fprintf(mapFile, " ; New fragment\n");
for (size_t i = 0; i < sect->nbSymbols; i++)
fprintf(mapFile, " $%04" PRIx32 " = %s\n",
sect->symbols[i]->offset + org,
sect->symbols[i]->name);
sect = sect->nextu; // Also print symbols in the following "pieces"
sect = sect->nextu; // Also print symbols in the following "pieces"
}
}
*pickedSection = (*pickedSection)->next;
}
uint16_t bankEndAddr = sectionTypeInfo[type].startAddr + sectionTypeInfo[type].size;
if (prevEndAddr < bankEndAddr) {
uint16_t empty = bankEndAddr - prevEndAddr;
fprintf(mapFile, " EMPTY: $%04" PRIx16 " byte%s\n", empty,
empty == 1 ? "" : "s");
}
if (used == 0) {
fputs(" EMPTY\n\n", mapFile);
} else {
uint16_t slack = maxsize[type] - used;
uint16_t slack = sectionTypeInfo[type].size - used;
fprintf(mapFile, " SLACK: $%04" PRIx16 " byte%s\n\n", slack,
fprintf(mapFile, " SLACK: $%04" PRIx16 " byte%s\n\n", slack,
slack == 1 ? "" : "s");
}
return used;
}
/**
/*
* Write the total used space by section type to the map file
* @param usedMap The total used space by section type
*/
@@ -438,15 +461,13 @@ static void writeMapUsed(uint32_t usedMap[MIN_NB_ELMS(SECTTYPE_INVALID)])
if (sections[type].nbBanks > 0) {
fprintf(mapFile, " %s: $%04" PRIx32 " byte%s in %" PRIu32 " bank%s\n",
typeNames[type], usedMap[type], usedMap[type] == 1 ? "" : "s",
sectionTypeInfo[type].name, usedMap[type], usedMap[type] == 1 ? "" : "s",
sections[type].nbBanks, sections[type].nbBanks == 1 ? "" : "s");
}
}
}
/**
* Writes the sym and/or map files, if applicable.
*/
// Writes the sym and/or map files, if applicable.
static void writeSymAndMap(void)
{
if (!symFileName && !mapFileName)

View File

@@ -63,11 +63,9 @@ static void pushRPN(int32_t value, bool comesFromError)
realloc(stack.values, sizeof(*stack.values) * stack.capacity);
stack.errorFlags =
realloc(stack.errorFlags, sizeof(*stack.errorFlags) * stack.capacity);
/*
* Static analysis tools complain that the capacity might become
* zero due to overflow, but fail to realize that it's caught by
* the overflow check above. Hence the stringent check below.
*/
// Static analysis tools complain that the capacity might become
// zero due to overflow, but fail to realize that it's caught by
// the overflow check above. Hence the stringent check below.
if (!stack.values || !stack.errorFlags || !stack.capacity)
err("Failed to resize RPN stack");
}
@@ -97,7 +95,7 @@ static void freeRPNStack(void)
free(stack.errorFlags);
}
/* RPN operators */
// RPN operators
static uint32_t getRPNByte(uint8_t const **expression, int32_t *size,
struct FileStackNode const *node, uint32_t lineNo)
@@ -111,17 +109,17 @@ static uint32_t getRPNByte(uint8_t const **expression, int32_t *size,
static struct Symbol const *getSymbol(struct Symbol const * const *symbolList,
uint32_t index)
{
assert(index != (uint32_t)-1); /* PC needs to be handled specially, not here */
assert(index != (uint32_t)-1); // PC needs to be handled specially, not here
struct Symbol const *symbol = symbolList[index];
/* If the symbol is defined elsewhere... */
// If the symbol is defined elsewhere...
if (symbol->type == SYMTYPE_IMPORT)
return sym_GetSymbol(symbol->name);
return symbol;
}
/**
/*
* Compute a patch's value from its RPN string.
* @param patch The patch to compute the value of
* @param section The section the patch is contained in
@@ -132,7 +130,7 @@ static struct Symbol const *getSymbol(struct Symbol const * const *symbolList,
static int32_t computeRPNExpr(struct Patch const *patch,
struct Symbol const * const *fileSymbols)
{
/* Small shortcut to avoid a lot of repetition */
// Small shortcut to avoid a lot of repetition
#define popRPN() popRPN(patch->src, patch->lineNo)
uint8_t const *expression = patch->rpnExpression;
@@ -147,13 +145,10 @@ static int32_t computeRPNExpr(struct Patch const *patch,
isError = false;
/*
* Friendly reminder:
* Be VERY careful with two `popRPN` in the same expression.
* C does not guarantee order of evaluation of operands!!
* So, if there are two `popRPN` in the same expression, make
* sure the operation is commutative.
*/
// Be VERY careful with two `popRPN` in the same expression.
// C does not guarantee order of evaluation of operands!!
// So, if there are two `popRPN` in the same expression, make
// sure the operation is commutative.
switch (command) {
struct Symbol const *symbol;
char const *name;
@@ -295,11 +290,9 @@ static int32_t computeRPNExpr(struct Patch const *patch,
break;
case RPN_BANK_SECT:
/*
* `expression` is not guaranteed to be '\0'-terminated. If it is not,
* `getRPNByte` will have a fatal internal error.
* In either case, `getRPNByte` will not free `expression`.
*/
// `expression` is not guaranteed to be '\0'-terminated. If it is not,
// `getRPNByte` will have a fatal internal error.
// In either case, `getRPNByte` will not free `expression`.
name = (char const *)expression;
while (getRPNByte(&expression, &size, patch->src, patch->lineNo))
;
@@ -329,7 +322,7 @@ static int32_t computeRPNExpr(struct Patch const *patch,
break;
case RPN_SIZEOF_SECT:
/* This has assumptions commented in the `RPN_BANK_SECT` case above. */
// This has assumptions commented in the `RPN_BANK_SECT` case above.
name = (char const *)expression;
while (getRPNByte(&expression, &size, patch->src, patch->lineNo))
;
@@ -348,12 +341,13 @@ static int32_t computeRPNExpr(struct Patch const *patch,
break;
case RPN_STARTOF_SECT:
/* This has assumptions commented in the `RPN_BANK_SECT` case above. */
// This has assumptions commented in the `RPN_BANK_SECT` case above.
name = (char const *)expression;
while (getRPNByte(&expression, &size, patch->src, patch->lineNo))
;
sect = sect_GetSection(name);
assert(sect->offset == 0);
if (!sect) {
error(patch->src, patch->lineNo,
@@ -380,9 +374,8 @@ static int32_t computeRPNExpr(struct Patch const *patch,
case RPN_RST:
value = popRPN();
/* Acceptable values are 0x00, 0x08, 0x10, ..., 0x38
* They can be easily checked with a bitmask
*/
// Acceptable values are 0x00, 0x08, 0x10, ..., 0x38
// They can be easily checked with a bitmask
if (value & ~0x38) {
if (!isError)
error(patch->src, patch->lineNo,
@@ -405,7 +398,7 @@ static int32_t computeRPNExpr(struct Patch const *patch,
value |= getRPNByte(&expression, &size,
patch->src, patch->lineNo) << shift;
if (value == -1) { /* PC */
if (value == -1) { // PC
if (!patch->pcSection) {
error(patch->src, patch->lineNo,
"PC has no value outside a section");
@@ -423,7 +416,7 @@ static int32_t computeRPNExpr(struct Patch const *patch,
isError = true;
} else {
value = symbol->value;
/* Symbols attached to sections have offsets */
// Symbols attached to sections have offsets
if (symbol->section)
value += symbol->section->org;
}
@@ -460,8 +453,8 @@ void patch_CheckAssertions(struct Assertion *assert)
fatal(assert->patch.src, assert->patch.lineNo, "%s",
assert->message[0] ? assert->message
: "assert failure");
/* Not reached */
break; /* Here so checkpatch doesn't complain */
// Not reached
break; // Here so checkpatch doesn't complain
case ASSERT_ERROR:
error(assert->patch.src, assert->patch.lineNo, "%s",
assert->message[0] ? assert->message
@@ -490,16 +483,13 @@ void patch_CheckAssertions(struct Assertion *assert)
freeRPNStack();
}
/**
/*
* Applies all of a section's patches
* @param section The section to patch
* @param arg Ignored callback arg
*/
static void applyFilePatches(struct Section *section, struct Section *dataSection)
{
if (!sect_HasData(section->type))
return;
verbosePrint("Patching section \"%s\"...\n", section->name);
for (uint32_t patchID = 0; patchID < section->nbPatches; patchID++) {
struct Patch *patch = &section->patches[patchID];
@@ -508,12 +498,11 @@ static void applyFilePatches(struct Section *section, struct Section *dataSectio
section->fileSymbols);
uint16_t offset = patch->offset + section->offset;
/* `jr` is quite unlike the others... */
// `jr` is quite unlike the others...
if (patch->type == PATCHTYPE_JR) {
// Offset is relative to the byte *after* the operand
// PC as operand to `jr` is lower than reference PC by 2
uint16_t address = patch->pcSection->org
+ patch->pcOffset + 2;
uint16_t address = patch->pcSection->org + patch->pcOffset + 2;
int16_t jumpOffset = value - address;
if (!isError && (jumpOffset < -128 || jumpOffset > 127))
@@ -522,7 +511,7 @@ static void applyFilePatches(struct Section *section, struct Section *dataSectio
jumpOffset);
dataSection->data[offset] = jumpOffset & 0xFF;
} else {
/* Patch a certain number of bytes */
// Patch a certain number of bytes
struct {
uint8_t size;
int32_t min;
@@ -547,7 +536,7 @@ static void applyFilePatches(struct Section *section, struct Section *dataSectio
}
}
/**
/*
* Applies all of a section's patches, iterating over "components" of
* unionized sections
* @param section The section to patch
@@ -555,6 +544,9 @@ static void applyFilePatches(struct Section *section, struct Section *dataSectio
*/
static void applyPatches(struct Section *section, void *arg)
{
if (!sect_HasData(section->type))
return;
(void)arg;
struct Section *dataSection = section;

View File

@@ -18,6 +18,7 @@
#include "link/section.h"
#include "error.h"
#include "linkdefs.h"
FILE *linkerScript;
char *includeFileName;
@@ -40,7 +41,7 @@ static void pushFile(char *newFileName)
linkerScriptName, lineNo);
if (fileStackIndex == fileStackSize) {
if (!fileStackSize) /* Init file stack */
if (!fileStackSize) // Init file stack
fileStackSize = 4;
fileStackSize *= 2;
fileStack = realloc(fileStack, sizeof(*fileStack) * fileStackSize);
@@ -87,7 +88,7 @@ static bool isNewline(int c)
return c == '\r' || c == '\n';
}
/**
/*
* Try parsing a number, in base 16 if it begins with a dollar,
* in base 10 otherwise
* @param str The number to parse
@@ -107,7 +108,7 @@ static bool tryParseNumber(char const *str, uint32_t *number)
base = 16;
}
/* An empty string is not a number */
// An empty string is not a number
if (!*str)
return false;
@@ -187,16 +188,16 @@ static struct LinkerScriptToken *nextToken(void)
static struct LinkerScriptToken token;
int curchar;
/* If the token has a string, make sure to avoid leaking it */
// If the token has a string, make sure to avoid leaking it
if (token.type == TOKEN_STRING)
free(token.attr.string);
/* Skip initial whitespace... */
// Skip initial whitespace...
do
curchar = nextChar();
while (isWhiteSpace(curchar));
/* If this is a comment, skip to the end of the line */
// If this is a comment, skip to the end of the line
if (curchar == ';') {
do {
curchar = nextChar();
@@ -206,22 +207,22 @@ static struct LinkerScriptToken *nextToken(void)
if (curchar == EOF) {
token.type = TOKEN_EOF;
} else if (isNewline(curchar)) {
/* If we have a newline char, this is a newline token */
// If we have a newline char, this is a newline token
token.type = TOKEN_NEWLINE;
if (curchar == '\r') {
/* Handle CRLF */
// Handle CRLF
curchar = nextChar();
if (curchar != '\n')
ungetc(curchar, linkerScript);
}
} else if (curchar == '"') {
/* If we have a string start, this is a string */
// If we have a string start, this is a string
token.type = TOKEN_STRING;
token.attr.string = NULL; /* Force initial alloc */
token.attr.string = NULL; // Force initial alloc
size_t size = 0;
size_t capacity = 16; /* Half of the default capacity */
size_t capacity = 16; // Half of the default capacity
do {
curchar = nextChar();
@@ -229,10 +230,10 @@ static struct LinkerScriptToken *nextToken(void)
errx("%s(%" PRIu32 "): Unterminated string",
linkerScriptName, lineNo);
} else if (curchar == '"') {
/* Quotes force a string termination */
// Quotes force a string termination
curchar = '\0';
} else if (curchar == '\\') {
/* Backslashes are escape sequences */
// Backslashes are escape sequences
curchar = nextChar();
if (curchar == EOF || isNewline(curchar))
errx("%s(%" PRIu32 "): Unterminated string",
@@ -258,10 +259,10 @@ static struct LinkerScriptToken *nextToken(void)
token.attr.string[size++] = curchar;
} while (curchar);
} else {
/* This is either a number, command or bank, that is: a word */
// This is either a number, command or bank, that is: a word
char *str = NULL;
size_t size = 0;
size_t capacity = 8; /* Half of the default capacity */
size_t capacity = 8; // Half of the default capacity
for (;;) {
if (size >= capacity || str == NULL) {
@@ -278,7 +279,7 @@ static struct LinkerScriptToken *nextToken(void)
break;
curchar = nextChar();
/* Whitespace, a newline or a comment end the token */
// Whitespace, a newline or a comment end the token
if (isWhiteSpace(curchar) || isNewline(curchar) || curchar == ';') {
ungetc(curchar, linkerScript);
curchar = '\0';
@@ -287,7 +288,7 @@ static struct LinkerScriptToken *nextToken(void)
token.type = TOKEN_INVALID;
/* Try to match a command */
// Try to match a command
for (enum LinkerScriptCommand i = 0; i < COMMAND_INVALID; i++) {
if (!strcmp(commands[i], str)) {
token.type = TOKEN_COMMAND;
@@ -297,9 +298,9 @@ static struct LinkerScriptToken *nextToken(void)
}
if (token.type == TOKEN_INVALID) {
/* Try to match a bank specifier */
// Try to match a bank specifier
for (enum SectionType type = 0; type < SECTTYPE_INVALID; type++) {
if (!strcmp(typeNames[type], str)) {
if (!strcmp(sectionTypeInfo[type].name, str)) {
token.type = TOKEN_BANK;
token.attr.secttype = type;
break;
@@ -308,13 +309,13 @@ static struct LinkerScriptToken *nextToken(void)
}
if (token.type == TOKEN_INVALID) {
/* Try to match an include token */
// Try to match an include token
if (!strcmp("INCLUDE", str))
token.type = TOKEN_INCLUDE;
}
if (token.type == TOKEN_INVALID) {
/* None of the strings matched, do we have a number? */
// None of the strings matched, do we have a number?
if (tryParseNumber(str, &token.attr.number))
token.type = TOKEN_NUMBER;
else
@@ -353,34 +354,33 @@ static void processCommand(enum LinkerScriptCommand command, uint16_t arg, uint1
enum LinkerScriptParserState {
PARSER_FIRSTTIME,
PARSER_LINESTART,
PARSER_INCLUDE, /* After an INCLUDE token */
PARSER_INCLUDE, // After an INCLUDE token
PARSER_LINEEND
};
/* Part of internal state, but has data that needs to be freed */
// Part of internal state, but has data that needs to be freed
static uint16_t *curaddr[SECTTYPE_INVALID];
/* Put as global to ensure it's initialized only once */
// Put as global to ensure it's initialized only once
static enum LinkerScriptParserState parserState = PARSER_FIRSTTIME;
struct SectionPlacement *script_NextSection(void)
{
static struct SectionPlacement section;
static enum SectionType type;
static struct SectionPlacement placement;
static uint32_t bank;
static uint32_t bankID;
if (parserState == PARSER_FIRSTTIME) {
lineNo = 1;
/* Init PC for all banks */
// Init PC for all banks
for (enum SectionType i = 0; i < SECTTYPE_INVALID; i++) {
curaddr[i] = malloc(sizeof(*curaddr[i]) * nbbanks(i));
for (uint32_t b = 0; b < nbbanks(i); b++)
curaddr[i][b] = startaddr[i];
curaddr[i][b] = sectionTypeInfo[i].startAddr;
}
type = SECTTYPE_INVALID;
placement.type = SECTTYPE_INVALID;
parserState = PARSER_LINESTART;
}
@@ -392,15 +392,15 @@ struct SectionPlacement *script_NextSection(void)
bool hasArg;
uint32_t arg;
if (type != SECTTYPE_INVALID) {
if (curaddr[type][bankID] > endaddr(type) + 1)
if (placement.type != SECTTYPE_INVALID) {
if (curaddr[placement.type][bankID] > endaddr(placement.type) + 1)
errx("%s(%" PRIu32 "): Sections would extend past the end of %s ($%04" PRIx16 " > $%04" PRIx16 ")",
linkerScriptName, lineNo, typeNames[type],
curaddr[type][bankID], endaddr(type));
if (curaddr[type][bankID] < startaddr[type])
linkerScriptName, lineNo, sectionTypeInfo[placement.type].name,
curaddr[placement.type][bankID], endaddr(placement.type));
if (curaddr[placement.type][bankID] < sectionTypeInfo[placement.type].startAddr)
errx("%s(%" PRIu32 "): PC underflowed ($%04" PRIx16 " < $%04" PRIx16 ")",
linkerScriptName, lineNo,
curaddr[type][bankID], startaddr[type]);
curaddr[placement.type][bankID], sectionTypeInfo[placement.type].startAddr);
}
switch (parserState) {
@@ -427,25 +427,25 @@ struct SectionPlacement *script_NextSection(void)
lineNo++;
break;
/* A stray string is a section name */
// A stray string is a section name
case TOKEN_STRING:
parserState = PARSER_LINEEND;
if (type == SECTTYPE_INVALID)
if (placement.type == SECTTYPE_INVALID)
errx("%s(%" PRIu32 "): Didn't specify a location before the section",
linkerScriptName, lineNo);
section.section =
placement.section =
sect_GetSection(token->attr.string);
if (!section.section)
if (!placement.section)
errx("%s(%" PRIu32 "): Unknown section \"%s\"",
linkerScriptName, lineNo,
token->attr.string);
section.org = curaddr[type][bankID];
section.bank = bank;
placement.org = curaddr[placement.type][bankID];
placement.bank = bank;
curaddr[type][bankID] += section.section->size;
return &section;
curaddr[placement.type][bankID] += placement.section->size;
return &placement;
case TOKEN_COMMAND:
case TOKEN_BANK:
@@ -454,50 +454,44 @@ struct SectionPlacement *script_NextSection(void)
token = nextToken();
hasArg = token->type == TOKEN_NUMBER;
/*
* Leaving `arg` uninitialized when `!hasArg`
* causes GCC to warn about its use as an
* argument to `processCommand`. This cannot
* happen because `hasArg` has to be true, but
* silence the warning anyways.
* I dislike doing this because it could swallow
* actual errors, but I don't have a choice.
*/
// Leaving `arg` uninitialized when `!hasArg` causes GCC to warn
// about its use as an argument to `processCommand`. This cannot
// happen because `hasArg` has to be true, but silence the warning
// anyways. I dislike doing this because it could swallow actual
// errors, but I don't have a choice.
arg = hasArg ? token->attr.number : 0;
if (tokType == TOKEN_COMMAND) {
if (type == SECTTYPE_INVALID)
if (placement.type == SECTTYPE_INVALID)
errx("%s(%" PRIu32 "): Didn't specify a location before the command",
linkerScriptName, lineNo);
if (!hasArg)
errx("%s(%" PRIu32 "): Command specified without an argument",
linkerScriptName, lineNo);
processCommand(attr.command, arg, &curaddr[type][bankID]);
} else { /* TOKEN_BANK */
type = attr.secttype;
/*
* If there's only one bank,
* specifying the number is optional.
*/
if (!hasArg && nbbanks(type) != 1)
processCommand(attr.command, arg, &curaddr[placement.type][bankID]);
} else { // TOKEN_BANK
placement.type = attr.secttype;
// If there's only one bank,
// specifying the number is optional.
if (!hasArg && nbbanks(placement.type) != 1)
errx("%s(%" PRIu32 "): Didn't specify a bank number",
linkerScriptName, lineNo);
else if (!hasArg)
arg = bankranges[type][0];
else if (arg < bankranges[type][0])
arg = sectionTypeInfo[placement.type].firstBank;
else if (arg < sectionTypeInfo[placement.type].firstBank)
errx("%s(%" PRIu32 "): specified bank number is too low (%" PRIu32 " < %" PRIu32 ")",
linkerScriptName, lineNo,
arg, bankranges[type][0]);
else if (arg > bankranges[type][1])
arg, sectionTypeInfo[placement.type].firstBank);
else if (arg > sectionTypeInfo[placement.type].lastBank)
errx("%s(%" PRIu32 "): specified bank number is too high (%" PRIu32 " > %" PRIu32 ")",
linkerScriptName, lineNo,
arg, bankranges[type][1]);
arg, sectionTypeInfo[placement.type].lastBank);
bank = arg;
bankID = arg - bankranges[type][0];
bankID = arg - sectionTypeInfo[placement.type].firstBank;
}
/* If we read a token we shouldn't have... */
// If we read a token we shouldn't have...
if (token->type != TOKEN_NUMBER)
goto lineend;
break;
@@ -513,9 +507,9 @@ struct SectionPlacement *script_NextSection(void)
errx("%s(%" PRIu32 "): Expected a file name after INCLUDE",
linkerScriptName, lineNo);
/* Switch to that file */
// Switch to that file
pushFile(token->attr.string);
/* The file stack took ownership of the string */
// The file stack took ownership of the string
token->attr.string = NULL;
parserState = PARSER_LINESTART;

766
src/link/sdas_obj.c Normal file
View File

@@ -0,0 +1,766 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2022, Eldred Habert and RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linkdefs.h"
#include "platform.h"
#include "link/assign.h"
#include "link/main.h"
#include "link/sdas_obj.h"
#include "link/section.h"
#include "link/symbol.h"
enum NumberType {
HEX = 16, // X
DEC = 10, // D
OCT = 8, // Q
};
static void consumeLF(struct FileStackNode const *where, uint32_t lineNo, FILE *file) {
if (getc(file) != '\n')
fatal(where, lineNo, "Bad line ending (CR without LF)");
}
static char const *delim = " \f\n\r\t\v"; // Whitespace according to the C and POSIX locales
static int nextLine(char **restrict lineBuf, size_t *restrict bufLen, uint32_t *restrict lineNo, struct FileStackNode const *where, FILE *file) {
retry:
++*lineNo;
int firstChar = getc(file);
switch (firstChar) {
case EOF:
return EOF;
case ';':
// Discard comment line
// TODO: if `;!FILE [...]` on the first line (`lineNo`), return it
do {
firstChar = getc(file);
} while (firstChar != EOF && firstChar != '\r' && firstChar != '\n');
// fallthrough
case '\r':
if (firstChar == '\r' && getc(file) != '\n')
consumeLF(where, *lineNo, file);
// fallthrough
case '\n':
goto retry;
}
size_t i = 0;
for (;;) {
if (i >= *bufLen) {
assert(*bufLen != 0);
*bufLen *= 2;
*lineBuf = realloc(*lineBuf, *bufLen);
if (!*lineBuf)
fatal(where, *lineNo, "Failed to realloc: %s", strerror(errno));
}
int c = getc(file);
switch (c) {
case '\r':
consumeLF(where, *lineNo, file);
// fallthrough
case '\n':
case EOF:
(*lineBuf)[i] = '\0'; // Terminate the string (space was ensured above)
return firstChar;
}
(*lineBuf)[i] = c;
++i;
}
}
static uint32_t readNumber(char const *restrict str, char const **endptr, enum NumberType base) {
uint32_t res = 0;
for (;;) {
static char const *digits = "0123456789ABCDEF";
char const *ptr = strchr(digits, toupper(*str));
if (!ptr || ptr - digits >= base) {
*endptr = str;
return res;
}
++str;
res = res * base + (ptr - digits);
}
}
static uint32_t parseNumber(struct FileStackNode const *where, uint32_t lineNo, char const *restrict str, enum NumberType base) {
if (str[0] == '\0')
fatal(where, lineNo, "Expected number, got empty string");
char const *endptr;
uint32_t res = readNumber(str, &endptr, base);
if (*endptr != '\0')
fatal(where, lineNo, "Expected number, got \"%s\"", str);
return res;
}
static uint8_t parseByte(struct FileStackNode const *where, uint32_t lineNo, char const *restrict str, enum NumberType base) {
uint32_t num = parseNumber(where, lineNo, str, base);
if (num > UINT8_MAX)
fatal(where, lineNo, "\"%s\" is not a byte", str);
return num;
}
enum AreaFlags {
AREA_TYPE = 2, // 0: Concatenate, 1: overlay
AREA_ISABS, // 0: Relative (???) address, 1: absolute address
AREA_PAGING, // Unsupported
AREA_ALL_FLAGS = 1 << AREA_TYPE | 1 << AREA_ISABS | 1 << AREA_PAGING,
};
enum RelocFlags {
RELOC_SIZE, // 0: 16-bit, 1: 8-bit
RELOC_ISSYM, // 0: Area, 1: Symbol
RELOC_ISPCREL, // 0: Normal, 1: PC-relative
RELOC_EXPR16, // Only for 8-bit size; 0: 8-bit expr, 1: 16-bit expr
RELOC_SIGNED, // 0: signed, 1: unsigned
RELOC_ZPAGE, // Unsupported
RELOC_NPAGE, // Unsupported
RELOC_WHICHBYTE, // 8-bit size with 16-bit expr only; 0: LOW(), 1: HIGH()
RELOC_EXPR24, // Only for 8-bit size; 0: follow RELOC_EXPR16, 1: 24-bit expr
RELOC_BANKBYTE, // 8-bit size with 24-bit expr only; 0: follow RELOC_WHICHBYTE, 1: BANK()
RELOC_ALL_FLAGS = 1 << RELOC_SIZE | 1 << RELOC_ISSYM | 1 << RELOC_ISPCREL | 1 << RELOC_EXPR16
| 1 << RELOC_SIGNED | 1 << RELOC_ZPAGE | 1 << RELOC_NPAGE | 1 << RELOC_WHICHBYTE
| 1 << RELOC_EXPR24 | 1 << RELOC_BANKBYTE,
};
void sdobj_ReadFile(struct FileStackNode const *where, FILE *file) {
size_t bufLen = 256;
char *line = malloc(bufLen);
char const *token;
#define getToken(ptr, ...) do { \
token = strtok((ptr), delim); \
if (!token) \
fatal(where, lineNo, __VA_ARGS__); \
} while (0)
#define expectEol(...) do { \
token = strtok(NULL, delim); \
if (token) \
fatal(where, lineNo, __VA_ARGS__); \
} while (0)
#define expectToken(expected, lineType) do { \
getToken(NULL, "'%c' line is too short", (lineType)); \
if (strcasecmp(token, (expected)) != 0) \
fatal(where, lineNo, "Malformed '%c' line: expected \"%s\", got \"%s\"", (lineType), (expected), token); \
} while (0)
if (!line)
fatal(where, 0, "Failed to alloc a line buffer: %s", strerror(errno));
uint32_t lineNo = 0;
int lineType = nextLine(&line, &bufLen, &lineNo, where, file);
enum NumberType numberType;
// The first letter (thus, the line type) identifies the integer type
switch (lineType) {
case EOF:
fatal(where, lineNo, "SDCC object only contains comments and empty lines");
case 'X':
numberType = HEX;
break;
case 'D':
numberType = DEC;
break;
case 'Q':
numberType = OCT;
break;
default:
fatal(where, lineNo, "This does not look like a SDCC object file (unknown integer format '%c')", lineType);
}
switch (line[0]) {
case 'L':
break;
case 'H':
fatal(where, lineNo, "Big-endian SDCC object files are not supported");
default:
fatal(where, lineNo, "Unknown endianness type '%c'", line[0]);
}
#define ADDR_SIZE 3
if (line[1] != '0' + ADDR_SIZE)
fatal(where, lineNo, "Unknown or unsupported address size '%c'", line[1]);
if (line[2] != '\0')
warning(where, lineNo, "Ignoring unknown characters (\"%s\") in first line", &line[2]);
// Header line
lineType = nextLine(&line, &bufLen, &lineNo, where, file);
if (lineType != 'H')
fatal(where, lineNo, "Expected header line, got '%c' line", lineType);
// Expected format: "A areas S global symbols"
getToken(line, "Empty 'H' line");
uint32_t expectedNbAreas = parseNumber(where, lineNo, token, numberType);
expectToken("areas", 'H');
getToken(NULL, "'H' line is too short");
uint32_t expectedNbSymbols = parseNumber(where, lineNo, token, numberType);
expectToken("global", 'H');
expectToken("symbols", 'H');
expectEol("'H' line is too long");
// Now, let's parse the rest of the lines as they come!
struct {
struct Section *section;
uint16_t writeIndex;
} *fileSections = NULL;
struct Symbol **fileSymbols = malloc(sizeof(*fileSymbols) * expectedNbSymbols);
size_t nbSections = 0, nbSymbols = 0;
if (!fileSymbols)
fatal(where, lineNo, "Failed to alloc file symbols table: %s", strerror(errno));
size_t nbBytes = 0; // How many bytes are in `data`, including the ADDR_SIZE "header" bytes
size_t dataCapacity = 16 + ADDR_SIZE; // SDCC object files usually contain 16 bytes per T line
uint8_t *data = malloc(sizeof(*data) * dataCapacity);
if (!data)
fatal(where, lineNo, "Failed to alloc data buffer: %s", strerror(errno));
for (;;) {
lineType = nextLine(&line, &bufLen, &lineNo, where, file);
if (lineType == EOF)
break;
switch (lineType) {
uint32_t tmp;
case 'M': // Module name
case 'O': // Assembler flags
// Ignored
break;
case 'A':
if (nbSections == expectedNbAreas)
warning(where, lineNo, "Got more 'A' lines than the expected %" PRIu32, expectedNbAreas);
fileSections = realloc(fileSections, sizeof(*fileSections) * (nbSections + 1));
if (!fileSections)
fatal(where, lineNo, "Failed to realloc file areas: %s", strerror(errno));
fileSections[nbSections].writeIndex = 0;
#define curSection (fileSections[nbSections].section)
curSection = malloc(sizeof(*curSection));
if (!curSection)
fatal(where, lineNo, "Failed to alloc new area: %s", strerror(errno));
getToken(line, "'A' line is too short");
assert(strlen(token) != 0); // This should be impossible, tokens are non-empty
curSection->name = strdup(token); // We need a pointer that will live longer
if (!curSection->name)
fatal(where, lineNo, "Failed to alloc new area's name: %s", strerror(errno));
// The following is required for fragment offsets to be reliably predicted
for (size_t i = 0; i < nbSections; ++i) {
if (!strcmp(token, fileSections[i].section->name))
fatal(where, lineNo, "Area \"%s\" already defined earlier", token);
}
expectToken("size", 'A');
getToken(NULL, "'A' line is too short");
tmp = parseNumber(where, lineNo, token, numberType);
if (tmp > UINT16_MAX)
fatal(where, lineNo, "Area \"%s\" is larger than the GB address space!?", curSection->name);
curSection->size = tmp;
expectToken("flags", 'A');
getToken(NULL, "'A' line is too short");
tmp = parseNumber(where, lineNo, token, numberType);
if (tmp & (1 << AREA_PAGING))
fatal(where, lineNo, "Internal error: paging is not supported");
curSection->isAddressFixed = tmp & (1 << AREA_ISABS);
curSection->isBankFixed = curSection->isAddressFixed;
curSection->modifier = curSection->isAddressFixed || (tmp & (1 << AREA_TYPE))
? SECTION_NORMAL : SECTION_FRAGMENT;
expectToken("addr", 'A');
getToken(NULL, "'A' line is too short");
tmp = parseNumber(where, lineNo, token, numberType);
curSection->org = tmp; // Truncation keeps the address portion only
curSection->bank = tmp >> 16;
expectEol("'A' line is too long");
// Init the rest of the members
curSection->offset = 0;
if (curSection->isAddressFixed) {
uint8_t high = curSection->org >> 8;
if (high < 0x40) {
curSection->type = SECTTYPE_ROM0;
} else if (high < 0x80) {
curSection->type = SECTTYPE_ROMX;
} else if (high < 0xA0) {
curSection->type = SECTTYPE_VRAM;
} else if (high < 0xC0) {
curSection->type = SECTTYPE_SRAM;
} else if (high < 0xD0) {
curSection->type = SECTTYPE_WRAM0;
} else if (high < 0xE0) {
curSection->type = SECTTYPE_WRAMX;
} else if (high < 0xFE) {
fatal(where, lineNo, "Areas in echo RAM are not supported");
} else if (high < 0xFF) {
curSection->type = SECTTYPE_OAM;
} else {
curSection->type = SECTTYPE_HRAM;
}
} else {
curSection->type = SECTTYPE_INVALID; // This means "indeterminate"
}
curSection->isAlignFixed = false; // No such concept!
// The array will be allocated if the section does contain data
curSection->data = NULL;
curSection->nbPatches = 0;
curSection->patches = NULL; // Same as `data`
curSection->fileSymbols = fileSymbols; // IDs are instead per-section
curSection->nbSymbols = 0;
curSection->symbols = NULL; // Will be allocated on demand as well
curSection->nextu = NULL;
#undef curSection
++nbSections;
break;
case 'S':
if (nbSymbols == expectedNbSymbols)
warning(where, lineNo, "Got more 'S' lines than the expected %" PRIu32, expectedNbSymbols);
// `realloc` is dangerous, as sections contain a pointer to `fileSymbols`.
// We can try to be nice, but if the pointer moves, it's game over!
if (nbSymbols >= expectedNbSymbols) {
struct Symbol **newFileSymbols = realloc(fileSymbols, sizeof(*fileSymbols) * (nbSymbols + 1));
if (!newFileSymbols)
fatal(where, lineNo, "Failed to alloc extra symbols: %s", strerror(errno));
if (newFileSymbols != fileSymbols)
fatal(where, lineNo, "Couldn't handle extra 'S' lines (pointer moved)");
// No need to assign, obviously
}
#define symbol (fileSymbols[nbSymbols])
symbol = malloc(sizeof(*symbol));
if (!symbol)
fatal(where, lineNo, "Failed to alloc symbol: %s", strerror(errno));
// Init other members
symbol->objFileName = where->name;
symbol->src = where;
symbol->lineNo = lineNo;
// No need to set the `sectionID`, since we can directly set the pointer
symbol->section = fileSections ? fileSections[nbSections - 1].section : NULL;
getToken(line, "'S' line is too short");
symbol->name = strdup(token);
if (!symbol->name)
fatal(where, lineNo, "Failed to alloc symbol name: %s", strerror(errno));
getToken(NULL, "'S' line is too short");
// It might be an `offset`, but both types are the same so type punning is fine
symbol->value = parseNumber(where, lineNo, &token[3], numberType);
if (symbol->section && symbol->section->isAddressFixed) {
assert(symbol->offset >= symbol->section->org);
symbol->offset -= symbol->section->org;
assert(symbol->offset <= symbol->section->size);
}
// Expected format: /[DR]ef[0-9A-F]+/i
if (token[0] == 'R' || token[0] == 'r') {
symbol->type = SYMTYPE_IMPORT;
// TODO: hard error if the rest is not zero
} else if (token[0] != 'D' && token[0] != 'd') {
fatal(where, lineNo, "'S' line is neither \"Def\" nor \"Ref\"");
} else {
// All symbols are exported
symbol->type = SYMTYPE_EXPORT;
struct Symbol const *other = sym_GetSymbol(symbol->name);
if (other) {
// The same symbol can only be defined twice if neither
// definition is in a floating section
if ((other->section && !other->section->isAddressFixed)
|| (symbol->section && !symbol->section->isAddressFixed)) {
sym_AddSymbol(symbol); // This will error out
} else if (other->value != symbol->value) {
error(where, lineNo,
"Definition of \"%s\" conflicts with definition in %s (%" PRId32 " != %" PRId32 ")",
symbol->name, other->objFileName, symbol->value, other->value);
}
} else {
// Add a new definition
sym_AddSymbol(symbol);
}
// It's fine to keep modifying the symbol after `AddSymbol`, only
// the name must not be modified
}
if (strncasecmp(&token[1], "ef", 2) != 0)
fatal(where, lineNo, "'S' line is neither \"Def\" nor \"Ref\"");
if (nbSections != 0) {
struct Section *section = fileSections[nbSections - 1].section;
++section->nbSymbols;
section->symbols = realloc(section->symbols, sizeof(section->symbols[0]) * section->nbSymbols);
if (!section->symbols)
fatal(where, lineNo, "Failed to realloc \"%s\"'s symbol list: %s", section->name, strerror(errno));
section->symbols[section->nbSymbols - 1] = symbol;
}
#undef symbol
expectEol("'S' line is too long");
++nbSymbols;
break;
case 'T':
// Now, time to parse the data!
if (nbBytes != 0)
warning(where, lineNo, "Previous 'T' line had no 'R' line (ignored)");
nbBytes = 0;
for (token = strtok(line, delim); token; token = strtok(NULL, delim)) {
if (dataCapacity == nbBytes) {
dataCapacity *= 2;
data = realloc(data, sizeof(*data) * dataCapacity);
if (!data)
fatal(where, lineNo, "Failed to realloc data buffer: %s", strerror(errno));
}
data[nbBytes] = parseByte(where, lineNo, token, numberType);
++nbBytes;
}
if (nbBytes < ADDR_SIZE)
fatal(where, lineNo, "'T' line is too short");
// Importantly, now we know that `nbBytes != 0`, which means "pending data"
break;
case 'R': // Supposed to directly follow `T`
if (nbBytes == 0) {
warning(where, lineNo, "'R' line with no 'T' line, ignoring");
break;
}
// First two bytes are ignored
getToken(line, "'R' line is too short");
getToken(NULL, "'R' line is too short");
uint16_t areaIdx;
getToken(NULL, "'R' line is too short");
areaIdx = parseByte(where, lineNo, token, numberType);
getToken(NULL, "'R' line is too short");
areaIdx |= (uint16_t)parseByte(where, lineNo, token, numberType) << 8;
if (areaIdx >= nbSections)
fatal(where, lineNo, "'R' line references area #%" PRIu16 ", but there are only %zu (so far)", areaIdx, nbSections);
assert(fileSections); // There should be at least one, from the above check
struct Section *section = fileSections[areaIdx].section;
uint16_t *writeIndex = &fileSections[areaIdx].writeIndex;
uint8_t writtenOfs = ADDR_SIZE; // Bytes before this have been written to ->data
uint16_t addr = data[0] | data[1] << 8;
if (section->isAddressFixed) {
if (addr < section->org)
fatal(where, lineNo, "'T' line reports address $%04" PRIx16 " in \"%s\", which starts at $%04" PRIx16, addr, section->name, section->org);
addr -= section->org;
}
// Lines are emitted that violate this check but contain no "payload";
// ignore those. "Empty" lines shouldn't trigger allocation, either.
if (nbBytes != ADDR_SIZE) {
if (addr != *writeIndex)
fatal(where, lineNo, "'T' lines which don't append to their section are not supported (%" PRIu16 " != %" PRIu16 ")", addr, *writeIndex);
if (!section->data) {
assert(section->size != 0);
section->data = malloc(section->size);
if (!section->data)
fatal(where, lineNo, "Failed to alloc data for \"%s\": %s", section->name, strerror(errno));
}
}
// Processing relocations is made difficult by SDLD's honestly quite bonkers
// handling of the thing.
// The way they work is that 16-bit relocs are, simply enough, writing a
// 16-bit value over a 16-bit "gap". Nothing weird here.
// 8-bit relocs, however, do not write an 8-bit value over an 8-bit gap!
// They write an 8-bit value over a 16-bit gap... and either of the two
// bytes is *discarded*. The "24-bit" flag extends this behavior to three
// bytes instead of two, but the idea's the same.
// Additionally, the "offset" is relative to *before* bytes from previous
// relocs are removed, so this needs to be accounted for as well.
// This all can be "translated" to RGBDS parlance by generating the
// appropriate RPN expression (depending on flags), plus an addition for the
// bytes being patched over.
while ((token = strtok(NULL, delim)) != NULL) {
uint16_t flags = parseByte(where, lineNo, token, numberType);
if ((flags & 0xF0) == 0xF0) {
getToken(NULL, "Incomplete relocation");
flags = (flags & 0x0F) | (uint16_t)parseByte(where, lineNo, token, numberType) << 4;
}
getToken(NULL, "Incomplete relocation");
uint8_t offset = parseByte(where, lineNo, token, numberType);
if (offset < ADDR_SIZE)
fatal(where, lineNo, "Relocation index cannot point to header (%" PRIu16 " < %u)", offset, ADDR_SIZE);
if (offset >= nbBytes)
fatal(where, lineNo, "Relocation index is out of bounds (%" PRIu16 " >= %zu)", offset, nbBytes);
getToken(NULL, "Incomplete relocation");
uint16_t idx = parseByte(where, lineNo, token, numberType);
getToken(NULL, "Incomplete relocation");
idx |= (uint16_t)parseByte(where, lineNo, token, numberType);
// Loudly fail on unknown flags
if (flags & (1 << RELOC_ZPAGE | 1 << RELOC_NPAGE))
fatal(where, lineNo, "Paging flags are not supported");
if (flags & ~RELOC_ALL_FLAGS)
warning(where, lineNo, "Unknown reloc flags 0x%x", flags & ~RELOC_ALL_FLAGS);
// Turn this into a Patch
section->patches = realloc(section->patches, sizeof(section->patches[0]) * (section->nbPatches + 1));
if (!section->patches)
fatal(where, lineNo, "Failed to alloc extra patch for \"%s\"", section->name);
struct Patch *patch = &section->patches[section->nbPatches];
patch->lineNo = lineNo;
patch->src = where;
patch->offset = offset - writtenOfs + *writeIndex;
if (section->nbPatches != 0 && section->patches[section->nbPatches - 1].offset >= patch->offset)
fatal(where, lineNo, "Relocs not sorted by offset are not supported (%" PRIu32 " >= %" PRIu32 ")", section->patches[section->nbPatches - 1].offset, patch->offset);
patch->pcSection = section; // No need to fill `pcSectionID`, then
patch->pcOffset = patch->offset - 1; // For `jr`s
patch->type = flags & 1 << RELOC_SIZE ? PATCHTYPE_BYTE : PATCHTYPE_WORD;
uint8_t nbBaseBytes = patch->type == PATCHTYPE_BYTE ? ADDR_SIZE : 2;
uint32_t baseValue = 0;
assert(offset < nbBytes);
if (nbBytes - offset < nbBaseBytes)
fatal(where, lineNo, "Reloc would patch out of bounds (%" PRIu8 " > %zu)", nbBaseBytes, nbBytes - offset);
for (uint8_t i = 0; i < nbBaseBytes; ++i)
baseValue = baseValue | data[offset + i] << (8 * i);
// Extra size that must be reserved for additional operators
#define RPN_EXTRA_SIZE (5 + 1 + 5 + 1 + 5 + 1) // >> 8 & $FF, then + <baseValue>
#define allocPatch(size) do { \
patch->rpnSize = (size); \
patch->rpnExpression = malloc(patch->rpnSize + RPN_EXTRA_SIZE); \
if (!patch->rpnExpression) \
fatal(where, lineNo, "Failed to alloc RPN expression: %s", strerror(errno)); \
} while (0)
// Bit 4 specifies signedness, but I don't think that matters?
// Generate a RPN expression from the info and flags
if (flags & 1 << RELOC_ISSYM) {
if (idx >= nbSymbols)
fatal(where, lineNo, "Reloc refers to symbol #%" PRIu16 " out of %zu", idx, nbSymbols);
struct Symbol const *sym = fileSymbols[idx];
// SDCC has a bunch of "magic symbols" that start with a
// letter and an underscore. These are not compatibility
// hacks, this is how SDLD actually works.
if (sym->name[0] == 'b' && sym->name[1] == '_') {
// Look for the symbol being referenced, and use its index instead
for (idx = 0; idx < nbSymbols; ++idx) {
if (strcmp(&sym->name[1], fileSymbols[idx]->name) == 0)
break;
}
if (idx == nbSymbols)
fatal(where, lineNo, "\"%s\" is missing a reference to \"%s\"", sym->name, &sym->name[1]);
allocPatch(5);
patch->rpnExpression[0] = RPN_BANK_SYM;
patch->rpnExpression[1] = idx;
patch->rpnExpression[2] = idx >> 8;
patch->rpnExpression[3] = idx >> 16;
patch->rpnExpression[4] = idx >> 24;
} else if (sym->name[0] == 'l' && sym->name[1] == '_') {
allocPatch(1 + strlen(&sym->name[2]) + 1);
patch->rpnExpression[0] = RPN_SIZEOF_SECT;
strcpy((char *)&patch->rpnExpression[1], &sym->name[2]);
} else if (sym->name[0] == 's' && sym->name[1] == '_') {
allocPatch(1 + strlen(&sym->name[2]) + 1);
patch->rpnExpression[0] = RPN_STARTOF_SECT;
strcpy((char *)&patch->rpnExpression[1], &sym->name[2]);
} else {
allocPatch(5);
patch->rpnExpression[0] = RPN_SYM;
patch->rpnExpression[1] = idx;
patch->rpnExpression[2] = idx >> 8;
patch->rpnExpression[3] = idx >> 16;
patch->rpnExpression[4] = idx >> 24;
}
} else {
if (idx >= nbSections)
fatal(where, lineNo, "Reloc refers to area #%" PRIu16 " out of %zu", idx, nbSections);
// It gets funky. If the area is absolute, *actually*, we
// must not add its base address, as the assembler will
// already have added it in `baseValue`.
// We counteract this by subtracting the section's base
// address from `baseValue`, undoing what the assembler did;
// this allows the relocation to still be correct, even if
// the section gets moved for any reason.
if (fileSections[idx].section->isAddressFixed)
baseValue -= fileSections[idx].section->org;
char const *name = fileSections[idx].section->name;
struct Section const *other = sect_GetSection(name);
// Unlike with `s_<AREA>`, referencing an area in this way
// wants the beginning of this fragment, so we must add the
// fragment's (putative) offset to account for this.
// The fragment offset prediction is guaranteed since each
// section can only have one fragment per SDLD object file,
// so this fragment will be appended to the existing section
// *if any*, and thus its offset will be the section's
// current size.
if (other)
baseValue += other->size;
allocPatch(1 + strlen(name) + 1);
patch->rpnSize = 1 + strlen(name) + 1;
patch->rpnExpression = malloc(patch->rpnSize + RPN_EXTRA_SIZE);
if (!patch->rpnExpression)
fatal(where, lineNo, "Failed to alloc RPN expression: %s", strerror(errno));
patch->rpnExpression[0] = RPN_STARTOF_SECT;
// The cast is fine, it's just different signedness
strcpy((char *)&patch->rpnExpression[1], name);
}
#undef allocPatch
patch->rpnExpression[patch->rpnSize] = RPN_CONST;
patch->rpnExpression[patch->rpnSize + 1] = baseValue;
patch->rpnExpression[patch->rpnSize + 2] = baseValue >> 8;
patch->rpnExpression[patch->rpnSize + 3] = baseValue >> 16;
patch->rpnExpression[patch->rpnSize + 4] = baseValue >> 24;
patch->rpnExpression[patch->rpnSize + 5] = RPN_ADD;
patch->rpnSize += 5 + 1;
if (patch->type == PATCHTYPE_BYTE) {
// Despite the flag's name, as soon as it is set, 3 bytes
// are present, so we must skip two of them
if (flags & 1 << RELOC_EXPR16) {
if (*writeIndex + (offset - writtenOfs) > section->size)
fatal(where, lineNo, "'T' line writes past \"%s\"'s end (%u > %" PRIu16 ")", section->name, *writeIndex + (offset - writtenOfs), section->size);
// Copy all bytes up to those (plus the byte that we'll overwrite)
memcpy(&section->data[*writeIndex], &data[writtenOfs], offset - writtenOfs + 1);
*writeIndex += offset - writtenOfs + 1;
writtenOfs = offset + 3; // Skip all three `baseValue` bytes, though
}
// Append the necessary operations...
if (flags & 1 << RELOC_ISPCREL) {
// The result must *not* be truncated for those!
patch->type = PATCHTYPE_JR;
// TODO: check the other flags?
} else if (flags & 1 << RELOC_EXPR24 && flags & 1 << RELOC_BANKBYTE) {
patch->rpnExpression[patch->rpnSize] = RPN_CONST;
patch->rpnExpression[patch->rpnSize + 1] = 16;
patch->rpnExpression[patch->rpnSize + 2] = 16 >> 8;
patch->rpnExpression[patch->rpnSize + 3] = 16 >> 16;
patch->rpnExpression[patch->rpnSize + 4] = 16 >> 24;
patch->rpnExpression[patch->rpnSize + 5] = flags & 1 << RELOC_SIGNED ? RPN_SHR : RPN_USHR;
patch->rpnSize += 5 + 1;
} else {
if (flags & 1 << RELOC_EXPR16 && flags & 1 << RELOC_WHICHBYTE) {
patch->rpnExpression[patch->rpnSize] = RPN_CONST;
patch->rpnExpression[patch->rpnSize + 1] = 8;
patch->rpnExpression[patch->rpnSize + 2] = 8 >> 8;
patch->rpnExpression[patch->rpnSize + 3] = 8 >> 16;
patch->rpnExpression[patch->rpnSize + 4] = 8 >> 24;
patch->rpnExpression[patch->rpnSize + 5] = flags & 1 << RELOC_SIGNED ? RPN_SHR : RPN_USHR;
patch->rpnSize += 5 + 1;
}
patch->rpnExpression[patch->rpnSize] = RPN_CONST;
patch->rpnExpression[patch->rpnSize + 1] = 0xFF;
patch->rpnExpression[patch->rpnSize + 2] = 0xFF >> 8;
patch->rpnExpression[patch->rpnSize + 3] = 0xFF >> 16;
patch->rpnExpression[patch->rpnSize + 4] = 0xFF >> 24;
patch->rpnExpression[patch->rpnSize + 5] = RPN_AND;
patch->rpnSize += 5 + 1;
}
} else if (flags & 1 << RELOC_ISPCREL) {
assert(patch->type == PATCHTYPE_WORD);
fatal(where, lineNo, "16-bit PC-relative relocations are not supported");
} else if (flags & (1 << RELOC_EXPR16 | 1 << RELOC_EXPR24)) {
fatal(where, lineNo, "Flags 0x%x are not supported for 16-bit relocs", flags & (1 << RELOC_EXPR16 | 1 << RELOC_EXPR24));
}
++section->nbPatches;
}
// If there is some data left to append, do so
if (writtenOfs != nbBytes) {
assert(nbBytes > writtenOfs);
if (*writeIndex + (nbBytes - writtenOfs) > section->size)
fatal(where, lineNo, "'T' line writes past \"%s\"'s end (%zu > %" PRIu16 ")", section->name, *writeIndex + (nbBytes - writtenOfs), section->size);
memcpy(&section->data[*writeIndex], &data[writtenOfs], nbBytes - writtenOfs);
*writeIndex += nbBytes - writtenOfs;
}
nbBytes = 0; // Do not allow two R lines to refer to the same T line
break;
case 'P':
default:
warning(where, lineNo, "Unknown/unsupported line type '%c', ignoring", lineType);
break;
}
}
if (nbBytes != 0)
warning(where, lineNo, "Last 'T' line had no 'R' line (ignored)");
if (nbSections < expectedNbAreas)
warning(where, lineNo, "Expected %" PRIu32 " 'A' lines, got only %zu", expectedNbAreas, nbSections);
if (nbSymbols < expectedNbSymbols)
warning(where, lineNo, "Expected %" PRIu32 " 'S' lines, got only %zu", expectedNbSymbols, nbSymbols);
nbSectionsToAssign += nbSections;
for (size_t i = 0; i < nbSections; ++i) {
struct Section *section = fileSections[i].section;
// RAM sections can have a size, but don't get any data (they shouldn't have any)
if (fileSections[i].writeIndex != section->size && fileSections[i].writeIndex != 0)
fatal(where, lineNo, "\"%s\" was not fully written (%" PRIu16 " < %" PRIu16 ")", section->name, fileSections[i].writeIndex, section->size);
// This must be done last, so that `->data` is not NULL anymore
sect_AddSection(section);
if (section->modifier == SECTION_FRAGMENT) {
// Add the fragment's offset to all of its symbols
for (uint32_t j = 0; j < section->nbSymbols; ++j)
section->symbols[j]->offset += section->offset;
}
}
#undef expectEol
#undef expectToken
#undef getToken
free(fileSections);
free(data);
fclose(file);
}

View File

@@ -6,6 +6,7 @@
* SPDX-License-Identifier: MIT
*/
#include <assert.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdlib.h>
@@ -16,6 +17,7 @@
#include "error.h"
#include "hashmap.h"
#include "linkdefs.h"
HashMap sections;
@@ -132,7 +134,7 @@ static void mergeSections(struct Section *target, struct Section *other, enum Se
if (target->type != other->type)
errx("Section \"%s\" is defined with conflicting types %s and %s",
other->name, typeNames[target->type], typeNames[other->type]);
other->name, sectionTypeInfo[target->type].name, sectionTypeInfo[other->type].name);
if (other->isBankFixed) {
if (!target->isBankFixed) {
@@ -153,18 +155,33 @@ static void mergeSections(struct Section *target, struct Section *other, enum Se
case SECTION_FRAGMENT:
checkFragmentCompat(target, other);
// Append `other` to `target`
// Note that the order in which fragments are stored in the `nextu` list does not
// really matter, only that offsets are properly computed
other->offset = target->size;
target->size += other->size;
other->offset = target->size - other->size;
if (sect_HasData(target->type)) {
/* Ensure we're not allocating 0 bytes */
target->data = realloc(target->data,
sizeof(*target->data) * target->size + 1);
if (!target->data)
errx("Failed to concatenate \"%s\"'s fragments", target->name);
memcpy(target->data + target->size - other->size, other->data, other->size);
/* Adjust patches' PC offsets */
// Normally we'd check that `sect_HasData`, but SDCC areas may be `_INVALID` here
// Note that if either fragment has data (= a non-NULL `data` pointer), then it's
// assumed that both fragments "have data", and thus should either have a non-NULL
// `data` pointer, or a size of 0.
if (other->data) {
if (target->data) {
// Ensure we're not allocating 0 bytes
target->data = realloc(target->data,
sizeof(*target->data) * target->size + 1);
if (!target->data)
errx("Failed to concatenate \"%s\"'s fragments", target->name);
memcpy(&target->data[other->offset], other->data, other->size);
} else {
assert(target->size == other->size); // It has been increased just above
target->data = other->data;
other->data = NULL; // Prevent a double free()
}
// Adjust patches' PC offsets
for (uint32_t patchID = 0; patchID < other->nbPatches; patchID++)
other->patches[patchID].pcOffset += other->offset;
} else if (target->data) {
assert(other->size == 0);
}
break;
@@ -178,7 +195,7 @@ static void mergeSections(struct Section *target, struct Section *other, enum Se
void sect_AddSection(struct Section *section)
{
/* Check if the section already exists */
// Check if the section already exists
struct Section *other = hash_GetElement(sections, section->name);
if (other) {
@@ -191,9 +208,9 @@ void sect_AddSection(struct Section *section)
mergeSections(other, section, section->modifier);
} else if (section->modifier == SECTION_UNION && sect_HasData(section->type)) {
errx("Section \"%s\" is of type %s, which cannot be unionized",
section->name, typeNames[section->type]);
section->name, sectionTypeInfo[section->type].name);
} else {
/* If not, add it */
// If not, add it
hash_AddElement(sections, section->name, section);
}
}
@@ -208,64 +225,59 @@ void sect_CleanupSections(void)
hash_EmptyMap(sections);
}
static bool sanityChecksFailed;
static void doSanityChecks(struct Section *section, void *ptr)
{
(void)ptr;
#define fail(...) do { \
warnx(__VA_ARGS__); \
sanityChecksFailed = true; \
} while (0)
/* Sanity check the section's type */
// Sanity check the section's type
if (section->type < 0 || section->type >= SECTTYPE_INVALID) {
error(NULL, 0, "Section \"%s\" has an invalid type", section->name);
return;
}
if (section->type < 0 || section->type >= SECTTYPE_INVALID)
fail("Section \"%s\" has an invalid type.", section->name);
if (is32kMode && section->type == SECTTYPE_ROMX) {
if (section->isBankFixed && section->bank != 1)
fail("%s: ROMX sections must be in bank 1 (if any) with option -t",
error(NULL, 0, "%s: ROMX sections must be in bank 1 (if any) with option -t",
section->name);
else
section->type = SECTTYPE_ROM0;
}
if (isWRA0Mode && section->type == SECTTYPE_WRAMX) {
if (section->isBankFixed && section->bank != 1)
fail("%s: WRAMX sections must be in bank 1 with options -w or -d",
error(NULL, 0, "%s: WRAMX sections must be in bank 1 with options -w or -d",
section->name);
else
section->type = SECTTYPE_WRAMX;
}
if (isDmgMode && section->type == SECTTYPE_VRAM && section->bank == 1)
fail("%s: VRAM bank 1 can't be used with option -d",
error(NULL, 0, "%s: VRAM bank 1 can't be used with option -d",
section->name);
/*
* Check if alignment is reasonable, this is important to avoid UB
* An alignment of zero is equivalent to no alignment, basically
*/
// Check if alignment is reasonable, this is important to avoid UB
// An alignment of zero is equivalent to no alignment, basically
if (section->isAlignFixed && section->alignMask == 0)
section->isAlignFixed = false;
/* Too large an alignment may not be satisfiable */
if (section->isAlignFixed && (section->alignMask & startaddr[section->type]))
fail("%s: %s sections cannot be aligned to $%04x bytes",
section->name, typeNames[section->type], section->alignMask + 1);
// Too large an alignment may not be satisfiable
if (section->isAlignFixed && (section->alignMask & sectionTypeInfo[section->type].startAddr))
error(NULL, 0, "%s: %s sections cannot be aligned to $%04x bytes",
section->name, sectionTypeInfo[section->type].name, section->alignMask + 1);
uint32_t minbank = bankranges[section->type][0], maxbank = bankranges[section->type][1];
uint32_t minbank = sectionTypeInfo[section->type].firstBank, maxbank = sectionTypeInfo[section->type].lastBank;
if (section->isBankFixed && section->bank < minbank && section->bank > maxbank)
fail(minbank == maxbank
error(NULL, 0, minbank == maxbank
? "Cannot place section \"%s\" in bank %" PRIu32 ", it must be %" PRIu32
: "Cannot place section \"%s\" in bank %" PRIu32 ", it must be between %" PRIu32 " and %" PRIu32,
section->name, section->bank, minbank, maxbank);
/* Check if section has a chance to be placed */
if (section->size > maxsize[section->type])
fail("Section \"%s\" is bigger than the max size for that type: %#" PRIx16 " > %#" PRIx16,
section->name, section->size, maxsize[section->type]);
// Check if section has a chance to be placed
if (section->size > sectionTypeInfo[section->type].size)
error(NULL, 0, "Section \"%s\" is bigger than the max size for that type: %#" PRIx16 " > %#" PRIx16,
section->name, section->size, sectionTypeInfo[section->type].size);
/* Translate loose constraints to strong ones when they're equivalent */
// Translate loose constraints to strong ones when they're equivalent
if (minbank == maxbank) {
section->bank = minbank;
@@ -273,23 +285,23 @@ static void doSanityChecks(struct Section *section, void *ptr)
}
if (section->isAddressFixed) {
/* It doesn't make sense to have both org and alignment set */
// It doesn't make sense to have both org and alignment set
if (section->isAlignFixed) {
if ((section->org & section->alignMask) != section->alignOfs)
fail("Section \"%s\"'s fixed address doesn't match its alignment",
error(NULL, 0, "Section \"%s\"'s fixed address doesn't match its alignment",
section->name);
section->isAlignFixed = false;
}
/* Ensure the target address is valid */
if (section->org < startaddr[section->type]
// Ensure the target address is valid
if (section->org < sectionTypeInfo[section->type].startAddr
|| section->org > endaddr(section->type))
fail("Section \"%s\"'s fixed address %#" PRIx16 " is outside of range [%#"
error(NULL, 0, "Section \"%s\"'s fixed address %#" PRIx16 " is outside of range [%#"
PRIx16 "; %#" PRIx16 "]", section->name, section->org,
startaddr[section->type], endaddr(section->type));
sectionTypeInfo[section->type].startAddr, endaddr(section->type));
if (section->org + section->size > endaddr(section->type) + 1)
fail("Section \"%s\"'s end address %#x is greater than last address %#x",
error(NULL, 0, "Section \"%s\"'s end address %#x is greater than last address %#x",
section->name, section->org + section->size,
endaddr(section->type) + 1);
}
@@ -300,6 +312,4 @@ static void doSanityChecks(struct Section *section, void *ptr)
void sect_DoSanityChecks(void)
{
sect_ForEach(doSanityChecks, NULL);
if (sanityChecksFailed)
errx("Sanity checks failed");
}

View File

@@ -40,7 +40,7 @@ void sym_ForEach(void (*callback)(struct Symbol *, void *), void *arg)
void sym_AddSymbol(struct Symbol *symbol)
{
/* Check if the symbol already exists */
// Check if the symbol already exists
struct Symbol *other = hash_GetElement(symbols, symbol->name);
if (other) {
@@ -53,7 +53,7 @@ void sym_AddSymbol(struct Symbol *symbol)
exit(1);
}
/* If not, add it */
// If not, add it
hash_AddElement(symbols, symbol->name, symbol);
}

View File

@@ -1,48 +1,72 @@
/*
* This file is part of RGBDS.
*
* Copyright (c) 2022, RGBDS contributors.
*
* SPDX-License-Identifier: MIT
*/
#include "linkdefs.h"
uint16_t startaddr[] = {
[SECTTYPE_ROM0] = 0x0000,
[SECTTYPE_ROMX] = 0x4000,
[SECTTYPE_VRAM] = 0x8000,
[SECTTYPE_SRAM] = 0xA000,
[SECTTYPE_WRAM0] = 0xC000,
[SECTTYPE_WRAMX] = 0xD000,
[SECTTYPE_OAM] = 0xFE00,
[SECTTYPE_HRAM] = 0xFF80
};
uint16_t maxsize[] = {
[SECTTYPE_ROM0] = 0x8000, // patched to 0x4000 if !is32kMode
[SECTTYPE_ROMX] = 0x4000,
[SECTTYPE_VRAM] = 0x2000,
[SECTTYPE_SRAM] = 0x2000,
[SECTTYPE_WRAM0] = 0x2000, // patched to 0x1000 if !isWRA0Mode
[SECTTYPE_WRAMX] = 0x1000,
[SECTTYPE_OAM] = 0x00A0,
[SECTTYPE_HRAM] = 0x007F
};
uint32_t bankranges[][2] = {
[SECTTYPE_ROM0] = {BANK_MIN_ROM0, BANK_MAX_ROM0},
[SECTTYPE_ROMX] = {BANK_MIN_ROMX, BANK_MAX_ROMX},
[SECTTYPE_VRAM] = {BANK_MIN_VRAM, BANK_MAX_VRAM},
[SECTTYPE_SRAM] = {BANK_MIN_SRAM, BANK_MAX_SRAM},
[SECTTYPE_WRAM0] = {BANK_MIN_WRAM0, BANK_MAX_WRAM0},
[SECTTYPE_WRAMX] = {BANK_MIN_WRAMX, BANK_MAX_WRAMX},
[SECTTYPE_OAM] = {BANK_MIN_OAM, BANK_MAX_OAM},
[SECTTYPE_HRAM] = {BANK_MIN_HRAM, BANK_MAX_HRAM}
};
char const * const typeNames[] = {
[SECTTYPE_ROM0] = "ROM0",
[SECTTYPE_ROMX] = "ROMX",
[SECTTYPE_VRAM] = "VRAM",
[SECTTYPE_SRAM] = "SRAM",
[SECTTYPE_WRAM0] = "WRAM0",
[SECTTYPE_WRAMX] = "WRAMX",
[SECTTYPE_OAM] = "OAM",
[SECTTYPE_HRAM] = "HRAM"
// The default values are the most lax, as they are used as-is by RGBASM; only RGBLINK has the full info,
// so RGBASM's job is only to catch unconditional errors earlier.
struct SectionTypeInfo sectionTypeInfo[SECTTYPE_INVALID] = {
[SECTTYPE_ROM0] = {
.name = "ROM0",
.startAddr = 0x0000,
.size = 0x8000, // Patched to 0x4000 if !is32kMode
.firstBank = 0,
.lastBank = 0,
},
[SECTTYPE_ROMX] = {
.name = "ROMX",
.startAddr = 0x4000,
.size = 0x4000,
.firstBank = 1,
.lastBank = 65535,
},
[SECTTYPE_VRAM] = {
.name = "VRAM",
.startAddr = 0x8000,
.size = 0x2000,
.firstBank = 0,
.lastBank = 1, // Patched to 0 if isDmgMode
},
[SECTTYPE_SRAM] = {
.name = "SRAM",
.startAddr = 0xA000,
.size = 0x2000,
.firstBank = 0,
.lastBank = 255,
},
[SECTTYPE_WRAM0] = {
.name = "WRAM0",
.startAddr = 0xC000,
.size = 0x2000, // Patched to 0x1000 if !isWRA0Mode
.firstBank = 0,
.lastBank = 0,
},
[SECTTYPE_WRAMX] = {
.name = "WRAMX",
.startAddr = 0xD000,
.size = 0x1000,
.firstBank = 1,
.lastBank = 7,
},
[SECTTYPE_OAM] = {
.name = "OAM",
.startAddr = 0xFE00,
.size = 0x00A0,
.firstBank = 0,
.lastBank = 0,
},
[SECTTYPE_HRAM] = {
.name = "HRAM",
.startAddr = 0xFF80,
.size = 0x007F,
.firstBank = 0,
.lastBank = 0,
},
};
char const * const sectionModNames[] = {

View File

@@ -6,9 +6,7 @@
* SPDX-License-Identifier: MIT
*/
/*
* Mathematical operators that don't reuse C's behavior
*/
// Mathematical operators that don't reuse C's behavior
#include <stdint.h>

View File

@@ -1,4 +1,4 @@
print_all: MACRO
MACRO print_all
REPT _NARG
PRINT " \1"
SHIFT
@@ -6,7 +6,7 @@ print_all: MACRO
PRINTLN
ENDM
print_some: MACRO
MACRO print_some
PRINT "\1"
SHIFT 5
PRINT "\2\6\9"
@@ -15,12 +15,12 @@ print_some: MACRO
PRINT "\3\9"
ENDM
bad: MACRO
MACRO bad
shift _NARG - 1
PRINTLN \1
ENDM
bad_rept: MACRO
MACRO bad_rept
REPT _NARG - 2
REPT 1
shift

View File

@@ -1,4 +1,4 @@
def_sect: macro
macro def_sect
IF _NARG == 2
SECTION "\1", \2
ELSE

View File

@@ -11,7 +11,7 @@ rept 1
break
; skips invalid code
!@#$%
elif: macro
macro elif
invalid
endr
warn "OK"

View File

@@ -1,3 +1,4 @@
opt Wno-unmapped-char
charmap "<NULL>", $00
charmap "A", $10
charmap "B", $20

View File

@@ -1,7 +1,7 @@
println "start"
; will not define 'mac'
mac: MACRO
MACRO mac
println \1
ENDM println "<_<"
mac "argument"

View File

@@ -1,6 +1,6 @@
def _ASM equ 0
test: MACRO
MACRO test
; Test RGBASM
redef V equs "_ASM +"
static_assert \#
@@ -9,7 +9,7 @@ test: MACRO
assert \#
ENDM
test_mod: MACRO
MACRO test_mod
def x = \1 ; dividend
def y = \2 ; divisor
shift 2
@@ -21,14 +21,14 @@ test_mod: MACRO
test (V (x - y) % y) == (V r)
ENDM
test_each_mod: MACRO
MACRO test_each_mod
test_mod (\1), (\2)
test_mod (\1), -(\2)
test_mod -(\1), (\2)
test_mod -(\1), -(\2)
ENDM
test_pow: MACRO
MACRO test_pow
def x = \1 ; dividend
def y = 2 ** \2 ; divisor
def r = x % y ; remainder
@@ -37,7 +37,7 @@ test_pow: MACRO
test (V r) == (V m)
ENDM
test_each_pow: MACRO
MACRO test_each_pow
test_pow (\1), (\2)
test_pow -(\1), (\2)
ENDM

View File

@@ -1,3 +1,3 @@
DEFINE equs "mac: MACRO\nPRINTLN \"Hello :D\"\nENDM"
DEFINE equs "MACRO mac\nPRINTLN \"Hello :D\"\nENDM"
DEFINE
mac

View File

@@ -65,3 +65,4 @@ while expanding symbol "recurse"
while expanding symbol "recurse"
while expanding symbol "recurse"
while expanding symbol "recurse"
while expanding symbol "recurse"

Some files were not shown because too many files have changed in this diff Show More