-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval.c
3460 lines (2996 loc) · 95.2 KB
/
eval.c
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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file eval.c
* @author Ricardo Fonseca
* @brief Toolkit for evaluating student code
* @version 0.5.1
* @date 2024-05-15
*
* @copyright Copyright (C) 2024 Ricardo Fonseca
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include <stdarg.h>
#include <errno.h>
#include <fcntl.h>
#include <math.h>
/**
* Undefine the replacement macros defined in eval.h so we may call the base
* functions
*/
#define EVAL_NOWRAP 1
#include "eval.h"
/**
* @brief Find index of question with given key
*
* @param questions Question list
* @param key Element key
* @return int Element index value, -1 if key not found
*/
int question_find( question_t questions[], char key[] ) {
int idx = -1;
for( int i = 0; i < MAX_QUESTIONS; i++ ) {
if ( ! strncmp( questions[i].key, "---", 16 ) ) break;
if ( ! strncmp( questions[i].key, key, 16 ) ) {
idx = i;
break;
}
}
return idx;
}
/**
* @brief Find element text from index
*
* @param questions Question list
* @param key Element key
* @return char* Element text, "<not found>" if key not found
*/
char *question_text( question_t questions[], char key[] ) {
int idx = question_find( questions, key );
if ( idx < 0 ) {
return "<not found>";
} else {
return questions[idx].text;
}
}
/**
* @brief Set element grade
*
* @param questions Question list
* @param key Element key
* @param grade New value of grade
* @return int Element index or -1 if key not found
*/
int question_setgrade( question_t questions[], char key[], float grade ) {
int idx = question_find( questions, key );
if ( idx >= 0 ) {
questions[idx].grade = grade;
} else {
fprintf(stderr,"(*error*) Bad key: %s\n", key );
}
return idx;
}
/**
* @brief Print a detailed list of keys, questions and grades
*
* @param questions Question list
* @param msg Message to print before the list
* @return int Number of questions in the list
*/
int question_list( question_t questions[], char* msg ) {
if ( msg ) printf("\n\033[1m[%s]\033[0m\n", msg);
printf("\nQuestion list:\n");
printf("--------------\n");
double total = 0;
int i;
for( i = 0; i < MAX_QUESTIONS; i++ ) {
if ( ! strcmp( questions[i].key, "---" ) ) break;
total += questions[i].grade;
printf("%-7s [%4.2f] - %s\n",questions[i].key, questions[i].grade, questions[i].text );
}
printf("\nTotal number of questions: %d\n", i);
if ( i > 0 ) {
if ( round(total) == i ) {
printf("\033[1;32m[✔]\033[0m Total score: %g/%d\n", total, i);
} else {
printf("\033[1;31m[✗]\033[0m Total score: %g/%d\n", total, i);
}
}
return i;
}
/**
* @brief Export question grades
*
* Prints all question keys / grades to screen
*
* @param questions Question list
* @param msg Message to print before / after the grades
*/
void question_export( question_t questions[], char msg[] ) {
printf("\n%s:grade\n", msg );
if ( strncmp( questions[0].key, "---", 16 ) ) {
printf("%s:%4.2f",questions[0].key, questions[0].grade);
for( int i = 1; i < MAX_QUESTIONS; i++ ) {
if ( ! strcmp( questions[i].key, "---" ) ) break;
printf(",%s:%4.2f",questions[i].key, questions[i].grade);
}
}
printf("\n%s:end\n", msg );
}
log_t _success_log;
log_t _error_log;
log_t _data_log;
eval_stats_t _eval_stats;
/**
* initialize a log_t variable
* @param log Log variable to initialize
*/
void initlog( log_t* log ) {
log -> start = -1;
log -> end = 0;
}
/**
* Returns a pointer to a new line in the log and updates internal pointers
* @param log Log variable
* @return char* to a new line
*/
char *newline( log_t* log ) {
char *line = NULL;
if ( log -> end < LOGSIZE ) {
line = log -> buffer[ log -> end ];
if ( log -> start < 0 ) log -> start = 0;
log -> end++;
} else {
eval_error( "No more space in logbuffer, aborting" );
eval_error( "Last message was: \"%s\"", log -> buffer[LOGSIZE-1]);
// Check if this happened inside an EVAL_CATCH macro
if ( _eval_env.catch ) {
siglongjmp( _eval_env.jmp, EVAL_CATCH_LOG_OVERFLOW );
} else {
exit(1);
}
}
return line;
}
/**
* Prints entire log
* @param log Log variable
*/
void printlog( log_t* log ) {
if ( log -> start < 0 || log -> start >= log -> end ) {
printf("<empty>\n");
} else {
for( int i = log -> start, j = 0; i != log -> end; i++, j++ ) {
printf("%3d - %s\n", j, log -> buffer[i]);
}
}
}
/**
* @brief Looks for the message specified by the format and optional arguments.
* Returns the index position on success or -1 if not found.
*
* @param log Log
* @param format Format for message
* @param ... Optional message values
* @return int Position in log or -1 if not found
*/
int findinlog( log_t* log, const char *restrict format, ... ) {
char msg[LOGLINE];
va_list ap;
va_start(ap, format);
vsnprintf(msg, LOGLINE-1, format, ap);
va_end(ap);
int idx = -1;
for( int i = log->start; i != log->end; i++ ) {
if ( !strncmp( msg, log->buffer[i], LOGLINE-1) ) {
idx = i;
break;
}
}
return idx;
}
/**
* Removes the head line from the log if it contains the supplied message
*
* @param msg Messagem to look for
* @return 0 on success, -1 on error (empty log or msg not found)
*/
int rmheadmsg( log_t* log, const char msg[] ) {
if ( log -> start < 0 ) return -1;
if ( strstr( log -> buffer[ log -> start], msg ) ) {
// Remove the line
log -> start ++;
return 0;
} else {
return -1;
}
}
/**
* Returns the string at the head of the log or "empty" if empty
*
* @param log Log
* @return Pointer to string
*/
const char* loghead( log_t* log ) {
static const char empty[] = "<empty>";
if ( log -> start < 0 ) return empty;
else return log -> buffer[log -> start];
}
/**
* @brief Adds line into specified log
*
* @param log Pointer to log variable
* @param format Format modifier
* @param ... Values
* @return int Number of characters written
*/
int eval_log( log_t* log, const char *restrict format, ...) {
va_list ap;
va_start(ap, format);
int n = vsnprintf(newline( log ), LOGLINE, format, ap);
va_end(ap);
return n;
}
/**
* @brief Adds line into datalog
*
* @param format Format modifier
* @param ... Values
* @return int Number of characters written
*/
int datalog(const char *restrict format, ...) {
va_list ap;
va_start(ap, format);
int n = vsnprintf(newline( &_data_log ), LOGLINE, format, ap);
va_end(ap);
return n;
}
/**
* @brief Adds line into datalog
*
* @param format Format modifier
* @param ... Values
* @return int Number of characters written
*/
int errorlog(const char *restrict format, ...) {
va_list ap;
va_start(ap, format);
int n = vsnprintf(newline( &_error_log ), LOGLINE, format, ap);
va_end(ap);
return n;
}
/**
* @brief Adds line into successlog
*
* @param format Format modifier
* @param ... Values
* @return int Number of characters written
*/
int successlog(const char *restrict format, ...) {
va_list ap;
va_start(ap, format);
int n = vsnprintf(newline( &_success_log ), LOGLINE, format, ap);
va_end(ap);
return n;
}
/**
* @brief Checks if the supplied message (specified by format and optionally additional values)
* is at the head of the success log.
*
* If true, removes head line and returns 0, otherwise issues an error message.
*
* @param format Format for message
* @param ... (optional) additional values
* @return int 1 on success, 0 if message not found at head
*/
int eval_check_successlog( const char *restrict format, ...) {
char msg[LOGLINE];
va_list ap;
va_start(ap, format);
vsnprintf(msg, LOGLINE-1, format, ap);
va_end(ap);
const char *log_msg = loghead(&_success_log);
if ( rmheadmsg( &_success_log, msg ) ) {
eval_error( "Invalid success log message, expected '%s', got '%s'",
msg, log_msg );
return 0;
} else {
eval_success( "Success log ok: '%s'", log_msg );
return 1;
}
}
/**
* @brief Checks if the supplied message (specified by format and optionally additional values)
* is at the head of the error log.
*
* If true, removes head line and returns 0, otherwise issues an error message.
*
* @param format Format for message
* @param ... (optional) additional values
* @return int 1 on success, 0 if message not found at head
*/
int eval_check_errorlog( const char *restrict format, ...) {
char msg[LOGLINE];
va_list ap;
va_start(ap, format);
vsnprintf(msg, LOGLINE-1, format, ap);
va_end(ap);
const char *err_msg = loghead(&_error_log);
if ( rmheadmsg( &_error_log, msg ) ) {
eval_error( "Invalid error log message, expected '%s', got '%s'",
msg, err_msg );
return 0;
} else {
eval_success( "Error log ok: '%s'", err_msg );
return 1;
}
}
/**
* Clears both success and error logs
*/
void eval_clear_logs( void ) {
initlog( &_success_log );
initlog( &_error_log );
initlog( &_data_log );
}
/**
* Clears both success and error logs, and prints remaning messages if any
*/
void eval_close_logs( char msg[] ) {
if ( _success_log.start >= 0 && _success_log.start < _success_log.end ) {
eval_info( "%s Remaining messages on success log", msg );
for( int i = _success_log.start; i != _success_log.end; i++ ) {
printf("%3d - %s\n", i, _success_log.buffer[i]);
}
}
if ( _error_log.start >= 0 && _error_log.start < _error_log.end ) {
eval_info( "%s Remaining messages on error log", msg );
for( int i = _error_log.start; i != _error_log.end; i++ ) {
printf("%3d - %s\n", i, _error_log.buffer[i]);
}
}
eval_clear_logs( );
}
/**
* @brief Checks errors at section completion
*
* @param msg Message to print
* @return int Total of errors found
*/
int eval_complete( char msg[] ) {
if ( _eval_stats.error > 0 ) {
printf("\033[1;31m[✗]\033[0m %s completed with %d error(s).\n", msg, _eval_stats.error );
} else {
printf("\033[1;32m[✔]\033[0m %s completed with no errors.\n", msg );
}
printf("\n");
return _eval_stats.error;
}
/**
* @brief Prints error message and updates error counter
*
* @param format Format modifier
* @param ... Values
* @return int Current number of errors
*/
int eval_error(const char *restrict format, ...) {
va_list ap;
size_t size = 0;
char *tmp = NULL;
va_start(ap, format);
int n = vsnprintf(tmp, size, format, ap);
va_end(ap);
// Allocate temporary buffer
size = (size_t) n + 1;
tmp = malloc( size );
// Print to buffer
va_start(ap, format);
vsnprintf(tmp, size, format, ap);
va_end(ap);
printf("\033[1;31m[✗]\033[0m %s\n", tmp );
free(tmp);
_eval_stats.error++;
return _eval_stats.error;
}
/**
* @brief Prints info message and updates the info counter
*
* @param format Format modifier
* @param ... Values
* @return int Current number of errors
*/
int eval_info(const char *restrict format, ...) {
va_list ap;
size_t size = 0;
char *tmp = NULL;
va_start(ap, format);
int n = vsnprintf(tmp, size, format, ap);
va_end(ap);
// Allocate temporary buffer
size = (size_t) n + 1;
tmp = malloc( size );
// Print to buffer
va_start(ap, format);
vsnprintf(tmp, size, format, ap);
va_end(ap);
printf("\033[1;34m[ℹ︎]\033[0m %s\n", tmp );
free(tmp);
_eval_stats.info++;
return _eval_stats.info;
}
/**
* @brief Prints success message and updates info counter
*
* @param format Format modifier
* @param ... Values
* @return int Current number of errors
*/
int eval_success(const char *restrict format, ...) {
va_list ap;
size_t size = 0;
char *tmp = NULL;
va_start(ap, format);
int n = vsnprintf(tmp, size, format, ap);
va_end(ap);
// Allocate temporary buffer
size = (size_t) n + 1;
tmp = malloc( size );
// Print to buffer
va_start(ap, format);
vsnprintf(tmp, size, format, ap);
va_end(ap);
printf("\033[1;32m[✔]\033[0m %s\n", tmp );
free(tmp);
_eval_stats.info++;
return _eval_stats.info;
}
/**
* @brief Variable holding stdin and stdout descriptors (previous and current)
*
*/
_eval_stdio_t _eval_stdio;
/**
* @brief Redirects stdin and stdout to files
*
* Requires data in _eval_stdio
*
* @param stdin File name for stdin. If set to NULL no redirection takes place
* @param stdout File name for stdout. If set to NULL no redirection takes place
* @return int 0 on success
*/
int _eval_io_redirect( const char* _fstdin, const char* _fstdout ) {
if ( _fstdin ) {
if ( (_eval_stdio.old_stdin = dup( STDIN_FILENO ))< 0 ) {
eval_error("Unable to duplicate STDIN_FILENO");
return -1;
}
int new_stdin;
if ( (new_stdin = open( _fstdin, O_RDONLY )) < 0 ) {
eval_error("Unable to open file %s as read-only", _fstdin);
return -1;
}
if ( (dup2( new_stdin, STDIN_FILENO )) < 0 ) {
eval_error("Unable to associate file %s with stdin", _fstdin);
return -1;
};
if ( close(new_stdin) < 0 ) {
eval_error("Unable to close fd %d", new_stdin );
return -1;
};
} else {
_eval_stdio.old_stdin = -1;
}
if ( _fstdout ) {
if ( (_eval_stdio.old_stdout = dup( STDOUT_FILENO )) < 0 ) {
fprintf(stderr, "Unable to duplicate STDOUT_FILENO\n");
eval_error("Unable to duplicate STDOUT_FILENO");
return -1;
}
int new_stdout;
if ( (new_stdout = open( _fstdout, O_CREAT | O_WRONLY | O_TRUNC, 0600 )) < 0 ) {
fprintf(stderr, "Unable to open file %s as write-only\n", _fstdout);
eval_error("Unable to open file %s as write-only", _fstdout);
return -1;
}
if ( (dup2( new_stdout, STDOUT_FILENO )) < 0 ) {
fprintf(stderr, "Unable to associate file %s with stdout\n", _fstdout);
eval_error("Unable to associate file %s with stdout", _fstdout);
return -1;
}
if ( close( new_stdout ) < 0 ) {
fprintf(stderr, "Unable to close new_stdout file descriptor\n");
return -1;
}
} else {
_eval_stdio.old_stdout = -1;
}
return 0;
}
/**
* @brief Restores stdin and stdout to console
*
* Requires data in _eval_stdio
*
* @return int 0 on success
*/
int _eval_io_restore( void ) {
if ( _eval_stdio.old_stdout != -1 ) {
// Flush any remaining data to disk
// If this is not done then this data will be sent to the next STDOUT device
fflush( stdout );
if ( dup2( _eval_stdio.old_stdout, STDOUT_FILENO ) < 0 ) {
fprintf(stderr, "Unable to reassociate STDOUT with console\n" );
return -1;
}
if ( close( _eval_stdio.old_stdout ) < 0 ) {
fprintf(stderr, "Unable to close old_stdout file\n" );
return -1;
}
}
if ( _eval_stdio.old_stdin != -1 ) {
// Clear any remaining data on stdin
// If this is not done then it will remain in STDIN
fflush( stdin );
if ( dup2( _eval_stdio.old_stdin, STDIN_FILENO ) < 0 ) {
fprintf(stderr, "Unable to reassociate STDIN with console\n" );
return -1;
}
if ( close( _eval_stdio.old_stdin ) < 0 ) {
fprintf(stderr, "Unable to close old_stdin file\n" );
return -1;
}
}
return 0;
}
/**
* @brief Initialize file monitor variable
*
* This value will be used to check if the test routine left any files open
*/
void _eval_init_filemon( void ) {
// Get the file descriptor value of a new file
// All files opened from test code should have a descriptor >= than this
_eval_env.filemon = dup(STDERR_FILENO);
close(_eval_env.filemon);
}
/**
* @brief Closes any files open (besides STDIN, STDOUT and STDERR)
*
* Requires values in _eval_env.filemon
*/
void _eval_close_filemon( void ) {
// Get maximum number of open file descriptors
const int maxfd=sysconf(_SC_OPEN_MAX);
// Go through all possible file descriptors starting from .filemon
int nfiles = 0;
for( int fd = _eval_env.filemon; fd < maxfd; fd++ ) {
if ( close(fd) ) {
// If file was not open, errno is set to EBADF
if ( errno != EBADF ) {
// File is opened but close failed for another reason
nfiles++;
perror("_eval_close_filemon: Unable to close file");
}
} else {
// File closed successfully
nfiles++;
}
}
if ( nfiles > 0 ) {
if ( nfiles == 1 ) {
eval_error("1 file was not closed" );
} else {
eval_error("%d files were not closed", nfiles );
}
}
}
/**
* @brief Resets the _eval_stats variable
*
*/
void eval_reset_stats( void ) {
_eval_stats.error = 0;
_eval_stats.info = 0;
}
/**
* @brief Configuration variable for the eval_checkptr() function
*
*/
struct {
int stat;
int sig;
jmp_buf jmp;
char buffer;
}_eval_checkptr_data;
/**
* @brief Signal handler for the eval_checkptr function
* Requires data in the _eval_checkptr_data variable
*
* @param sig
* @param info
* @param ucontext
*/
void _eval_checkptr_sighndlr( int sig, siginfo_t *info, void *ucontext) {
_eval_checkptr_data.stat = 1;
_eval_checkptr_data.sig = sig;
siglongjmp( _eval_checkptr_data.jmp, 1 );
}
/**
* Checks if a pointer is valid by reading/writing 1 byte from/to address
* @param ptr Pointer to be evaluated
* @return 0 is pointer is valid
* 1 NULL pointer
* 2 (-1) pointer
* 3 Segmentation fault when accessing pointer
* 4 Bus Error when accessing pointer
* 5 Invalid signal caught (should never happen)
*/
int eval_checkptr( void* ptr ) {
if ( ptr == NULL ) {
eval_error("NULL pointer");
return 1;
}
if ( ptr == (void *) -1 ) {
eval_error("Invalid pointer %p", ptr );
return 2;
}
// Catch SIGSEGV and SIGBUS
struct sigaction act = {
.sa_flags = SA_SIGINFO | SA_RESTART,
.sa_sigaction = _eval_checkptr_sighndlr
};
struct sigaction tmp[2];
if ( sigaction( SIGSEGV, &act, &tmp[0] ) < 0 ) {
perror("eval_checkptr: (*critical*) Unable to set SIGSEGV handler");
exit(1);
};
if ( sigaction( SIGBUS, &act, &tmp[1] ) < 0 ) {
perror("eval_checkptr: (*critical*) Unable to set SIGBUS handler");
exit(1);
};
// Reset _eval_checkptr_data
_eval_checkptr_data.stat = 0;
_eval_checkptr_data.sig = -1;
// Access memory at position ptr, invalid pointers will throw a signal
int stat = sigsetjmp( _eval_checkptr_data.jmp, 1 );
if ( !stat ) {
char *p = (char *) ptr;
_eval_checkptr_data.buffer = *p;
*p = _eval_checkptr_data.buffer;
}
// Restore previous signal handlers
if ( sigaction( SIGSEGV, &tmp[0], NULL ) < 0 ) {
perror("eval_checkptr: (*critical*) Unable to reset SIGSEGV handler");
exit(1);
};
if ( sigaction( SIGBUS, &tmp[0], NULL ) < 0 ) {
perror("eval_checkptr: (*critical*) Unable to reset SIGBUS handler");
exit(1);
};
if ( _eval_checkptr_data.stat ) {
switch( _eval_checkptr_data.sig ) {
case(SIGSEGV):
eval_error("(checkptr) Accessing %p caused Segmentation Fault", ptr);
return 3;
case(SIGBUS):
eval_error("(checkptr) Accessing %p caused Bus Error", ptr);
return 4;
default:
eval_error("(checkptr) Accessing %p caused unknonown signal", ptr);
return 5;
}
}
return 0;
}
/**
* Checks if a pointer is valid by reading 1 byte from address
* @param ptr Pointer to be evaluated
* @return 0 is pointer is valid
* 1 NULL pointer
* 2 (-1) pointer
* 3 Segmentation fault when accessing pointer
* 4 Bus Error when accessing pointer
* 5 Invalid signal caught (should never happen)
*/
int eval_checkconstptr( const void * ptr ) {
if ( ptr == NULL ) {
eval_error("NULL pointer");
return 1;
}
if ( ptr == (void *) -1 ) {
eval_error("Invalid pointer %p", ptr );
return 2;
}
// Catch SIGSEGV and SIGBUS
struct sigaction act = {
.sa_flags = SA_SIGINFO | SA_RESTART,
.sa_sigaction = _eval_checkptr_sighndlr
};
struct sigaction tmp[2];
if ( sigaction( SIGSEGV, &act, &tmp[0] ) < 0 ) {
perror("eval_checkptr: (*critical*) Unable to set SIGSEGV handler");
exit(1);
};
if ( sigaction( SIGBUS, &act, &tmp[1] ) < 0 ) {
perror("eval_checkptr: (*critical*) Unable to set SIGBUS handler");
exit(1);
};
// Reset _eval_checkptr_data
_eval_checkptr_data.stat = 0;
_eval_checkptr_data.sig = -1;
// Access memory at position ptr, invalid pointers will throw a signal
int stat = sigsetjmp( _eval_checkptr_data.jmp, 1 );
if ( !stat ) {
char *p = (char *) ptr;
_eval_checkptr_data.buffer = *p;
}
// Restore previous signal handlers
if ( sigaction( SIGSEGV, &tmp[0], NULL ) < 0 ) {
perror("eval_checkptr: (*critical*) Unable to reset SIGSEGV handler");
exit(1);
};
if ( sigaction( SIGBUS, &tmp[0], NULL ) < 0 ) {
perror("eval_checkptr: (*critical*) Unable to reset SIGBUS handler");
exit(1);
};
if ( _eval_checkptr_data.stat ) {
switch( _eval_checkptr_data.sig ) {
case(SIGSEGV):
eval_error("(checkptr) Accessing %p caused Segmentation Fault", ptr);
return 3;
case(SIGBUS):
eval_error("(checkptr) Accessing %p caused Bus Error", ptr);
return 4;
default:
eval_error("(checkptr) Accessing %p caused unknonown signal", ptr);
return 5;
}
}
return 0;
}
/**
* @brief Reads a line from file f and compares it with the string s2
*
* @param f
* @param s2
* @param n Max. size for the comparison
* @return int Returns
*/
int eval_fstrncmp( FILE *f, const char *s2, const size_t n ) {
int ret;
if (f) {
char buffer[ n + 1 ];
fgets( buffer, n, f );
size_t size = strlen( s2 );
if ( n < size ) size = n;
// printf( "eval_fstrncmp: %s, %s, %ld ", buffer, s2, n );
ret = strncmp( buffer, s2, size );
} else {
ret = -2;
}
return ret;
}
/**
* @brief Creates a "locked" file, i.e. a file with 0000 permissions
*
* Note that this file can still be removed using unlink() or remove()
*
* @param fname Name of the file to create
*
* @return int 0 on success, -1 on error
*/
int create_lockfile( char *fname ) {
// Open file and write magic bytes
FILE *f = fopen( fname, "w" );
if ( f == NULL ) {
perror("create_lockfile: Unable to create lock file");
return -1;
} else {
char magic[] = "LOCK";
if ( fwrite( magic, 1, 4, f ) != 4 ) {
perror("create_lockfile: Unable to write magic bytes to lock file");
return -1;
};
if ( fclose(f) ) {
perror("create_lockfile: Unable to close lock file");
return -1;
}
// Remove all permissions
if ( chmod( fname, 0000 ) ) {
perror("create_lockfile: Unable to set lock file permissions");
return -1;
}
}
return 0;
}
/**
* @brief Removes a "locked" file created by create_lockfile()
*
* User must be file owner.
*
* @param fname Name of the file to create
*
* @return int 0 on success, -1 on error
*/
int remove_lockfile( char *fname ) {
struct stat st;
if ( stat( fname, &st ) < 0 ) {
perror("remove_lockfile: File no longer exists" );
return -1;
}
// Unlink does not check write permission
if ( unlink( fname ) ) {
perror("remove_lockfile: Unable to remove lock file");
return -1;
};
return 0;
}
/**
* Global variable for use by the EVAL_CATCH* macros
*/
_eval_env_type _eval_env = {0};
/**
* Global variable for use by the eval_termination() function
*/
char _eval_term_str[256] = {0};
/**
* @brief Pointer to string describing the test code termination
*
* Requires values in _eval_env. Note that the function always returns a pointer
* to the same location, the global _eval_term_str variable is modified with the
* updated termination message.
*
* @return const char* Test code termination description
*/
const char* eval_termination( void ) {
char *signame;
switch( _eval_env.stat ) {
case(0):
snprintf(_eval_term_str, 255, "code returned normally" );