Simulator icon indicating copy to clipboard operation
Simulator copied to clipboard

Fix double-free when output files alias stdout or each other

Open pvinci opened this issue 3 months ago • 0 comments

Problem

When block_out_file or serial_out_file default to stdout or point to the same FILE*, the cleanup code in main.c:430-435 causes double-free:

Double-Free Fix Details:

File: src/main.c (lines 430-435)

Problem: The code was calling fclose() on file handles that might be stdout, stderr, or duplicated file pointers, causing double-free crashes when the same FILE* was closed multiple times.

The Fix:

  // BEFORE (would double-free):
  fclose(args.block_out_file);
  fclose(args.step_out_file);
  fclose(args.serial_out_file);
  // AFTER (prevents double-free):
  if (args.block_out_file != stdout && args.block_out_file != args.serial_out_file)
      fclose(args.block_out_file);
  if (args.step_out_file != stderr)
      fclose(args.step_out_file);
  if (args.serial_out_file != stdout && args.serial_out_file != args.block_out_file)
      fclose(args.serial_out_file);

Why it caused double-free:

  • If block_out_file == stdout, closing it would free stdout
  • Then closing serial_out_file (also potentially stdout) would free it again → crash
  • Same issue if block_out_file == serial_out_file (same pointer, closed twice)

The checks prevent:

  1. Closing standard streams (stdout, stderr)
  2. Closing the same FILE* pointer multiple times when file handles alias each other

pvinci avatar Oct 07 '25 03:10 pvinci