• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nasa / trick / 44797905565

20 Nov 2026 06:59PM UTC coverage: 57.215% (+0.2%) from 57.009%
44797905565

push

github

web-flow
feat: Add TMM/MM calls for determining whether any errors while writing a checkpoint (#2278)

108 of 168 new or added lines in 8 files covered. (64.29%)

15 existing lines in 5 files now uncovered.

15134 of 26451 relevant lines covered (57.22%)

470620.48 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.22
/trick_source/sim_services/MemoryManager/MemoryManager_write_checkpoint.cpp
1
#include "trick/MemoryManager.hh"
2

3
#include <algorithm> // std::sort()
4
#include <errno.h>
5
#include <fstream>
6
#include <sstream>
7
#include <stdio.h>  // fflush()
8
#include <stdlib.h> // free()
9
#include <string.h>
10
#include <sys/mman.h>
11
#include <sys/types.h>
12
#include <sys/wait.h>
13
#include <unistd.h>
14

15
#ifndef MAP_ANONYMOUS
16
#define MAP_ANONYMOUS MAP_ANON
17
#endif
18

19
// Values of the result a forked checkpoint writer reports through shared memory.
20
enum
21
{
22
    FORKED_WRITE_NOT_REPORTED = 0, // Reset by the parent before fork; still set if the writer ended before reporting.
23
    FORKED_WRITE_SUCCESS      = 1, // The forked checkpoint writer completed the write without errors.
24
    FORKED_WRITE_FAILED       = 2 // The forked checkpoint writer reported errors (written with errors, or not written).
25
};
26

27
// Number of write_checkpoint() calls currently in progress on this thread (more than 1 when a
28
// file-name version calls a stream version). Errors reported while it is above 0 count as
29
// checkpoint write errors.
30
static thread_local int checkpoint_write_depth = 0;
31

32
// Marks the current thread as writing a checkpoint for the lifetime of the object.
33
struct CheckpointWriteScope
34
{
35
        CheckpointWriteScope() { ++checkpoint_write_depth; }
288 ✔
36
        ~CheckpointWriteScope() { --checkpoint_write_depth; }
288 ✔
37
        // A copy wouldn't increment the depth but would still decrement it.
38
        CheckpointWriteScope(const CheckpointWriteScope&)            = delete;
39
        CheckpointWriteScope& operator=(const CheckpointWriteScope&) = delete;
40
};
41

42
// GreenHills stuff
43
#if ( __ghs )
44
#include "ghs_stubs.h"
45
#endif
46

47
// MEMBER FUNCTION
48
void Trick::MemoryManager::execute_checkpoint( std::ostream& out_s ) {
266 ✔
49

50
    ALLOC_INFO_MAP::iterator pos;
266 ✔
51
    ALLOC_INFO* alloc_info;
52
    char name[256];
53
    int local_anon_var_number;
54
    int extern_anon_var_number;
55

56
    // 1) Generate declaration statements for each the allocations that we are managing.
57
    out_s << "// Variable Declarations." << std::endl;
266 ✔
58
    out_s.flush();
266 ✔
59

60
    local_anon_var_number = 0;
266 ✔
61
    extern_anon_var_number = 0;
266 ✔
62

63
    // Give names to the anonymous declarations
64
    // Also search each allocation for STLs.
65
    // STLs will be added to the dependencies vector.
66
    int n_depends = dependencies.size();
266 ✔
67
    for (int ii = 0 ; ii < n_depends ; ii ++) {
1,339 ✔
68
        alloc_info = dependencies[ii];
1,073 ✔
69
        /** Generate temporary names for anonymous variables. */
70
        if (alloc_info->name == NULL) {
1,073 ✔
71
            // Skip naming individual C-string allocations to eliminate unused declarations
72
            // Individual char arrays (size=1, num_index=1) represent single strings that are
73
            // included in char* arrays, so we don't need separate allocations for them
74
            if (alloc_info->type == TRICK_CHARACTER && alloc_info->size == 1 && alloc_info->num_index == 1
309 ✔
75
                && alloc_info->stcl == TRICK_LOCAL)
123 ✔
76
            {
77
                // Skip naming this individual char array allocation to prevent unused declarations
78
                continue;
123 ✔
79
            }
80

81
            if ( alloc_info->stcl == TRICK_LOCAL) {
186 ✔
82
                snprintf( name, sizeof(name), "%s%d", local_anon_var_prefix, local_anon_var_number++);
186 ✔
83
                alloc_info->name = strdup( name);
186 ✔
84
            } else if (alloc_info->stcl == TRICK_EXTERN) {
×
85
                snprintf( name, sizeof(name), "%s%d", extern_anon_var_prefix, extern_anon_var_number++);
×
86
                alloc_info->name = strdup( name);
×
87
                /** @b NOTE: We should not write declarations for external
88
                    anonymous variables, because we should not reload them.*/
89
            } else {
90
                emitError("write_checkpoint: This is bad. ALLOC_INFO object is messed up.\n") ;
×
NEW
91
                checkpoint_write_success = false;
×
92
            }
93
        }
94
        get_stl_dependencies(alloc_info);
950 ✔
95
    }
96

97
    // Write a declaration statement for all of the LOCAL variables,
98
    n_depends = dependencies.size();
266 ✔
99
    for (int ii = 0 ; ii < n_depends ; ii ++) {
3,911 ✔
100
        alloc_info = dependencies[ii];
3,645 ✔
101
        if ( alloc_info->stcl == TRICK_LOCAL) {
3,645 ✔
102
            currentCheckPointAgent->write_decl( out_s, alloc_info);
3,191 ✔
103
        }
104
    }
105

106
    // Write a "clear_all_vars" command.
107
    if (reduced_checkpoint) {
266 ✔
108
        out_s << std::endl << std::endl << "// Clear all allocations to 0." << std::endl;
266 ✔
109
        out_s << "clear_all_vars();" << std::endl;
266 ✔
110
    }
111

112
    // 2) Dump the contents of each of the dynamic and mapped allocations.
113
    out_s << std::endl << std::endl << "// Variable Assignments." << std::endl;
266 ✔
114
    out_s.flush();
266 ✔
115

116
    for (int ii = 0 ; ii < n_depends ; ii ++) {
3,911 ✔
117
        alloc_info = dependencies[ii];
3,645 ✔
118
        // Skip naming individual C-string allocations to eliminate unused declarations.
119
        // Individual char arrays (size=1, num_index=1) represent single strings that are
120
        // included in char* arrays, so we don't need separate allocations for them.
121
        // Also, safety check for NULL name before pushing to name stack later.
122
        if (!(alloc_info->type == TRICK_CHARACTER && alloc_info->size == 1 && alloc_info->num_index == 1
3,645 ✔
123
              && alloc_info->stcl == TRICK_LOCAL)
123 ✔
124
            && alloc_info->name != NULL)
3,522 ✔
125
        {
126
            write_var(out_s, alloc_info);
3,522 ✔
127
            out_s << std::endl;
3,522 ✔
128
        }
129
    }
130

131
    // Free all of the temporary names that were created for the checkpoint.
132

133
    for (int ii = 0 ; ii < n_depends ; ii ++) {
3,911 ✔
134
        alloc_info = dependencies[ii];
3,645 ✔
135
        // If the temporary-variable prefix occurs at the beginning of the name ...
136
        if ((alloc_info->name != NULL) &&
3,645 ✔
137
            (( strstr( alloc_info->name, local_anon_var_prefix ) == alloc_info->name ) ||
3,522 ✔
138
             ( strstr( alloc_info->name, extern_anon_var_prefix) == alloc_info->name ))) {
3,336 ✔
139
                free( alloc_info->name);
186 ✔
140
                alloc_info->name = NULL;
186 ✔
141
        }
142
    }
143

144
    // Delete the variables created by STLs. Remove memory in reverse order.
145
    std::vector<ALLOC_INFO*>::reverse_iterator it ;
266 ✔
146
    for ( it = stl_dependencies.rbegin() ; it != stl_dependencies.rend() ; it++ ) {
2,838 ✔
147
        delete_var((*it)->start) ;
2,572 ✔
148
    }
149

150
    out_s.flush();
266 ✔
151
    if (out_s.fail())
266 ✔
152
    {
NEW
153
        emitError("write_checkpoint: An error occurred while writing to the checkpoint output stream.\n");
×
NEW
154
        checkpoint_write_success = false;
×
155
    }
156
    if (!checkpoint_write_success)
266 ✔
157
    {
158
        emitWarning("write_checkpoint: Checkpoint was written with errors and may not restore correctly."
8 ✔
159
                    " See get_checkpoint_write_state() / TMM_get_checkpoint_write_state().");
160
    }
161
}
266 ✔
162

163
// Reset the checkpoint write error state before starting a new checkpoint.
164
void Trick::MemoryManager::begin_checkpoint_write()
288 ✔
165
{
166
    // Called at the start of every public write_checkpoint(). Collects any earlier forked
167
    // checkpoint so its result can't overwrite this one, then resets the write state to true.
168
    // Calling it more than once for the same write is harmless.
169
    wait_for_checkpoint_write();
288 ✔
170
    checkpoint_write_success = true;
288 ✔
171
}
288 ✔
172

173
// MEMBER FUNCTION
174
bool Trick::MemoryManager::get_checkpoint_write_state()
235 ✔
175
{
176
    // Read the result while still holding the lock, so it can't change between collecting
177
    // a forked writer and returning.
178
    pthread_mutex_lock(&checkpoint_write_mutex);
235 ✔
179
    wait_for_checkpoint_write_locked();
235 ✔
180
    bool state = checkpoint_write_success;
235 ✔
181
    pthread_mutex_unlock(&checkpoint_write_mutex);
235 ✔
182
    return state;
235 ✔
183
}
184

185
// MEMBER FUNCTION
186
int Trick::MemoryManager::fork_checkpoint_writer()
20 ✔
187
{
188
    pthread_mutex_lock(&checkpoint_write_mutex);
20 ✔
189

190
    // Collect any earlier forked checkpoint so only one result is pending.
191
    wait_for_checkpoint_write_locked();
20 ✔
192
    reset_forked_checkpoint_result();
20 ✔
193

194
    // The child's code locks mm_mutex. Holding it across fork() makes sure no other thread
195
    // owns it at that moment, so the child's copy can be unlocked and its maps are consistent.
196
    // Flush buffered output first, otherwise the child inherits a copy and prints it again.
197
    std::cout.flush();
20 ✔
198
    fflush(nullptr);
20 ✔
199
    pthread_mutex_lock(&mm_mutex);
20 ✔
200
    pid_t pid = fork();
20 ✔
201
    pthread_mutex_unlock(&mm_mutex);
20 ✔
202

203
    if (pid > 0)
20 ✔
204
    {
205
        checkpoint_write_pid = (int)pid;
20 ✔
206
    }
207
    pthread_mutex_unlock(&checkpoint_write_mutex);
20 ✔
208
    return (int)pid;
20 ✔
209
}
210

211
// MEMBER FUNCTION
212
void Trick::MemoryManager::reset_forked_checkpoint_result()
20 ✔
213
{
214
    if (checkpoint_write_shared == nullptr)
20 ✔
215
    {
216
        void* shared = mmap(nullptr, sizeof(*checkpoint_write_shared), PROT_READ | PROT_WRITE,
8 ✔
217
                            MAP_SHARED | MAP_ANONYMOUS, -1, 0);
218
        if (shared != MAP_FAILED)
8 ✔
219
        {
220
            checkpoint_write_shared = static_cast<int*>(shared);
8 ✔
221
        }
222
    }
223
    if (checkpoint_write_shared != nullptr)
20 ✔
224
    {
225
        volatile int* shared = checkpoint_write_shared;
20 ✔
226
        *shared              = FORKED_WRITE_NOT_REPORTED;
20 ✔
227
    }
228
}
20 ✔
229

230
// MEMBER FUNCTION
NEW
231
void Trick::MemoryManager::report_forked_checkpoint_write()
×
232
{
233
    // volatile (not atomic) is enough here: the parent only reads the value after the child
234
    // has exited and been reaped, and process termination orders the child's writes.
NEW
235
    if (checkpoint_write_shared != nullptr)
×
236
    {
NEW
237
        volatile int* shared = checkpoint_write_shared;
×
NEW
238
        *shared              = checkpoint_write_success ? FORKED_WRITE_SUCCESS : FORKED_WRITE_FAILED;
×
239
    }
NEW
240
}
×
241

242
// MEMBER FUNCTION
243
void Trick::MemoryManager::wait_for_checkpoint_write()
952 ✔
244
{
245
    // Only one thread at a time can wait for the forked child. The thread holding the lock
246
    // collects the result and sets checkpoint_write_pid to -1. Other threads block on the lock,
247
    // then find pid -1 and use that result without waiting.
248
    pthread_mutex_lock(&checkpoint_write_mutex);
952 ✔
249
    wait_for_checkpoint_write_locked();
952 ✔
250
    pthread_mutex_unlock(&checkpoint_write_mutex);
952 ✔
251
}
952 ✔
252

253
// MEMBER FUNCTION
254
void Trick::MemoryManager::wait_for_checkpoint_write_locked()
1,207 ✔
255
{
256
    if (checkpoint_write_pid <= 0)
1,207 ✔
257
    {
258
        return;
1,187 ✔
259
    }
260

261
    int status = 0;
20 ✔
262
    pid_t ret;
263
    do
264
    {
265
        ret = waitpid(checkpoint_write_pid, &status, 0);
20 ✔
266
    } while (ret == -1 && errno == EINTR);
20 ✔
267
    int saved_errno = errno;
20 ✔
268

269
    if (ret > 0)
20 ✔
270
    {
271
        // If shared memory is available, the child must also have reported its result there;
272
        // this catches a stray exit(0) or exit(1) that didn't come from the checkpoint writer.
273
        bool reported         = true;
15 ✔
274
        bool reported_success = true;
15 ✔
275
        if (checkpoint_write_shared != nullptr)
15 ✔
276
        {
277
            volatile int* shared = checkpoint_write_shared;
15 ✔
278
            int result           = *shared;
15 ✔
279
            reported             = (result != FORKED_WRITE_NOT_REPORTED);
15 ✔
280
            reported_success     = (result == FORKED_WRITE_SUCCESS);
15 ✔
281
        }
282

283
        // Signal: child died abnormally. Exit code > 1 or no reported result: abnormal exit.
284
        // Exit code 1 with a reported result is the child's own reported failure, so no extra warning.
285
        if (WIFSIGNALED(status))
15 ✔
286
        {
287
            emitWarning("write_checkpoint: Forked checkpoint process ended abnormally (signal "
2 ✔
288
                        + std::to_string(WTERMSIG(status)) + "). Checkpoint write state set to false.");
4 ✔
289
        }
290
        else if (WIFEXITED(status) && (WEXITSTATUS(status) > 1 || !reported))
13 ✔
291
        {
292
            emitWarning("write_checkpoint: Forked checkpoint process ended abnormally (exit code "
3 ✔
293
                        + std::to_string(WEXITSTATUS(status)) + (reported ? "" : ", no result reported")
6 ✔
294
                        + "). Checkpoint write state set to false.");
9 ✔
295
        }
296
        // success means the child exited normally with exit code 0 and reported success.
297
        checkpoint_write_success = WIFEXITED(status) && WEXITSTATUS(status) == 0 && reported && reported_success;
15 ✔
298
    }
299
    else if (saved_errno == ECHILD && checkpoint_write_shared != nullptr)
5 ✔
300
    {
301
        // The child was already reaped, e.g. by a SIGCHLD handler (exec_set_trap_sigchld),
302
        // so use the result it reported through shared memory.
303
        // In theory the pid could already have been reused by another child of this process
304
        // before this waitpid() ran; that window is narrow and only exists with the trap on.
305
        volatile int* shared = checkpoint_write_shared;
5 ✔
306
        int result           = *shared;
5 ✔
307
        if (result == FORKED_WRITE_NOT_REPORTED)
5 ✔
308
        {
309
            emitWarning("write_checkpoint: Forked checkpoint process ended abnormally before reporting its result."
2 ✔
310
                        " Checkpoint write state set to false.");
311
        }
312
        checkpoint_write_success = (result == FORKED_WRITE_SUCCESS);
5 ✔
313
    }
5 ✔
314
    else
315
    {
NEW
316
        emitWarning("write_checkpoint: Unable to get the result of the forked checkpoint process ("
×
NEW
317
                    + std::string(strerror(saved_errno)) + "). Checkpoint write state is unknown and set to false.");
×
NEW
318
        checkpoint_write_success = false;
×
319
    }
320
    checkpoint_write_pid = -1;
20 ✔
321
}
322

323
// MEMBER FUNCTION
NEW
324
void Trick::MemoryManager::set_checkpoint_write_state(bool state) { checkpoint_write_success = state; }
×
325

326
// MEMBER FUNCTION
327
void Trick::MemoryManager::report_checkpoint_write_error()
6 ✔
328
{
329
    if (checkpoint_write_depth > 0)
6 ✔
330
    {
331
        checkpoint_write_success = false;
4 ✔
332
    }
333
}
6 ✔
334

335
// Local sort function used in write_checkpoint.
336
static bool alloc_info_id_compare(ALLOC_INFO * lhs, ALLOC_INFO * rhs) { return ( lhs->id < rhs->id ) ; }
4,196 ✔
337

338
// MEMBER FUNCTION
339
void Trick::MemoryManager::write_checkpoint( std::ostream& out_s) {
19 ✔
340
    CheckpointWriteScope write_scope;
19 ✔
341

342
    ALLOC_INFO_MAP::iterator pos;
19 ✔
343
    ALLOC_INFO* alloc_info;
344
    begin_checkpoint_write();
19 ✔
345
    dependencies.clear();
19 ✔
346
    stl_dependencies.clear();
19 ✔
347

348
    pthread_mutex_lock(&mm_mutex);
19 ✔
349
    for ( pos=alloc_info_map.begin() ; pos!=alloc_info_map.end() ; pos++ ) {
814 ✔
350
        alloc_info = pos->second;
795 ✔
351
        dependencies.push_back(alloc_info);
795 ✔
352
    }
353

354
    // Sort the dependencies by ALLOC_INFO.id.
355
    std::sort( dependencies.begin() , dependencies.end() , alloc_info_id_compare) ;
19 ✔
356
    pthread_mutex_unlock(&mm_mutex);
19 ✔
357

358
    execute_checkpoint( out_s );
19 ✔
359

360
}
19 ✔
361

362
// MEMBER FUNCTION
363
void Trick::MemoryManager::write_checkpoint(const char* filename) {
22 ✔
364
    CheckpointWriteScope write_scope;
22 ✔
365
    // Collect any pending forked checkpoint before opening the file, so its result can't
366
    // overwrite an open failure below and a child still writing the same file isn't truncated.
367
    begin_checkpoint_write();
22 ✔
368
    std::ofstream outfile(filename, std::ios::out);
22 ✔
369

370
    if (outfile.is_open()) {
22 ✔
371
        write_checkpoint( outfile);
19 ✔
372
    } else {
373
        std::stringstream message;
3 ✔
374
        message << "Couldn't open \"" << filename << "\".";
3 ✔
375
        emitError(message.str());
3 ✔
376
        checkpoint_write_success = false;
3 ✔
377
    }
3 ✔
378
}
22 ✔
379

380
// MEMBER FUNCTION
381
void Trick::MemoryManager::write_checkpoint( std::ostream& out_s, const char* var_name) {
246 ✔
382
    CheckpointWriteScope write_scope;
246 ✔
383
    begin_checkpoint_write();
246 ✔
384
    dependencies.clear();
246 ✔
385
    stl_dependencies.clear();
246 ✔
386

387
    pthread_mutex_lock(&mm_mutex);
246 ✔
388
    get_alloc_deps_in_allocation( var_name);
246 ✔
389
    pthread_mutex_unlock(&mm_mutex);
246 ✔
390

391
    execute_checkpoint( out_s );
246 ✔
392
}
246 ✔
393

394
// MEMBER FUNCTION
395
void Trick::MemoryManager::write_checkpoint(const char* filename, const char* var_name) {
×
NEW
396
    CheckpointWriteScope write_scope;
×
397
    // Collect any pending forked checkpoint before opening the file, so its result can't
398
    // overwrite an open failure below and a child still writing the same file isn't truncated.
NEW
399
    begin_checkpoint_write();
×
400
    std::ofstream out_s( filename, std::ios::out);
×
401
    if (out_s.is_open()) {
×
402
        write_checkpoint( out_s, var_name);
×
403
    } else {
404
        std::stringstream message;
×
405
        message << "Couldn't open \"" << filename << "\".";
×
406
        emitError(message.str());
×
NEW
407
        checkpoint_write_success = false;
×
408
    }
×
409
}
×
410

411
// MEMBER FUNCTION
412
void Trick::MemoryManager::write_checkpoint( std::ostream& out_s, std::vector<const char*>& var_name_list) {
1 ✔
413
    CheckpointWriteScope write_scope;
1 ✔
414

415
    const char* var_name;
416
    int n_names;
417

418
    begin_checkpoint_write();
1 ✔
419
    dependencies.clear();
1 ✔
420
    stl_dependencies.clear();
1 ✔
421

422
    n_names = var_name_list.size();
1 ✔
423
    for (int ii=0; ii< n_names; ii++) {
3 ✔
424
        var_name = var_name_list[ii];
2 ✔
425
        pthread_mutex_lock(&mm_mutex);
2 ✔
426
        get_alloc_deps_in_allocation(var_name);
2 ✔
427
        pthread_mutex_unlock(&mm_mutex);
2 ✔
428
    }
429

430
    execute_checkpoint( out_s );
1 ✔
431
}
1 ✔
432

433
// MEMBER FUNCTION
434
void Trick::MemoryManager::write_checkpoint(const char* filename, std::vector<const char*>& var_name_list) {
×
NEW
435
    CheckpointWriteScope write_scope;
×
436
    // Collect any pending forked checkpoint before opening the file, so its result can't
437
    // overwrite an open failure below and a child still writing the same file isn't truncated.
NEW
438
    begin_checkpoint_write();
×
UNCOV
439
    std::ofstream out_s( filename, std::ios::out);
×
440

441
    if (out_s.is_open()) {
×
442
        write_checkpoint( out_s, var_name_list);
×
443
    } else {
NEW
444
        std::stringstream message;
×
NEW
445
        message << "Couldn't open \"" << filename << "\".";
×
NEW
446
        emitError(message.str());
×
NEW
447
        checkpoint_write_success = false;
×
448
    }
×
449
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc