Skip to content

libsimlin: sync_state TOCTOU race in simlin_project_add_model #303

Closed

Description

@bpowers

Problem

In src/libsimlin/src/project.rs, the simlin_project_add_model function has the same class of sync_state TOCTOU race as #297 (which covers apply_project_patch_internal in patch.rs).

At lines 362-369:

let prev_state = proj.sync_state.lock().unwrap().take();  // line 362: sets sync_state to None
let new_state = engine::db::sync_from_datamodel_incremental(  // lines 363-367: rebuild DB
    &mut db,
    &project_locked.datamodel,
    prev_state.as_ref(),
);
drop(db);                                                    // line 368: release DB lock
*proj.sync_state.lock().unwrap() = Some(new_state);          // line 369: restore sync_state

Between drop(db) on line 368 and restoring sync_state on line 369, another thread calling simlin_sim_new can acquire the DB lock, observe sync_state as None, and receive a NotSimulatable error because sync_from_datamodel_incremental is called with prev_state = None, triggering a full resync from scratch rather than using the incremental path.

Why It Matters

This is a correctness issue for multi-threaded callers (Python bindings, concurrent FFI calls). The API is documented as thread-safe, so concurrent add_model + sim_new calls should not produce spurious errors. The impact is a transient NotSimulatable failure that is non-deterministic and difficult to reproduce, making it a particularly confusing bug for users.

Components Affected

  • src/libsimlin/src/project.rs - simlin_project_add_model function (lines 362-369)

Possible Solutions

The fix should restructure the lock protocol so sync_state is never in a None state visible to concurrent readers. Two straightforward approaches:

  1. Hold the DB lock until after sync_state is restored: Move drop(db) after the sync_state assignment on line 369, so no concurrent reader can observe the intermediate state.

  2. Clone instead of take: Replace .take() with .clone() (as suggested for libsimlin: sync_state TOCTOU race in apply_project_patch_internal #297), so sync_state always holds a valid value and concurrent readers see the previous consistent state.

This does NOT warrant restoring the monolithic compilation fallback -- the incremental-only path is correct; the issue is purely about lock ordering.

Context

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions