cmetal 0.5.0

A self-contained learning environment for advanced C, inspired by rustlings
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
use crate::compiler::Compiler;
use crate::info_file::ExerciseInfo;
use anyhow::Result;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

/// Kill a compiled exercise after this long. Learner code loops
/// forever all the time; watch mode must survive it. Kept in sync
/// with RUN_TIMEOUT in scripts/check_exercises.py (a unit test in
/// compiler.rs enforces the match).
pub(crate) const RUN_TIMEOUT: Duration = Duration::from_secs(10);

/// Cap on captured output, per stream. A program that prints in a
/// loop until the timeout kills it would otherwise hand us hundreds
/// of megabytes. The reader keeps DRAINING past the cap — stopping
/// would re-introduce the pipe-full deadlock — and discards the
/// excess.
const MAX_CAPTURED_OUTPUT: usize = 1_048_576;

/// An exercise file that includes one of these headers holds tests
/// of its own, written by the learner or left over from the layout
/// that kept the tests inside the exercise. Kept in sync with
/// OWN_TEST_MARKERS in scripts/check_exercises.py (a unit test in
/// compiler.rs enforces the match).
pub(crate) const OWN_TEST_MARKERS: [&str; 2] = ["cmetal_test.h", "clings_test.h"];

/// Whether a C file includes one of the test headers. Only an
/// `#include` line counts: the name of the header in a comment or in
/// a string does not make a file a test file.
pub(crate) fn holds_tests(path: &Path) -> bool {
    let Ok(bytes) = std::fs::read(path) else {
        return false;
    };
    String::from_utf8_lossy(&bytes).lines().any(|line| {
        line.trim_start()
            .strip_prefix('#')
            .is_some_and(|rest| rest.trim_start().starts_with("include"))
            && OWN_TEST_MARKERS.iter().any(|marker| line.contains(marker))
    })
}

/// Where `cmetal update` records that a working copy was written
/// against an earlier curriculum and still carries the tests of that
/// version (see [`Exercise::test_plan`]).
pub(crate) fn legacy_marker(base_dir: &Path, name: &str) -> PathBuf {
    base_dir.join(".cmetal").join("legacy").join(name)
}

/// Which tests decide whether an exercise passes.
struct TestPlan {
    /// The tests inside the exercise file.
    own: bool,
    /// The tests that cmetal ships next to the pristine exercise.
    shipped: bool,
}

pub struct Exercise {
    pub info: ExerciseInfo,
    pub path: PathBuf,
    /// The tests that cmetal ships for this exercise. They sit next to
    /// the pristine exercise, outside the learner's working copies.
    pub test_path: PathBuf,
    /// The pristine exercise that the working copy was made from.
    pub pristine_path: PathBuf,
    /// Present when `cmetal update` kept this working copy from a
    /// curriculum that had the tests inside the exercise file.
    pub legacy_marker: PathBuf,
    pub solution_path: PathBuf,
    /// Where the decoded solution is revealed once the exercise is solved.
    pub reveal_path: PathBuf,
    /// Whether this exercise supports the compiler selected for this run.
    pub supported: bool,
}

#[derive(Debug)]
pub struct VerifyResult {
    pub success: bool,
    pub stage: &'static str,
    pub output: String,
}

impl Exercise {
    pub fn new(
        info: ExerciseInfo,
        exercises_dir: &Path,
        solutions_dir: &Path,
        compiler: &str,
    ) -> Self {
        let rel = info.rel_path();
        let path = exercises_dir.join(&rel);
        let solution_path = solutions_dir.join(&rel);
        let base_dir = solutions_dir.parent().unwrap_or(solutions_dir);
        let reveal_path = base_dir.join("my_solutions").join(&rel);
        let test_path = base_dir.join("exercises").join(info.test_rel_path());
        let pristine_path = base_dir.join("exercises").join(&rel);
        let legacy_marker = legacy_marker(base_dir, &info.name);
        let supported = info.supports_compiler(compiler);
        Self {
            info,
            path,
            test_path,
            pristine_path,
            legacy_marker,
            solution_path,
            reveal_path,
            supported,
        }
    }

    /// Human-readable list of compilers this exercise requires,
    /// e.g. "gcc" or "gcc, clang". Empty when unrestricted.
    pub fn required_compilers(&self) -> String {
        self.info
            .compilers
            .as_deref()
            .unwrap_or_default()
            .join(", ")
    }

    /// Decode the official solution and write it to `my_solutions/`.
    /// Prefers the obfuscated `.c.enc` file; falls back to a plaintext
    /// `.c` (the unpacked form contributors work with).
    pub fn reveal_solution(&self) -> Result<PathBuf> {
        let enc_path = self.solution_path.with_extension("c.enc");
        let content = if enc_path.exists() {
            crate::solutions::decode(&std::fs::read_to_string(&enc_path)?)?
        } else if self.solution_path.exists() {
            std::fs::read_to_string(&self.solution_path)?
        } else {
            anyhow::bail!("No solution available for {}", self.name());
        };
        if let Some(parent) = self.reveal_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&self.reveal_path, content)?;
        Ok(self.reveal_path.clone())
    }

    pub fn name(&self) -> &str {
        &self.info.name
    }

    pub fn hints(&self) -> Vec<&str> {
        self.info.get_hints()
    }

    pub fn exists(&self) -> bool {
        self.path.exists()
    }

    /// Decides which tests the exercise must pass, or says why it
    /// has none. Three situations are kept apart:
    ///
    /// - The curriculum ships a test file. The shipped tests are
    ///   required, and the tests that the learner wrote inside the
    ///   exercise file run in addition. The one exception is a working
    ///   copy that `cmetal update` kept from a curriculum with the
    ///   tests inside the exercise file: it is checked with the tests
    ///   it carries, because the shipped tests belong to a later
    ///   version of the exercise.
    /// - The curriculum is from that earlier layout: its pristine
    ///   exercise holds the tests and there is no test file. The tests
    ///   inside the working copy are the tests.
    /// - The test file is missing from a curriculum that should have
    ///   it. That is a broken installation, and tests written by the
    ///   learner do not stand in for the shipped ones.
    fn test_plan(&self) -> std::result::Result<TestPlan, String> {
        let own = holds_tests(&self.path);
        if self.test_path.exists() {
            let legacy_copy = own && self.legacy_marker.exists();
            return Ok(TestPlan {
                own,
                shipped: !legacy_copy,
            });
        }
        if holds_tests(&self.pristine_path) {
            if own {
                return Ok(TestPlan {
                    own: true,
                    shipped: false,
                });
            }
            return Err(format!(
                "This workspace holds the curriculum of an earlier version of \
                 cmetal, which kept the tests inside the exercise file, and \
                 {} has no tests.\n\
                 Run `cmetal update` to get the current curriculum, or \
                 `cmetal reset {}` to get the exercise with its tests back.",
                self.path.display(),
                self.name()
            ));
        }
        let repair = if self.legacy_marker.parent().is_some_and(|legacy| {
            legacy
                .parent()
                .is_some_and(|meta| meta.join("manifest.json").exists())
        }) {
            "Create a complete workspace with `cmetal init <new directory>` \
             and copy my_exercises/ and .cmetal-state.txt into it."
        } else {
            "In a git checkout, `git restore exercises` brings the file back."
        };
        Err(format!(
            "The tests of this exercise are missing: {}\n\
             The curriculum files are incomplete. {repair}",
            self.test_path.display()
        ))
    }

    /// Added to a failure of the shipped tests when the exercise file
    /// holds tests of its own: the file may come from an earlier
    /// version of the exercise, and the learner decides what to do.
    fn earlier_version_note(&self) -> String {
        format!(
            "\nNote: {} holds tests of its own. If you started it with an \
             earlier version of cmetal, the exercise has changed since then: \
             `cmetal diff {name}` shows the differences, and \
             `cmetal reset {name}` takes the new exercise (it discards your \
             edits).",
            self.path.display(),
            name = self.name()
        )
    }

    pub fn verify(&self, compiler: &Compiler, build_dir: &Path) -> Result<VerifyResult> {
        std::fs::create_dir_all(build_dir)?;

        let bin_path = build_dir.join(&self.info.name);

        // Step 1: Compile
        let result = compiler.compile(&self.path, &bin_path, &self.info.flags)?;
        if !result.success {
            return Ok(VerifyResult {
                success: false,
                stage: "compilation",
                output: result.output,
            });
        }

        // Step 2: Run the binary
        let run_result = run_binary(&bin_path)?;
        if !run_result.success {
            return Ok(VerifyResult {
                success: false,
                stage: "execution",
                output: run_result.output,
            });
        }
        let run_output = run_result.output.clone();

        // Step 3: Tests (if enabled). Two sets can exist: the tests
        // inside the exercise file, and the tests that cmetal ships
        // next to the pristine exercise. test_plan() says which of
        // them this exercise must pass.
        let mut shipped_tests = false;
        if self.info.test {
            let plan = match self.test_plan() {
                Ok(plan) => plan,
                Err(message) => {
                    return Ok(VerifyResult {
                        success: false,
                        stage: "test compilation",
                        output: message,
                    });
                }
            };
            shipped_tests = plan.shipped;
            let note = if plan.own {
                self.earlier_version_note()
            } else {
                String::new()
            };

            if plan.own {
                let own_bin = build_dir.join(format!("{}_own_test", self.info.name));
                let result = compiler.compile_with_tests(&self.path, &own_bin, &self.info.flags)?;
                if !result.success {
                    return Ok(VerifyResult {
                        success: false,
                        stage: "own test compilation",
                        output: result.output,
                    });
                }

                let own_result = run_binary(&own_bin)?;
                if !own_result.success {
                    return Ok(VerifyResult {
                        success: false,
                        stage: "own tests",
                        output: own_result.output,
                    });
                }
            }

            if shipped_tests {
                let test_bin = build_dir.join(format!("{}_test", self.info.name));
                let result = compiler.compile_shipped_tests(
                    &self.test_path,
                    &self.path,
                    &test_bin,
                    &self.info.flags,
                )?;
                if !result.success {
                    return Ok(VerifyResult {
                        success: false,
                        stage: "test compilation",
                        output: result.output + &note,
                    });
                }

                let test_result = run_binary(&test_bin)?;
                if !test_result.success {
                    return Ok(VerifyResult {
                        success: false,
                        stage: "tests",
                        output: test_result.output + &note,
                    });
                }
            }
        }

        // Step 4: Compile and run with sanitizers (if enabled)
        if self.info.sanitizers {
            let san_bin = build_dir.join(format!("{}_san", self.info.name));
            let result =
                compiler.compile_with_sanitizers(&self.path, &san_bin, &self.info.flags)?;
            if !result.success {
                return Ok(VerifyResult {
                    success: false,
                    stage: "sanitizer compilation",
                    output: result.output,
                });
            }

            let san_result = run_binary(&san_bin)?;
            if !san_result.success {
                return Ok(VerifyResult {
                    success: false,
                    stage: "sanitizer check",
                    output: san_result.output,
                });
            }

            // The shipped tests run under the sanitizers too: main
            // rarely reaches every path, and an error path that leaks
            // or reads out of bounds shows only in the tests.
            if shipped_tests {
                let san_test_bin = build_dir.join(format!("{}_san_test", self.info.name));
                let result = compiler.compile_shipped_tests_with_sanitizers(
                    &self.test_path,
                    &self.path,
                    &san_test_bin,
                    &self.info.flags,
                )?;
                if !result.success {
                    return Ok(VerifyResult {
                        success: false,
                        stage: "sanitizer compilation",
                        output: result.output,
                    });
                }

                let san_test_result = run_binary(&san_test_bin)?;
                if !san_test_result.success {
                    return Ok(VerifyResult {
                        success: false,
                        stage: "sanitizer check",
                        output: san_test_result.output,
                    });
                }
            }
        }

        Ok(VerifyResult {
            success: true,
            stage: "complete",
            output: run_output,
        })
    }
}

struct RunResult {
    success: bool,
    output: String,
}

fn run_binary(path: &Path) -> Result<RunResult> {
    run_binary_with_timeout(path, RUN_TIMEOUT)
}

fn run_binary_with_timeout(path: &Path, timeout: Duration) -> Result<RunResult> {
    let mut child = Command::new(path)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;

    // Drain the pipes on their own threads: a child that fills a pipe
    // while we only poll try_wait() would block forever on write.
    let stdout_reader = spawn_pipe_reader(child.stdout.take());
    let stderr_reader = spawn_pipe_reader(child.stderr.take());

    let deadline = Instant::now() + timeout;
    let (status, timed_out) = loop {
        if let Some(status) = child.try_wait()? {
            break (Some(status), false);
        }
        if Instant::now() >= deadline {
            let _ = child.kill();
            let _ = child.wait();
            break (None, true);
        }
        std::thread::sleep(Duration::from_millis(20));
    };

    let stdout = stdout_reader.join().unwrap_or_default();
    let stderr = stderr_reader.join().unwrap_or_default();

    let mut combined = String::new();
    if !stdout.bytes.is_empty() {
        combined.push_str(&String::from_utf8_lossy(&stdout.bytes));
    }
    if !stderr.bytes.is_empty() {
        if !combined.is_empty() {
            combined.push('\n');
        }
        combined.push_str(&String::from_utf8_lossy(&stderr.bytes));
    }
    if stdout.truncated || stderr.truncated {
        if !combined.is_empty() {
            combined.push('\n');
        }
        combined.push_str("[output truncated at 1 MiB per stream]");
    }

    if timed_out {
        if !combined.is_empty() {
            combined.push('\n');
        }
        combined.push_str(&format!(
            "Timed out after {} seconds and was killed. \
             Is there an infinite loop?",
            timeout.as_secs()
        ));
        return Ok(RunResult {
            success: false,
            output: combined,
        });
    }

    // A program that dies from a signal often prints nothing. Name
    // the signal, so that the learner sees a crash and not an empty
    // failure.
    if let Some(signal) = status.and_then(terminating_signal) {
        if !combined.is_empty() && !combined.ends_with('\n') {
            combined.push('\n');
        }
        combined.push_str(&describe_signal(signal));
    }

    Ok(RunResult {
        success: status.map(|s| s.success()).unwrap_or(false),
        output: combined,
    })
}

#[cfg(unix)]
fn terminating_signal(status: std::process::ExitStatus) -> Option<i32> {
    std::os::unix::process::ExitStatusExt::signal(&status)
}

#[cfg(not(unix))]
fn terminating_signal(_status: std::process::ExitStatus) -> Option<i32> {
    None
}

/// The sentence that reports a fatal signal. The numbers of these
/// signals are the same on Linux and on macOS; SIGBUS is 7 on one
/// and 10 on the other, so it is reported by number only.
fn describe_signal(signal: i32) -> String {
    let name = match signal {
        4 => " (SIGILL, illegal instruction)",
        6 => " (SIGABRT, the program called abort)",
        8 => " (SIGFPE, arithmetic error such as a division by zero)",
        11 => " (SIGSEGV, invalid memory access)",
        _ => "",
    };
    format!("The program crashed: it was killed by signal {signal}{name}.")
}

#[derive(Default)]
struct CapturedOutput {
    bytes: Vec<u8>,
    truncated: bool,
}

fn spawn_pipe_reader<R: Read + Send + 'static>(
    pipe: Option<R>,
) -> std::thread::JoinHandle<CapturedOutput> {
    std::thread::spawn(move || {
        let mut captured = CapturedOutput::default();
        let Some(mut pipe) = pipe else {
            return captured;
        };
        let mut chunk = [0u8; 8192];
        loop {
            match pipe.read(&mut chunk) {
                Ok(0) | Err(_) => break,
                Ok(n) => {
                    let remaining = MAX_CAPTURED_OUTPUT.saturating_sub(captured.bytes.len());
                    let keep = remaining.min(n);
                    captured.bytes.extend_from_slice(&chunk[..keep]);
                    if keep < n {
                        captured.truncated = true;
                        // keep looping: the pipe must stay drained
                    }
                }
            }
        }
        captured
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The project supports gcc OR clang: honor $CC, then try both.
    /// Returns None (tests skip) when no C compiler is available.
    fn find_cc() -> Option<String> {
        let candidates = match std::env::var("CC") {
            Ok(cc) if !cc.is_empty() => vec![cc],
            _ => vec!["gcc".to_string(), "clang".to_string()],
        };
        candidates.into_iter().find(|cc| {
            Command::new(cc)
                .arg("--version")
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status()
                .map(|s| s.success())
                .unwrap_or(false)
        })
    }

    /// Compile a C snippet into `dir`; the caller keeps the TempDir
    /// alive for as long as the binary is needed.
    fn compile_snippet(cc: &str, dir: &Path, name: &str, code: &str) -> PathBuf {
        let src = dir.join(format!("{name}.c"));
        let bin = dir.join(name);
        std::fs::write(&src, code).unwrap();
        let status = Command::new(cc)
            .arg(&src)
            .arg("-o")
            .arg(&bin)
            .status()
            .unwrap();
        assert!(status.success());
        bin
    }

    macro_rules! require_cc {
        () => {
            match find_cc() {
                Some(cc) => cc,
                None => {
                    eprintln!("skipping: no C compiler available");
                    return;
                }
            }
        };
    }

    #[test]
    fn infinite_loop_is_killed_and_reported() {
        let cc = require_cc!();
        let tmp = tempfile::TempDir::new().unwrap();
        let bin = compile_snippet(
            &cc,
            tmp.path(),
            "spin",
            "int main(void) { volatile int x = 1; while (x) {} }",
        );
        let start = Instant::now();
        let result = run_binary_with_timeout(&bin, Duration::from_secs(1)).unwrap();
        assert!(!result.success);
        assert!(result.output.contains("Timed out"));
        // killed near the deadline, not at some multiple of it
        assert!(start.elapsed() < Duration::from_secs(5));
    }

    #[test]
    fn normal_exit_and_output_are_captured() {
        let cc = require_cc!();
        let tmp = tempfile::TempDir::new().unwrap();
        let bin = compile_snippet(
            &cc,
            tmp.path(),
            "hello",
            "#include <stdio.h>\nint main(void) { puts(\"hi\"); return 0; }",
        );
        let result = run_binary(&bin).unwrap();
        assert!(result.success);
        assert!(result.output.contains("hi"));
    }

    #[test]
    fn large_output_does_not_deadlock() {
        // More than any pipe buffer: without dedicated reader threads
        // the child blocks on write and the timeout kills a healthy
        // program. 680 KB stays under the capture cap: no truncation.
        let cc = require_cc!();
        let tmp = tempfile::TempDir::new().unwrap();
        let bin = compile_snippet(
            &cc,
            tmp.path(),
            "chatty",
            "#include <stdio.h>\nint main(void) {\n\
             for (int i = 0; i < 40000; i++) printf(\"0123456789abcdef\\n\");\n\
             return 0; }",
        );
        let result = run_binary(&bin).unwrap();
        assert!(result.success);
        assert!(result.output.len() > 500_000);
        assert!(!result.output.contains("output truncated"));
    }

    #[test]
    fn output_flood_is_bounded_and_drained() {
        // The worst case both fixes must survive together: a program
        // that prints forever. The reader must keep draining (or the
        // child deadlocks on a full pipe long before the timeout) but
        // keep only MAX_CAPTURED_OUTPUT per stream.
        let cc = require_cc!();
        let tmp = tempfile::TempDir::new().unwrap();
        let bin = compile_snippet(
            &cc,
            tmp.path(),
            "flood",
            "#include <stdio.h>\nint main(void) {\n\
             while (1) puts(\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\");\n\
             }",
        );
        let result = run_binary_with_timeout(&bin, Duration::from_secs(1)).unwrap();
        assert!(!result.success);
        assert!(result.output.contains("Timed out"));
        assert!(result.output.contains("output truncated"));
        // both streams capped, plus the two notes: nowhere near the
        // hundreds of MB the child produced
        assert!(result.output.len() <= 2 * MAX_CAPTURED_OUTPUT + 1024);
    }
}