-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTimeMem.c
More file actions
1385 lines (1254 loc) · 37.7 KB
/
TimeMem.c
File metadata and controls
1385 lines (1254 loc) · 37.7 KB
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
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS 1
#endif
#if !defined(_WIN32) && !defined(_GNU_SOURCE)
#define _GNU_SOURCE 1
#endif
#include <ctype.h>
#include <errno.h>
#include <float.h>
#include <inttypes.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <Psapi.h>
#else
#include <signal.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#endif
#define PROGRAM_NAME "timemem"
#define PROGRAM_VERSION "2.0"
#define EXIT_CANCELED 125
#define EXIT_CANNOT_INVOKE 126
#define EXIT_ENOENT 127
#define EXIT_TIMED_OUT 124
#define SIGNALLED_OFFSET 128
static const char *const DEFAULT_FORMAT =
"%Uuser %Ssystem %Eelapsed %PCPU (%Xavgtext+%Davgdata %Mmaxresident)k\n"
"%Iinputs+%Ooutputs (%Fmajor+%Rminor)pagefaults %Wswaps";
static const char *const POSIX_FORMAT =
"real %e\n"
"user %U\n"
"sys %S";
static const char *const VERBOSE_FORMAT =
"\tCommand being timed: \"%C\"\n"
"\tUser time (seconds): %U\n"
"\tSystem time (seconds): %S\n"
"\tPercent of CPU this job got: %P\n"
"\tElapsed (wall clock) time (h:mm:ss or m:ss): %E\n"
"\tAverage shared text size (kbytes): %X\n"
"\tAverage unshared data size (kbytes): %D\n"
"\tAverage stack size (kbytes): %p\n"
"\tAverage total size (kbytes): %K\n"
"\tMaximum resident set size (kbytes): %M\n"
"\tAverage resident set size (kbytes): %t\n"
"\tMajor (requiring I/O) page faults: %F\n"
"\tMinor (reclaiming a frame) page faults: %R\n"
"\tVoluntary context switches: %w\n"
"\tInvoluntary context switches: %c\n"
"\tSwaps: %W\n"
"\tFile system inputs: %I\n"
"\tFile system outputs: %O\n"
"\tSocket messages sent: %s\n"
"\tSocket messages received: %r\n"
"\tSignals delivered: %k\n"
"\tPage size (bytes): %Z\n"
"\tExit status: %x";
typedef enum OutputMode
{
OUTPUT_DEFAULT = 0,
OUTPUT_CUSTOM,
OUTPUT_POSIX,
OUTPUT_OLD
} OutputMode;
typedef enum ExitKind
{
EXIT_KIND_NORMAL = 0,
EXIT_KIND_SIGNALLED,
EXIT_KIND_STOPPED,
EXIT_KIND_TIMEOUT,
EXIT_KIND_UNKNOWN
} ExitKind;
typedef struct Options
{
bool append;
bool quiet;
bool verbose;
bool show_help;
bool show_version;
bool timeout_enabled;
double timeout_seconds;
const char *format;
const char *output_path;
OutputMode output_mode;
int command_index;
} Options;
typedef struct Metrics
{
double elapsed_seconds;
double user_seconds;
double system_seconds;
uint64_t avg_shared_text_kb;
uint64_t avg_unshared_data_kb;
uint64_t avg_stack_kb;
uint64_t avg_total_kb;
uint64_t avg_resident_kb;
uint64_t max_resident_kb;
uint64_t file_inputs;
uint64_t file_outputs;
uint64_t major_page_faults;
uint64_t minor_page_faults;
uint64_t page_fault_count;
uint64_t swaps;
uint64_t signals_delivered;
uint64_t socket_messages_sent;
uint64_t socket_messages_received;
uint64_t voluntary_context_switches;
uint64_t involuntary_context_switches;
uint64_t page_size_bytes;
uint64_t peak_working_set_kb;
uint64_t peak_paged_pool_kb;
uint64_t peak_nonpaged_pool_kb;
uint64_t peak_pagefile_kb;
ExitKind exit_kind;
int exit_status;
int exit_code;
int signal_number;
bool timed_out;
} Metrics;
typedef struct StringBuilder
{
char *data;
size_t length;
size_t capacity;
} StringBuilder;
static void usage(FILE *stream)
{
fprintf(stream,
"Usage: %s [OPTIONS] COMMAND [ARG]...\n"
"Run COMMAND, then print system resource usage.\n"
"\n"
" -a, --append with -o/--output FILE, append instead of overwrite\n"
" -f, --format FORMAT use FORMAT instead of the default output\n"
" -o, --output FILE write summary to FILE instead of the default stream\n"
" --output-file FILE alias for --output\n"
" --old print the legacy pre-change report layout\n"
" -p, --portability print POSIX-compatible output\n"
" -q, --quiet suppress abnormal termination messages\n"
" -t, --timeout DURATION terminate the command after DURATION\n"
" -v, --verbose print the verbose statistics report\n"
" -V, --version display version information and exit\n"
" --help display this help and exit\n"
"\n"
"DURATION accepts a floating-point value with optional suffix:\n"
" s seconds (default), m minutes, h hours, d days\n"
" 0 disables the timeout.\n"
"\n"
"Common format sequences for -f/--format:\n"
" %% literal %%\n"
" %%%% literal %% (escaped for printf above)\n"
" %%C command line and arguments\n"
" %%D average unshared data size in KB\n"
" %%E elapsed wall clock time as [h:]m:ss.ss\n"
" %%e elapsed wall clock time in seconds\n"
" %%F major page faults\n"
" %%I file system inputs\n"
" %%K average total memory use in KB\n"
" %%M maximum resident set size in KB\n"
" %%O file system outputs\n"
" %%P percent CPU\n"
" %%R minor page faults\n"
" %%S system time in seconds\n"
" %%Tt termination type (normal/signalled/stopped/timeout)\n"
" %%Tn signal number when signalled\n"
" %%Ts signal name when signalled\n"
" %%Tx exit code when available\n"
" %%To ok if the command completed successfully\n"
" %%U user time in seconds\n"
" %%W swaps\n"
" %%X average shared text size in KB\n"
" %%Z page size in bytes\n"
" %%c involuntary context switches\n"
" %%k signals delivered\n"
" %%p average stack size in KB\n"
" %%r socket messages received\n"
" %%s socket messages sent\n"
" %%t average resident set size in KB\n"
" %%w voluntary context switches\n"
" %%x command exit status\n",
PROGRAM_NAME);
}
static void print_version(void)
{
printf("%s %s\n", PROGRAM_NAME, PROGRAM_VERSION);
}
static void fatal_out_of_memory(void)
{
fprintf(stderr, "%s: out of memory\n", PROGRAM_NAME);
exit(EXIT_FAILURE);
}
static bool strings_equal(const char *lhs, const char *rhs)
{
return strcmp(lhs, rhs) == 0;
}
static bool starts_with(const char *text, const char *prefix)
{
return strncmp(text, prefix, strlen(prefix)) == 0;
}
static char *duplicate_string(const char *text)
{
size_t length = strlen(text) + 1;
char *copy = (char *)malloc(length);
if (copy == NULL)
fatal_out_of_memory();
memcpy(copy, text, length);
return copy;
}
static void builder_init(StringBuilder *builder)
{
builder->data = NULL;
builder->length = 0;
builder->capacity = 0;
}
static void builder_reserve(StringBuilder *builder, size_t extra)
{
size_t required = builder->length + extra + 1;
if (required <= builder->capacity)
return;
size_t new_capacity = builder->capacity == 0 ? 64 : builder->capacity;
while (new_capacity < required)
new_capacity *= 2;
char *new_data = (char *)realloc(builder->data, new_capacity);
if (new_data == NULL)
fatal_out_of_memory();
builder->data = new_data;
builder->capacity = new_capacity;
}
static void builder_append_char(StringBuilder *builder, char value)
{
builder_reserve(builder, 1);
builder->data[builder->length++] = value;
builder->data[builder->length] = '\0';
}
static void builder_append_text(StringBuilder *builder, const char *text)
{
size_t length = strlen(text);
builder_reserve(builder, length);
memcpy(builder->data + builder->length, text, length);
builder->length += length;
builder->data[builder->length] = '\0';
}
static char *builder_take(StringBuilder *builder)
{
if (builder->data == NULL)
{
char *empty = duplicate_string("");
return empty;
}
char *result = builder->data;
builder->data = NULL;
builder->length = 0;
builder->capacity = 0;
return result;
}
static bool parse_duration(const char *text, double *seconds)
{
char *end = NULL;
double multiplier = 1.0;
double value;
if (text == NULL || *text == '\0')
return false;
errno = 0;
value = strtod(text, &end);
if (errno != 0 || end == text || value < 0.0)
return false;
if (*end != '\0')
{
if (end[1] != '\0')
return false;
switch (tolower((unsigned char)*end))
{
case 's':
multiplier = 1.0;
break;
case 'm':
multiplier = 60.0;
break;
case 'h':
multiplier = 60.0 * 60.0;
break;
case 'd':
multiplier = 60.0 * 60.0 * 24.0;
break;
default:
return false;
}
}
if (value > DBL_MAX / multiplier)
return false;
*seconds = value * multiplier;
return true;
}
static const char *termination_type_name(ExitKind kind)
{
switch (kind)
{
case EXIT_KIND_NORMAL:
return "normal";
case EXIT_KIND_SIGNALLED:
return "signalled";
case EXIT_KIND_STOPPED:
return "stopped";
case EXIT_KIND_TIMEOUT:
return "timeout";
default:
return "unknown";
}
}
static double safe_cpu_percent(const Metrics *metrics)
{
double cpu = metrics->user_seconds + metrics->system_seconds;
if (metrics->elapsed_seconds <= 0.0)
return -1.0;
return (cpu * 100.0) / metrics->elapsed_seconds;
}
static void print_seconds(FILE *stream, double seconds)
{
long whole = (long)seconds;
long fraction = (long)((seconds - (double)whole) * 100.0);
if (fraction < 0)
fraction = 0;
fprintf(stream, "%ld.%02ld", whole, fraction);
}
static void print_elapsed(FILE *stream, double seconds)
{
long total_seconds = (long)seconds;
long hundredths = (long)((seconds - (double)total_seconds) * 100.0);
if (hundredths < 0)
hundredths = 0;
if (total_seconds >= 3600)
{
long hours = total_seconds / 3600;
long minutes = (total_seconds % 3600) / 60;
long secs = total_seconds % 60;
fprintf(stream, "%ld:%02ld:%02ld", hours, minutes, secs);
}
else
{
long minutes = total_seconds / 60;
long secs = total_seconds % 60;
fprintf(stream, "%ld:%02ld.%02ld", minutes, secs, hundredths);
}
}
static char *join_command(char *const *argv, int argc, int start_index)
{
StringBuilder builder;
builder_init(&builder);
for (int i = start_index; i < argc; ++i)
{
if (i > start_index)
builder_append_char(&builder, ' ');
builder_append_text(&builder, argv[i]);
}
return builder_take(&builder);
}
static bool long_option_argument(const char *arg, const char *name, const char **value)
{
size_t name_length = strlen(name);
if (!starts_with(arg, name))
return false;
if (arg[name_length] == '\0')
{
*value = NULL;
return true;
}
if (arg[name_length] == '=')
{
*value = arg + name_length + 1;
return true;
}
return false;
}
static const char *require_option_argument(const char *option, int argc, char *const *argv, int *index, const char *inline_value)
{
if (inline_value != NULL)
return inline_value;
if (*index + 1 >= argc)
{
fprintf(stderr, "%s: option '%s' requires an argument\n", PROGRAM_NAME, option);
exit(EXIT_CANCELED);
}
++(*index);
return argv[*index];
}
static void parse_options(int argc, char *const *argv, Options *options)
{
memset(options, 0, sizeof(*options));
options->output_mode = OUTPUT_DEFAULT;
options->command_index = argc;
for (int i = 1; i < argc; ++i)
{
const char *arg = argv[i];
const char *value = NULL;
if (strings_equal(arg, "--"))
{
options->command_index = i + 1;
return;
}
if (arg[0] != '-' || arg[1] == '\0')
{
options->command_index = i;
return;
}
if (arg[1] == '-')
{
if (strings_equal(arg, "--help"))
{
options->show_help = true;
return;
}
if (strings_equal(arg, "--version"))
{
options->show_version = true;
return;
}
if (strings_equal(arg, "--append"))
{
options->append = true;
continue;
}
if (strings_equal(arg, "--portability"))
{
options->output_mode = OUTPUT_POSIX;
continue;
}
if (strings_equal(arg, "--quiet"))
{
options->quiet = true;
continue;
}
if (strings_equal(arg, "--verbose"))
{
options->verbose = true;
continue;
}
if (strings_equal(arg, "--old"))
{
options->output_mode = OUTPUT_OLD;
continue;
}
if (long_option_argument(arg, "--format", &value))
{
options->format = require_option_argument("--format", argc, argv, &i, value);
options->output_mode = OUTPUT_CUSTOM;
continue;
}
if (long_option_argument(arg, "--output", &value) ||
long_option_argument(arg, "--output-file", &value))
{
options->output_path = require_option_argument("--output", argc, argv, &i, value);
continue;
}
if (long_option_argument(arg, "--timeout", &value))
{
const char *duration_text = require_option_argument("--timeout", argc, argv, &i, value);
if (!parse_duration(duration_text, &options->timeout_seconds))
{
fprintf(stderr, "%s: invalid timeout duration '%s'\n", PROGRAM_NAME, duration_text);
exit(EXIT_CANCELED);
}
options->timeout_enabled = options->timeout_seconds > 0.0;
continue;
}
fprintf(stderr, "%s: unrecognized option '%s'\n", PROGRAM_NAME, arg);
exit(EXIT_CANCELED);
}
for (size_t j = 1; arg[j] != '\0'; ++j)
{
switch (arg[j])
{
case 'a':
options->append = true;
break;
case 'f':
{
const char *inline_value = arg[j + 1] != '\0' ? arg + j + 1 : NULL;
options->format = require_option_argument("-f", argc, argv, &i, inline_value);
options->output_mode = OUTPUT_CUSTOM;
j = strlen(arg) - 1;
break;
}
case 'o':
{
const char *inline_value = arg[j + 1] != '\0' ? arg + j + 1 : NULL;
options->output_path = require_option_argument("-o", argc, argv, &i, inline_value);
j = strlen(arg) - 1;
break;
}
case 'p':
options->output_mode = OUTPUT_POSIX;
break;
case 'q':
options->quiet = true;
break;
case 't':
{
const char *inline_value = arg[j + 1] != '\0' ? arg + j + 1 : NULL;
const char *duration_text = require_option_argument("-t", argc, argv, &i, inline_value);
if (!parse_duration(duration_text, &options->timeout_seconds))
{
fprintf(stderr, "%s: invalid timeout duration '%s'\n", PROGRAM_NAME, duration_text);
exit(EXIT_CANCELED);
}
options->timeout_enabled = options->timeout_seconds > 0.0;
j = strlen(arg) - 1;
break;
}
case 'v':
options->verbose = true;
break;
case 'V':
options->show_version = true;
return;
default:
fprintf(stderr, "%s: unrecognized option '-%c'\n", PROGRAM_NAME, arg[j]);
exit(EXIT_CANCELED);
}
}
}
options->command_index = argc;
}
static const char *select_format(const Options *options)
{
if (options->verbose)
return VERBOSE_FORMAT;
if (options->output_mode == OUTPUT_CUSTOM)
return options->format;
if (options->output_mode == OUTPUT_POSIX)
return POSIX_FORMAT;
return DEFAULT_FORMAT;
}
static bool using_old_output(const Options *options)
{
return !options->verbose && options->output_mode == OUTPUT_OLD;
}
static FILE *open_output_stream(const Options *options)
{
if (options->output_path == NULL)
return using_old_output(options) ? stdout : stderr;
FILE *stream = fopen(options->output_path, options->append ? "a" : "w");
if (stream == NULL)
{
fprintf(stderr, "%s: cannot open '%s': %s\n",
PROGRAM_NAME,
options->output_path,
strerror(errno));
exit(EXIT_CANCELED);
}
return stream;
}
#ifdef _WIN32
static double filetime_to_seconds(const FILETIME *time)
{
ULARGE_INTEGER value;
value.LowPart = time->dwLowDateTime;
value.HighPart = time->dwHighDateTime;
return (double)value.QuadPart * 1.0e-7;
}
static double monotonic_seconds(void)
{
static LARGE_INTEGER frequency;
static BOOL initialized = FALSE;
LARGE_INTEGER counter;
if (!initialized)
{
QueryPerformanceFrequency(&frequency);
initialized = TRUE;
}
QueryPerformanceCounter(&counter);
return (double)counter.QuadPart / (double)frequency.QuadPart;
}
static void append_quoted_windows_argument(StringBuilder *builder, const char *arg)
{
bool needs_quotes = arg[0] == '\0';
for (const char *p = arg; *p != '\0' && !needs_quotes; ++p)
{
if (*p == ' ' || *p == '\t' || *p == '"')
needs_quotes = true;
}
if (!needs_quotes)
{
builder_append_text(builder, arg);
return;
}
builder_append_char(builder, '"');
size_t backslashes = 0;
for (const char *p = arg; *p != '\0'; ++p)
{
if (*p == '\\')
{
++backslashes;
continue;
}
if (*p == '"')
{
for (size_t i = 0; i < backslashes * 2 + 1; ++i)
builder_append_char(builder, '\\');
builder_append_char(builder, '"');
backslashes = 0;
continue;
}
while (backslashes-- > 0)
builder_append_char(builder, '\\');
backslashes = 0;
builder_append_char(builder, *p);
}
while (backslashes-- > 0)
{
builder_append_char(builder, '\\');
builder_append_char(builder, '\\');
}
builder_append_char(builder, '"');
}
static char *build_windows_command_line(char *const *argv, int argc, int start_index)
{
StringBuilder builder;
builder_init(&builder);
for (int i = start_index; i < argc; ++i)
{
if (i > start_index)
builder_append_char(&builder, ' ');
append_quoted_windows_argument(&builder, argv[i]);
}
return builder_take(&builder);
}
static void print_windows_error(const char *prefix, const char *subject, DWORD error_code)
{
char buffer[512];
DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
DWORD count = FormatMessageA(
flags,
NULL,
error_code,
0,
buffer,
(DWORD)(sizeof(buffer) / sizeof(buffer[0])),
NULL);
if (count == 0)
fprintf(stderr, "%s: %s %s (error %lu)\n", PROGRAM_NAME, prefix, subject, (unsigned long)error_code);
else
fprintf(stderr, "%s: %s %s: %s\n", PROGRAM_NAME, prefix, subject, buffer);
}
static int wait_for_process(HANDLE process, HANDLE job, double timeout_seconds, bool *timed_out)
{
const DWORD slice_ms = 50;
double deadline = monotonic_seconds() + timeout_seconds;
for (;;)
{
DWORD wait_ms = INFINITE;
if (timeout_seconds > 0.0)
{
double remaining = deadline - monotonic_seconds();
if (remaining <= 0.0)
{
*timed_out = true;
if (job != NULL)
TerminateJobObject(job, EXIT_TIMED_OUT);
else
TerminateProcess(process, EXIT_TIMED_OUT);
wait_ms = INFINITE;
}
else if (remaining * 1000.0 < (double)slice_ms)
wait_ms = (DWORD)(remaining * 1000.0);
else
wait_ms = slice_ms;
}
DWORD wait_result = WaitForSingleObject(process, wait_ms);
if (wait_result == WAIT_OBJECT_0)
return 0;
if (wait_result == WAIT_FAILED)
return -1;
if (timeout_seconds > 0.0 && *timed_out)
return 0;
}
}
static int run_command(char *const *argv, int argc, int start_index, const Options *options, Metrics *metrics)
{
STARTUPINFOA startup_info;
PROCESS_INFORMATION process_info;
HANDLE job = NULL;
char *command_line;
FILETIME creation_time, exit_time, kernel_time, user_time;
PROCESS_MEMORY_COUNTERS_EX memory_counters;
IO_COUNTERS io_counters;
SYSTEM_INFO system_info;
DWORD exit_code = 0;
double start_time;
double end_time;
memset(metrics, 0, sizeof(*metrics));
memset(&startup_info, 0, sizeof(startup_info));
memset(&process_info, 0, sizeof(process_info));
memset(&memory_counters, 0, sizeof(memory_counters));
memset(&io_counters, 0, sizeof(io_counters));
startup_info.cb = sizeof(startup_info);
command_line = build_windows_command_line(argv, argc, start_index);
start_time = monotonic_seconds();
if (!CreateProcessA(
NULL,
command_line,
NULL,
NULL,
TRUE,
CREATE_SUSPENDED,
NULL,
NULL,
&startup_info,
&process_info))
{
DWORD error_code = GetLastError();
print_windows_error("cannot run", argv[start_index], error_code);
free(command_line);
return error_code == ERROR_FILE_NOT_FOUND ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
}
job = CreateJobObjectA(NULL, NULL);
if (job != NULL)
{
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits;
memset(&limits, 0, sizeof(limits));
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
SetInformationJobObject(job, JobObjectExtendedLimitInformation, &limits, sizeof(limits));
AssignProcessToJobObject(job, process_info.hProcess);
}
ResumeThread(process_info.hThread);
bool timed_out = false;
if (wait_for_process(process_info.hProcess, job, options->timeout_enabled ? options->timeout_seconds : 0.0, &timed_out) != 0)
{
DWORD error_code = GetLastError();
print_windows_error("cannot wait for", argv[start_index], error_code);
CloseHandle(process_info.hThread);
CloseHandle(process_info.hProcess);
if (job != NULL)
CloseHandle(job);
free(command_line);
return EXIT_FAILURE;
}
end_time = monotonic_seconds();
metrics->elapsed_seconds = end_time - start_time;
metrics->timed_out = timed_out;
metrics->exit_kind = timed_out ? EXIT_KIND_TIMEOUT : EXIT_KIND_NORMAL;
if (!GetExitCodeProcess(process_info.hProcess, &exit_code))
exit_code = EXIT_FAILURE;
metrics->exit_code = (int)exit_code;
metrics->exit_status = timed_out ? EXIT_TIMED_OUT : (int)exit_code;
if (!GetProcessTimes(process_info.hProcess, &creation_time, &exit_time, &kernel_time, &user_time))
{
print_windows_error("cannot read process times for", argv[start_index], GetLastError());
CloseHandle(process_info.hThread);
CloseHandle(process_info.hProcess);
if (job != NULL)
CloseHandle(job);
free(command_line);
return EXIT_FAILURE;
}
metrics->system_seconds = filetime_to_seconds(&kernel_time);
metrics->user_seconds = filetime_to_seconds(&user_time);
memory_counters.cb = sizeof(memory_counters);
if (!GetProcessMemoryInfo(process_info.hProcess, (PROCESS_MEMORY_COUNTERS *)&memory_counters, sizeof(memory_counters)))
{
print_windows_error("cannot read process memory for", argv[start_index], GetLastError());
CloseHandle(process_info.hThread);
CloseHandle(process_info.hProcess);
if (job != NULL)
CloseHandle(job);
free(command_line);
return EXIT_FAILURE;
}
if (!GetProcessIoCounters(process_info.hProcess, &io_counters))
memset(&io_counters, 0, sizeof(io_counters));
GetSystemInfo(&system_info);
metrics->page_size_bytes = (uint64_t)system_info.dwPageSize;
metrics->page_fault_count = (uint64_t)memory_counters.PageFaultCount;
metrics->minor_page_faults = metrics->page_fault_count;
metrics->peak_working_set_kb = (uint64_t)(memory_counters.PeakWorkingSetSize / 1024);
metrics->peak_paged_pool_kb = (uint64_t)(memory_counters.QuotaPeakPagedPoolUsage / 1024);
metrics->peak_nonpaged_pool_kb = (uint64_t)(memory_counters.QuotaPeakNonPagedPoolUsage / 1024);
metrics->peak_pagefile_kb = (uint64_t)(memory_counters.PeakPagefileUsage / 1024);
metrics->max_resident_kb = metrics->peak_working_set_kb;
metrics->avg_resident_kb = (uint64_t)(memory_counters.WorkingSetSize / 1024);
if (metrics->avg_resident_kb == 0)
metrics->avg_resident_kb = metrics->max_resident_kb;
metrics->avg_unshared_data_kb = (uint64_t)(memory_counters.PrivateUsage / 1024);
metrics->avg_stack_kb = 0;
metrics->avg_shared_text_kb = 0;
metrics->avg_total_kb = metrics->avg_unshared_data_kb + metrics->avg_stack_kb + metrics->avg_shared_text_kb;
metrics->file_inputs = (uint64_t)io_counters.ReadOperationCount;
metrics->file_outputs = (uint64_t)io_counters.WriteOperationCount;
CloseHandle(process_info.hThread);
CloseHandle(process_info.hProcess);
if (job != NULL)
CloseHandle(job);
free(command_line);
return metrics->exit_status;
}
#else
static double monotonic_seconds(void)
{
struct timespec time_now;
clock_gettime(CLOCK_MONOTONIC, &time_now);
return (double)time_now.tv_sec + (double)time_now.tv_nsec / 1000000000.0;
}
static const char *signal_name_for_number(int signal_number)
{
const char *name = strsignal(signal_number);
return name == NULL ? "" : name;
}
static int wait_with_timeout(pid_t pid, struct rusage *usage_data, int *wait_status, double timeout_seconds, bool *timed_out)
{
double deadline = monotonic_seconds() + timeout_seconds;
const struct timespec sleep_interval = { 0, 50000000L };
for (;;)
{
pid_t result = wait4(pid, wait_status, timeout_seconds > 0.0 ? WNOHANG : 0, usage_data);
if (result == pid)
return 0;
if (result < 0)
return -1;
if (timeout_seconds <= 0.0)
return -1;
if (monotonic_seconds() >= deadline)
{
*timed_out = true;
kill(-pid, SIGKILL);
if (wait4(pid, wait_status, 0, usage_data) != pid)
return -1;
return 0;
}
nanosleep(&sleep_interval, NULL);
}
}
static int run_command(char *const *argv, int argc, int start_index, const Options *options, Metrics *metrics)
{
pid_t pid;
struct rusage usage_data;
struct sigaction ignore_action;
struct sigaction previous_int;
struct sigaction previous_quit;
int wait_status = 0;
double start_time;
double end_time;
long page_size;
(void)argc;
memset(metrics, 0, sizeof(*metrics));
memset(&usage_data, 0, sizeof(usage_data));
memset(&ignore_action, 0, sizeof(ignore_action));
memset(&previous_int, 0, sizeof(previous_int));
memset(&previous_quit, 0, sizeof(previous_quit));
ignore_action.sa_handler = SIG_IGN;
start_time = monotonic_seconds();
pid = fork();
if (pid < 0)
{
fprintf(stderr, "%s: cannot fork: %s\n", PROGRAM_NAME, strerror(errno));
return EXIT_CANCELED;
}
if (pid == 0)
{
setpgid(0, 0);
execvp(argv[start_index], &argv[start_index]);
fprintf(stderr, "%s: cannot run %s: %s\n", PROGRAM_NAME, argv[start_index], strerror(errno));
_exit(errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
}
setpgid(pid, pid);
sigaction(SIGINT, &ignore_action, &previous_int);
sigaction(SIGQUIT, &ignore_action, &previous_quit);
bool timed_out = false;
if (wait_with_timeout(pid, &usage_data, &wait_status, options->timeout_enabled ? options->timeout_seconds : 0.0, &timed_out) != 0)
{
fprintf(stderr, "%s: error waiting for child process: %s\n", PROGRAM_NAME, strerror(errno));
sigaction(SIGINT, &previous_int, NULL);
sigaction(SIGQUIT, &previous_quit, NULL);
return EXIT_FAILURE;
}
sigaction(SIGINT, &previous_int, NULL);
sigaction(SIGQUIT, &previous_quit, NULL);
end_time = monotonic_seconds();
metrics->elapsed_seconds = end_time - start_time;
metrics->timed_out = timed_out;
metrics->user_seconds = (double)usage_data.ru_utime.tv_sec + (double)usage_data.ru_utime.tv_usec / 1000000.0;
metrics->system_seconds = (double)usage_data.ru_stime.tv_sec + (double)usage_data.ru_stime.tv_usec / 1000000.0;
metrics->major_page_faults = (uint64_t)usage_data.ru_majflt;
metrics->minor_page_faults = (uint64_t)usage_data.ru_minflt;
metrics->page_fault_count = metrics->major_page_faults + metrics->minor_page_faults;
metrics->file_inputs = (uint64_t)usage_data.ru_inblock;