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

nasa / trick / 43336118544

13 Nov 2026 12:19AM UTC coverage: 57.196% (+0.2%) from 57.005%
43336118544

Pull #2278

github

web-flow
Merge fa86b4180 into ed6bbea72
Pull Request #2278: feat: Add TMM/MM calls for determining whether any errors while writing a checkpoint

101 of 155 new or added lines in 9 files covered. (65.16%)

15 existing lines in 5 files now uncovered.

15122 of 26439 relevant lines covered (57.2%)

966474.96 hits per line

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

82.41
/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
// GreenHills stuff
28
#if ( __ghs )
29
#include "ghs_stubs.h"
30
#endif
31

32
// MEMBER FUNCTION
33
void Trick::MemoryManager::execute_checkpoint( std::ostream& out_s ) {
132 ✔
34

35
    ALLOC_INFO_MAP::iterator pos;
132 ✔
36
    ALLOC_INFO* alloc_info;
37
    char name[256];
38
    int local_anon_var_number;
39
    int extern_anon_var_number;
40

41
    // 1) Generate declaration statements for each the allocations that we are managing.
42
    out_s << "// Variable Declarations." << std::endl;
132 ✔
43
    out_s.flush();
132 ✔
44

45
    local_anon_var_number = 0;
132 ✔
46
    extern_anon_var_number = 0;
132 ✔
47

48
    // Give names to the anonymous declarations
49
    // Also search each allocation for STLs.
50
    // STLs will be added to the dependencies vector.
51
    int n_depends = dependencies.size();
132 ✔
52
    for (int ii = 0 ; ii < n_depends ; ii ++) {
1,878 ✔
53
        alloc_info = dependencies[ii];
1,746 ✔
54
        /** Generate temporary names for anonymous variables. */
55
        if (alloc_info->name == NULL) {
1,746 ✔
56
            // Skip naming individual C-string allocations to eliminate unused declarations
57
            // Individual char arrays (size=1, num_index=1) represent single strings that are
58
            // included in char* arrays, so we don't need separate allocations for them
59
            if (alloc_info->type == TRICK_CHARACTER && alloc_info->size == 1 && alloc_info->num_index == 1
618 ✔
60
                && alloc_info->stcl == TRICK_LOCAL)
246 ✔
61
            {
62
                // Skip naming this individual char array allocation to prevent unused declarations
63
                continue;
246 ✔
64
            }
65

66
            if ( alloc_info->stcl == TRICK_LOCAL) {
372 ✔
67
                snprintf( name, sizeof(name), "%s%d", local_anon_var_prefix, local_anon_var_number++);
372 ✔
68
                alloc_info->name = strdup( name);
372 ✔
69
            } else if (alloc_info->stcl == TRICK_EXTERN) {
×
70
                snprintf( name, sizeof(name), "%s%d", extern_anon_var_prefix, extern_anon_var_number++);
×
71
                alloc_info->name = strdup( name);
×
72
                /** @b NOTE: We should not write declarations for external
73
                    anonymous variables, because we should not reload them.*/
74
            } else {
75
                emitError("write_checkpoint: This is bad. ALLOC_INFO object is messed up.\n") ;
×
NEW
76
                checkpoint_write_success = false;
×
77
            }
78
        }
79
        get_stl_dependencies(alloc_info);
1,500 ✔
80
    }
81

82
    // Write a declaration statement for all of the LOCAL variables,
83
    n_depends = dependencies.size();
132 ✔
84
    for (int ii = 0 ; ii < n_depends ; ii ++) {
7,022 ✔
85
        alloc_info = dependencies[ii];
6,890 ✔
86
        if ( alloc_info->stcl == TRICK_LOCAL) {
6,890 ✔
87
            currentCheckPointAgent->write_decl( out_s, alloc_info);
5,982 ✔
88
        }
89
    }
90

91
    // Write a "clear_all_vars" command.
92
    if (reduced_checkpoint) {
132 ✔
93
        out_s << std::endl << std::endl << "// Clear all allocations to 0." << std::endl;
132 ✔
94
        out_s << "clear_all_vars();" << std::endl;
132 ✔
95
    }
96

97
    // 2) Dump the contents of each of the dynamic and mapped allocations.
98
    out_s << std::endl << std::endl << "// Variable Assignments." << std::endl;
132 ✔
99
    out_s.flush();
132 ✔
100

101
    for (int ii = 0 ; ii < n_depends ; ii ++) {
7,022 ✔
102
        alloc_info = dependencies[ii];
6,890 ✔
103
        // Skip naming individual C-string allocations to eliminate unused declarations.
104
        // Individual char arrays (size=1, num_index=1) represent single strings that are
105
        // included in char* arrays, so we don't need separate allocations for them.
106
        // Also, safety check for NULL name before pushing to name stack later.
107
        if (!(alloc_info->type == TRICK_CHARACTER && alloc_info->size == 1 && alloc_info->num_index == 1
6,890 ✔
108
              && alloc_info->stcl == TRICK_LOCAL)
246 ✔
109
            && alloc_info->name != NULL)
6,644 ✔
110
        {
111
            write_var(out_s, alloc_info);
6,644 ✔
112
            out_s << std::endl;
6,644 ✔
113
        }
114
    }
115

116
    // Free all of the temporary names that were created for the checkpoint.
117

118
    for (int ii = 0 ; ii < n_depends ; ii ++) {
7,022 ✔
119
        alloc_info = dependencies[ii];
6,890 ✔
120
        // If the temporary-variable prefix occurs at the beginning of the name ...
121
        if ((alloc_info->name != NULL) &&
6,890 ✔
122
            (( strstr( alloc_info->name, local_anon_var_prefix ) == alloc_info->name ) ||
6,644 ✔
123
             ( strstr( alloc_info->name, extern_anon_var_prefix) == alloc_info->name ))) {
6,272 ✔
124
                free( alloc_info->name);
372 ✔
125
                alloc_info->name = NULL;
372 ✔
126
        }
127
    }
128

129
    // Delete the variables created by STLs. Remove memory in reverse order.
130
    std::vector<ALLOC_INFO*>::reverse_iterator it ;
132 ✔
131
    for ( it = stl_dependencies.rbegin() ; it != stl_dependencies.rend() ; it++ ) {
5,276 ✔
132
        delete_var((*it)->start) ;
5,144 ✔
133
    }
134

135
    out_s.flush();
132 ✔
136
    if (out_s.fail())
132 ✔
137
    {
NEW
138
        emitError("write_checkpoint: An error occurred while writing to the checkpoint output stream.\n");
×
NEW
139
        checkpoint_write_success = false;
×
140
    }
141
    if (!checkpoint_write_success)
132 ✔
142
    {
143
        emitWarning("write_checkpoint: Checkpoint was written with errors and may not restore correctly."
16 ✔
144
                    " See get_checkpoint_write_state() / TMM_get_checkpoint_write_state().");
145
    }
146
}
132 ✔
147

148
// Reset the checkpoint write error state before starting a new checkpoint.
149
void Trick::MemoryManager::begin_checkpoint_write()
176 ✔
150
{
151
    // Called at the start of every public write_checkpoint(). Collects any earlier forked
152
    // checkpoint so its result can't overwrite this one, then resets the write state to true.
153
    // Calling it more than once for the same write is harmless.
154
    wait_for_checkpoint_write();
176 ✔
155
    checkpoint_write_success = true;
176 ✔
156
}
176 ✔
157

158
// MEMBER FUNCTION
159
bool Trick::MemoryManager::get_checkpoint_write_state()
66 ✔
160
{
161
    // Read the result while still holding the lock, so it can't change between collecting
162
    // a forked writer and returning.
163
    pthread_mutex_lock(&checkpoint_write_mutex);
66 ✔
164
    wait_for_checkpoint_write_locked();
66 ✔
165
    bool state = checkpoint_write_success;
66 ✔
166
    pthread_mutex_unlock(&checkpoint_write_mutex);
66 ✔
167
    return state;
66 ✔
168
}
169

170
// MEMBER FUNCTION
171
int Trick::MemoryManager::fork_checkpoint_writer()
40 ✔
172
{
173
    pthread_mutex_lock(&checkpoint_write_mutex);
40 ✔
174

175
    // Collect any earlier forked checkpoint so only one result is pending.
176
    wait_for_checkpoint_write_locked();
40 ✔
177
    reset_forked_checkpoint_result();
40 ✔
178

179
    // The child's code locks mm_mutex. Holding it across fork() makes sure no other thread
180
    // owns it at that moment, so the child's copy can be unlocked and its maps are consistent.
181
    // Flush buffered output first, otherwise the child inherits a copy and prints it again.
182
    std::cout.flush();
40 ✔
183
    fflush(nullptr);
40 ✔
184
    pthread_mutex_lock(&mm_mutex);
40 ✔
185
    pid_t pid = fork();
40 ✔
186
    pthread_mutex_unlock(&mm_mutex);
40 ✔
187

188
    if (pid > 0)
40 ✔
189
    {
190
        checkpoint_write_pid = (int)pid;
40 ✔
191
    }
192
    pthread_mutex_unlock(&checkpoint_write_mutex);
40 ✔
193
    return (int)pid;
40 ✔
194
}
195

196
// MEMBER FUNCTION
197
void Trick::MemoryManager::reset_forked_checkpoint_result()
40 ✔
198
{
199
    if (checkpoint_write_shared == nullptr)
40 ✔
200
    {
201
        void* shared = mmap(nullptr, sizeof(*checkpoint_write_shared), PROT_READ | PROT_WRITE,
16 ✔
202
                            MAP_SHARED | MAP_ANONYMOUS, -1, 0);
203
        if (shared != MAP_FAILED)
16 ✔
204
        {
205
            checkpoint_write_shared = static_cast<int*>(shared);
16 ✔
206
        }
207
    }
208
    if (checkpoint_write_shared != nullptr)
40 ✔
209
    {
210
        volatile int* shared = checkpoint_write_shared;
40 ✔
211
        *shared              = FORKED_WRITE_NOT_REPORTED;
40 ✔
212
    }
213
}
40 ✔
214

215
// MEMBER FUNCTION
NEW
216
void Trick::MemoryManager::report_forked_checkpoint_write()
×
217
{
218
    // volatile (not atomic) is enough here: the parent only reads the value after the child
219
    // has exited and been reaped, and process termination orders the child's writes.
NEW
220
    if (checkpoint_write_shared != nullptr)
×
221
    {
NEW
222
        volatile int* shared = checkpoint_write_shared;
×
NEW
223
        *shared              = checkpoint_write_success ? FORKED_WRITE_SUCCESS : FORKED_WRITE_FAILED;
×
224
    }
NEW
225
}
×
226

227
// MEMBER FUNCTION
228
void Trick::MemoryManager::wait_for_checkpoint_write()
1,502 ✔
229
{
230
    // Only one thread at a time can wait for the forked child. The thread holding the lock
231
    // collects the result and sets checkpoint_write_pid to -1. Other threads block on the lock,
232
    // then find pid -1 and use that result without waiting.
233
    pthread_mutex_lock(&checkpoint_write_mutex);
1,502 ✔
234
    wait_for_checkpoint_write_locked();
1,502 ✔
235
    pthread_mutex_unlock(&checkpoint_write_mutex);
1,502 ✔
236
}
1,502 ✔
237

238
// MEMBER FUNCTION
239
void Trick::MemoryManager::wait_for_checkpoint_write_locked()
1,608 ✔
240
{
241
    if (checkpoint_write_pid <= 0)
1,608 ✔
242
    {
243
        return;
1,568 ✔
244
    }
245

246
    int status = 0;
40 ✔
247
    pid_t ret;
248
    do
249
    {
250
        ret = waitpid(checkpoint_write_pid, &status, 0);
40 ✔
251
    } while (ret == -1 && errno == EINTR);
40 ✔
252
    int saved_errno = errno;
40 ✔
253

254
    if (ret > 0)
40 ✔
255
    {
256
        // If shared memory is available, the child must also have reported its result there;
257
        // this catches a stray exit(0) or exit(1) that didn't come from the checkpoint writer.
258
        bool reported         = true;
30 ✔
259
        bool reported_success = true;
30 ✔
260
        if (checkpoint_write_shared != nullptr)
30 ✔
261
        {
262
            volatile int* shared = checkpoint_write_shared;
30 ✔
263
            int result           = *shared;
30 ✔
264
            reported             = (result != FORKED_WRITE_NOT_REPORTED);
30 ✔
265
            reported_success     = (result == FORKED_WRITE_SUCCESS);
30 ✔
266
        }
267

268
        // Signal: child died abnormally. Exit code > 1 or no reported result: abnormal exit.
269
        // Exit code 1 with a reported result is the child's own reported failure, so no extra warning.
270
        if (WIFSIGNALED(status))
30 ✔
271
        {
272
            emitWarning("write_checkpoint: Forked checkpoint process ended abnormally (signal "
4 ✔
273
                        + std::to_string(WTERMSIG(status)) + "). Checkpoint write state set to false.");
8 ✔
274
        }
275
        else if (WIFEXITED(status) && (WEXITSTATUS(status) > 1 || !reported))
26 ✔
276
        {
277
            emitWarning("write_checkpoint: Forked checkpoint process ended abnormally (exit code "
6 ✔
278
                        + std::to_string(WEXITSTATUS(status)) + (reported ? "" : ", no result reported")
12 ✔
279
                        + "). Checkpoint write state set to false.");
18 ✔
280
        }
281
        // success means the child exited normally with exit code 0 and reported success.
282
        checkpoint_write_success = WIFEXITED(status) && WEXITSTATUS(status) == 0 && reported && reported_success;
30 ✔
283
    }
284
    else if (saved_errno == ECHILD && checkpoint_write_shared != nullptr)
10 ✔
285
    {
286
        // The child was already reaped, e.g. by a SIGCHLD handler (exec_set_trap_sigchld),
287
        // so use the result it reported through shared memory.
288
        // In theory the pid could already have been reused by another child of this process
289
        // before this waitpid() ran; that window is narrow and only exists with the trap on.
290
        volatile int* shared = checkpoint_write_shared;
10 ✔
291
        int result           = *shared;
10 ✔
292
        if (result == FORKED_WRITE_NOT_REPORTED)
10 ✔
293
        {
294
            emitWarning("write_checkpoint: Forked checkpoint process ended abnormally before reporting its result."
4 ✔
295
                        " Checkpoint write state set to false.");
296
        }
297
        checkpoint_write_success = (result == FORKED_WRITE_SUCCESS);
10 ✔
298
    }
10 ✔
299
    else
300
    {
NEW
301
        emitWarning("write_checkpoint: Unable to get the result of the forked checkpoint process ("
×
NEW
302
                    + std::string(strerror(saved_errno)) + "). Checkpoint write state is unknown and set to false.");
×
NEW
303
        checkpoint_write_success = false;
×
304
    }
305
    checkpoint_write_pid = -1;
40 ✔
306
}
307

308
// MEMBER FUNCTION
309
void Trick::MemoryManager::set_checkpoint_write_state(bool state) { checkpoint_write_success = state; }
8 ✔
310

311
// Local sort function used in write_checkpoint.
312
static bool alloc_info_id_compare(ALLOC_INFO * lhs, ALLOC_INFO * rhs) { return ( lhs->id < rhs->id ) ; }
8,556 ✔
313

314
// MEMBER FUNCTION
315
void Trick::MemoryManager::write_checkpoint( std::ostream& out_s) {
38 ✔
316

317
    ALLOC_INFO_MAP::iterator pos;
38 ✔
318
    ALLOC_INFO* alloc_info;
319
    begin_checkpoint_write();
38 ✔
320
    dependencies.clear();
38 ✔
321
    stl_dependencies.clear();
38 ✔
322

323
    pthread_mutex_lock(&mm_mutex);
38 ✔
324
    for ( pos=alloc_info_map.begin() ; pos!=alloc_info_map.end() ; pos++ ) {
1,628 ✔
325
        alloc_info = pos->second;
1,590 ✔
326
        dependencies.push_back(alloc_info);
1,590 ✔
327
    }
328

329
    // Sort the dependencies by ALLOC_INFO.id.
330
    std::sort( dependencies.begin() , dependencies.end() , alloc_info_id_compare) ;
38 ✔
331
    pthread_mutex_unlock(&mm_mutex);
38 ✔
332

333
    execute_checkpoint( out_s );
38 ✔
334

335
}
38 ✔
336

337
// MEMBER FUNCTION
338
void Trick::MemoryManager::write_checkpoint(const char* filename) {
44 ✔
339
    // Collect any pending forked checkpoint before opening the file, so its result can't
340
    // overwrite an open failure below and a child still writing the same file isn't truncated.
341
    begin_checkpoint_write();
44 ✔
342
    std::ofstream outfile(filename, std::ios::out);
44 ✔
343

344
    if (outfile.is_open()) {
44 ✔
345
        write_checkpoint( outfile);
38 ✔
346
    } else {
347
        std::stringstream message;
6 ✔
348
        message << "Couldn't open \"" << filename << "\".";
6 ✔
349
        emitError(message.str());
6 ✔
350
        checkpoint_write_success = false;
6 ✔
351
    }
6 ✔
352
}
44 ✔
353

354
// MEMBER FUNCTION
355
void Trick::MemoryManager::write_checkpoint( std::ostream& out_s, const char* var_name) {
92 ✔
356
    begin_checkpoint_write();
92 ✔
357
    dependencies.clear();
92 ✔
358
    stl_dependencies.clear();
92 ✔
359

360
    pthread_mutex_lock(&mm_mutex);
92 ✔
361
    get_alloc_deps_in_allocation( var_name);
92 ✔
362
    pthread_mutex_unlock(&mm_mutex);
92 ✔
363

364
    execute_checkpoint( out_s );
92 ✔
365
}
92 ✔
366

367
// MEMBER FUNCTION
368
void Trick::MemoryManager::write_checkpoint(const char* filename, const char* var_name) {
×
369
    // Collect any pending forked checkpoint before opening the file, so its result can't
370
    // overwrite an open failure below and a child still writing the same file isn't truncated.
NEW
371
    begin_checkpoint_write();
×
372
    std::ofstream out_s( filename, std::ios::out);
×
373
    if (out_s.is_open()) {
×
374
        write_checkpoint( out_s, var_name);
×
375
    } else {
376
        std::stringstream message;
×
377
        message << "Couldn't open \"" << filename << "\".";
×
378
        emitError(message.str());
×
NEW
379
        checkpoint_write_success = false;
×
380
    }
×
381
}
×
382

383
// MEMBER FUNCTION
384
void Trick::MemoryManager::write_checkpoint( std::ostream& out_s, std::vector<const char*>& var_name_list) {
2 ✔
385

386
    const char* var_name;
387
    int n_names;
388

389
    begin_checkpoint_write();
2 ✔
390
    dependencies.clear();
2 ✔
391
    stl_dependencies.clear();
2 ✔
392

393
    n_names = var_name_list.size();
2 ✔
394
    for (int ii=0; ii< n_names; ii++) {
6 ✔
395
        var_name = var_name_list[ii];
4 ✔
396
        pthread_mutex_lock(&mm_mutex);
4 ✔
397
        get_alloc_deps_in_allocation(var_name);
4 ✔
398
        pthread_mutex_unlock(&mm_mutex);
4 ✔
399
    }
400

401
    execute_checkpoint( out_s );
2 ✔
402
}
2 ✔
403

404
// MEMBER FUNCTION
405
void Trick::MemoryManager::write_checkpoint(const char* filename, std::vector<const char*>& var_name_list) {
×
406
    // Collect any pending forked checkpoint before opening the file, so its result can't
407
    // overwrite an open failure below and a child still writing the same file isn't truncated.
NEW
408
    begin_checkpoint_write();
×
UNCOV
409
    std::ofstream out_s( filename, std::ios::out);
×
410

411
    if (out_s.is_open()) {
×
412
        write_checkpoint( out_s, var_name_list);
×
413
    } else {
414
        std::cerr << "ERROR: Couldn't open \""<< filename <<"\"." << std::endl;
×
415
        std::cerr.flush();
×
NEW
416
        checkpoint_write_success = false;
×
417
    }
418
}
×
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