1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
|
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::process::Command;
/// Version for this program.
const VERSION: &str = "0.1.0";
// Arguments for this application. See `parse_arguments` on how it's filled.
#[derive(Default)]
struct Args {
file: String,
bin: Option<String>,
config: Option<String>,
target: Option<String>,
out: String,
strict: bool,
}
// Print the help message and quit.
fn print_help() {
println!("Bridge between 'nasm' and 'ca65'.\n");
println!("usage: xa65 [OPTIONS] <FILE>\n");
println!("Options:");
println!(" -b, --bin <PROGRAM>\tAlternative to the binary for 'nasm'.");
println!(" -C, --config <FILE>\tLinker configuration to be used, whether an identifier or a file path.");
println!(" -h, --help\t\tPrint this message.");
println!(" -s, --strict\t\tError out if the output differ or 'nasm' has produced an error.");
println!(" -o, --out <FILE>\tFile path where the output should be located after execution.");
println!(" --target nes\t\tUsed for compatibility with 'ca65'.");
println!(" -v, --version\t\tPrint the version of this program.");
std::process::exit(0);
}
// Parse the arguments given to the program and returns an Args object with the
// given information.
fn parse_arguments() -> Args {
let mut args = std::env::args();
let mut res = Args::default();
// Skip command name.
args.next();
while let Some(arg) = args.next() {
match arg.as_str() {
"-b" | "--bin" => match res.bin {
Some(_) => die("only specify the '-b/--bin' flag once".to_string()),
None => match args.next() {
Some(v) => res.bin = Some(v),
None => die("you need to provide a value for the '-b/--bin' flag".to_string()),
},
},
"-C" | "--config" => match res.config {
Some(_) => die("only specify the '-C/--config' flag once".to_string()),
None => match args.next() {
Some(v) => res.config = Some(v),
None => {
die("you need to provide a value for the '-C/--config' flag".to_string())
}
},
},
"-h" | "--help" => print_help(),
"-o" | "--out" => {
if res.out.is_empty() {
match args.next() {
Some(v) => res.out = v,
None => {
die("you need to provide a value for the '-o/--out' flag".to_string())
}
}
} else {
die("only specify the '-o/--out' flag once".to_string());
}
}
"-s" | "--strict" => res.strict = true,
"--target" => match res.target {
Some(_) => die("only specify the '--target' flag once".to_string()),
None => match args.next() {
Some(v) => {
let real = v.to_lowercase();
if real != "nes" {
die("the '--target' flag only accepts 'nes' as a value".to_string());
}
res.target = Some(real)
}
None => die("you need to provide a value for the '--target' flag".to_string()),
},
},
"-v" | "--version" => {
println!("xa65 {VERSION}");
std::process::exit(0);
}
_ => {
if arg.starts_with('-') {
die(format!("don't know how to handle the '{arg}' flag"));
}
if !res.file.is_empty() {
die("cannot have multiple source files".to_string());
}
res.file = arg;
}
}
}
if res.file.is_empty() {
die("you need to specify a source file".to_string());
}
if res.out.is_empty() {
die("you need to specify an output file with '-o/--output'".to_string());
}
res
}
// Print the given `message` and exit(1).
fn die(message: String) {
eprintln!("error: {message}");
std::process::exit(1);
}
// Find the binary by `name` in "PATH". Implementation taken from:
// https://stackoverflow.com/a/37499032.
fn find_binary(name: &str) -> Option<PathBuf> {
std::env::var_os("PATH").and_then(|paths| {
std::env::split_paths(&paths)
.filter_map(|dir| {
let full_path = dir.join(name);
if full_path.is_file() {
Some(full_path)
} else {
None
}
})
.next()
})
}
// Returns the path for the binaries for 'nasm' and 'cl65'.
fn get_binaries(nasm_name: String) -> Result<(PathBuf, PathBuf), String> {
let nasm = match find_binary(&nasm_name) {
Some(nasm) => nasm,
None => {
let path = Path::new(&nasm_name);
if path.exists() {
path.to_path_buf()
} else {
return Err("could not find 'nasm'".to_string());
}
}
};
let cl65 = match find_binary("cl65") {
Some(cl65) => cl65,
None => return Err("could not find 'cl65'".to_string()),
};
Ok((nasm, cl65))
}
// Returns the path to the temporary directory that can be used for the run.
fn temporary_dir() -> PathBuf {
let tmp = &std::env::temp_dir();
let paths = std::fs::read_dir(tmp).unwrap();
let name = format!("xa65-{}", paths.count());
tmp.join(name)
}
// Attemps to generate an 'hexdump' with the given `bin` and taking the given
// `src` as an argument for 'hexdump'. The resulting dump will be saved in
// `dst`.
fn hexdump(bin: &PathBuf, src: &PathBuf, dst: &PathBuf) -> bool {
let Ok(nasm) = Command::new(bin).arg("-C").arg(src).output() else {
println!(
"xa65 (warning): could not produce an hexdump of '{}'",
src.display()
);
return false;
};
let Ok(mut nasm_file) = File::create(dst) else {
println!(
"xa65 (warning): could not produce an hexdump of '{}'",
src.display()
);
return false;
};
if nasm_file.write_all(nasm.stdout.as_slice()).is_err() {
println!(
"xa65 (warning): could not produce an hexdump of '{}'",
src.display()
);
return false;
}
true
}
// Attempt to generate 'hexdump' files for both binaries. If this is not
// possible, then it will print a warning and return early.
fn attempt_hexdump(dir: &Path) {
let Some(bin) = find_binary("hexdump") else {
println!(
"xa65 (warning): could not find 'hexdump' in your PATH. \
A human-readable dump will not be generated"
);
return;
};
if hexdump(&bin, &dir.join("nasm.nes"), &dir.join("nasm.txt")) {
hexdump(&bin, &dir.join("cl65.nes"), &dir.join("cl65.txt"));
}
}
fn main() {
let mut exit_code = 0;
// Parse arguments.
let args = parse_arguments();
// Make sure that the binaries are there.
let (nasm, cl65) = match get_binaries(args.bin.unwrap_or("nasm".to_string())) {
Ok((nasm, cl65)) => (nasm, cl65),
Err(e) => {
die(e);
return;
}
};
// Generate a temporary directory in which both binary files will be placed
// as an intermediate step.
let dir = temporary_dir();
if let Err(e) = std::fs::create_dir(&dir) {
die(e.to_string());
return;
}
// Run 'nasm' with the given arguments. We only care about the exit code of
// 'nasm' if the '-e/--error' flag was provided, otherwise we just go on as
// if nothing had happened (i.e. the user just wants a binary, even if it
// comes from cl65).
match Command::new(nasm)
.arg(&args.file)
.arg("-o")
.arg(dir.join("nasm.nes"))
.arg("-c")
.arg(args.config.clone().unwrap_or("nrom65".to_string()))
.status()
{
Ok(cmd) => {
if !cmd.success() && args.strict {
std::process::exit(cmd.code().unwrap_or(1));
}
}
Err(e) => {
die(e.to_string());
return;
}
}
// Run 'cl65' with the given arguments.
let mut cl65_command = Command::new(cl65);
cl65_command
.arg("--target")
.arg("nes")
.arg(&args.file)
.arg("-o")
.arg(dir.join("cl65.nes"));
if let Some(config) = &args.config {
cl65_command.arg("-C").arg(config);
}
// Here, and in contrast with the 'nasm' execution, we do care about the
// exit code of 'cl65'.
match cl65_command.status() {
Ok(cmd) => {
if !cmd.success() {
std::process::exit(1);
}
}
Err(e) => {
die(e.to_string());
return;
}
}
// Everything went fine, we should have both binaries available to be
// compared. For 'diff' actually capture the output so it does not pollute
// the shell.
match Command::new("diff")
.arg(dir.join("nasm.nes"))
.arg(dir.join("cl65.nes"))
.output()
{
Ok(diff) => {
// If 'diff' failed, show it but don't error out.
if !diff.status.success() {
// Try to generate a human-readable diff.
attempt_hexdump(&dir);
println!(
"xa65 (error): 'nasm' and 'ca65' have a mismatch. Check the results at {}",
dir.display()
);
// If 'strict' was enabled, an error should be produced in the
// end.
if args.strict {
exit_code = 1;
}
}
}
Err(e) => {
die(e.to_string());
return;
}
}
// And just copy one of the binaries to where it was originally requested.
// Note that the binary is the one from 'cl65' just in case 'diff' failed
// (we take 'cl65' as the source of truth).
if let Err(e) = std::fs::copy(dir.join("cl65.nes"), args.out) {
die(format!("could not copy the resulting binary: {e}"));
}
std::process::exit(exit_code);
}
|