-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
472 lines (381 loc) · 14.5 KB
/
main.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
#include "graphics.h" // for setScrollArea, gotoStatLine, clea...
#include "stats.h" // for printStats, advanceSpinner
#include "timer.h" // for tick_create, MSEC_TO_NSEC
#include "util.h" // for showError, proc_runtime, printChar
#include <ctype.h> // for isprint
#include <pthread.h> // for pthread_create, pthread_join, pth...
#include <semaphore.h> // for sem_post, sem_wait, sem_destroy
#include <signal.h> // for sigaction, sigemptyset, sa_handler
#include <stdbool.h> // for false, true, bool
#include <stdio.h> // for fflush, NULL, printf, fclose, fputs
#include <stdlib.h> // for EXIT_FAILURE, calloc, exit, WEXIT...
#include <stdnoreturn.h> // for noreturn
#include <string.h> // for memset, strsignal
#include <sys/ioctl.h> // for winsize, ioctl, TIOCGWINSZ
#include <sys/time.h> // for CLOCK_MONOTONIC, CLOCK_REALTIME
#include <sys/wait.h> // for wait
#include <termios.h> // for tcsetattr, tcgetattr
#include <time.h> // for clock_gettime, timespec
#include <unistd.h> // for close, STDIN_FILENO, dup2, read
#include "main.h"
#define DEBUG_FILE "debug.log"
static window_t procWindow;
static options_t invocOptions;
static sem_t outputMutex;
static sem_t redrawMutex;
static const char* childProcessName;
static unsigned char* inputBuffer;
static FILE* outputFile;
static FILE* debugFile;
static struct termios termRestore;
static void tickCallback(sigval_t sv)
{
(void)sv;
sem_wait(&outputMutex);
unsetTextFormat();
printStats(false, false, &procWindow, &invocOptions);
setTextFormat();
sem_post(&outputMutex);
}
static void initConsole(void)
{
struct termios term;
if (!invocOptions.verbose)
{
inputBuffer = (unsigned char*)calloc(sizeof(unsigned char), 2048);
if (!inputBuffer)
showError(EXIT_FAILURE, false, "Input buffer calloc failed\n");
}
sem_wait(&outputMutex);
tcgetattr(STDIN_FILENO, &term);
tcgetattr(STDIN_FILENO, &termRestore);
term.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &term);
fputs("\n\e[1A", stdout); // Set the cursor to our starting position
if (invocOptions.useScrollingRegion)
setScrollArea(procWindow.termSize.ws_row - 1);
sem_post(&outputMutex);
}
static void* readLoop(void* arg)
{
unsigned char inputChar;
bool newLine = false;
int procPipe = *(int*)arg;
while (read(procPipe, &inputChar, 1) > 0)
{
if (outputFile)
fwrite(&inputChar, sizeof(inputChar), 1, outputFile);
sem_wait(&outputMutex);
if (invocOptions.verbose)
{
if (inputChar == '\t')
{
tabToSpaces(inputBuffer, &invocOptions, &procWindow);
}
else if (inputChar == '\n')
{
unsetTextFormat();
advanceSpinner(&procWindow, &invocOptions);
if (invocOptions.useScrollingRegion)
putchar(inputChar);
else
printStats(true, true, &procWindow, &invocOptions);
procWindow.numCharacters = 0;
setTextFormat();
}
else if (isprint(inputChar) || (inputChar == '\e') || (inputChar == '\b'))
{
processChar(inputChar, inputBuffer, &invocOptions, &procWindow);
}
}
else
{
if ((inputChar >= '\n') && (inputChar <= '\r'))
{
if (!newLine)
{
advanceSpinner(&procWindow, &invocOptions);
newLine = true;
}
}
else
{
if (newLine)
{
memset(inputBuffer, 0, 2048);
unsetTextFormat();
printStats(false, true, &procWindow, &invocOptions);
returnToStartLine(true, &procWindow);
setTextFormat();
procWindow.numCharacters = 0;
newLine = false;
}
if (inputChar == '\t')
tabToSpaces(inputBuffer, &invocOptions, &procWindow);
else if (isprint(inputChar) || (inputChar == '\e') || (inputChar == '\b'))
processChar(inputChar, inputBuffer, &invocOptions, &procWindow);
}
}
if (invocOptions.debug)
fprintf(debugFile, "%.03f: %c (%u)\n", proc_runtime(&procWindow), inputChar,
inputChar);
fflush(stdout);
sem_post(&outputMutex);
}
return NULL;
}
static void* inputLoop(void* arg)
{
unsigned char inputChar;
int childStdIn = *(int*)arg;
while (read(STDIN_FILENO, &inputChar, 1) > 0)
{
if (outputFile)
fwrite(&inputChar, sizeof(inputChar), 1, outputFile);
sem_wait(&outputMutex);
if (isprint(inputChar))
{
processChar(inputChar, inputBuffer, &invocOptions, &procWindow);
fflush(stdout);
}
if ((write(childStdIn, &inputChar, 1) < 0) && (invocOptions.debug))
fprintf(debugFile, "stdin passthrough failed (fd %d): %.03f: %c (%u)\n",
childStdIn, proc_runtime(&procWindow), inputChar, inputChar);
else if (invocOptions.debug)
fprintf(debugFile, "stdin: %.03f: %c (%u)\n", proc_runtime(&procWindow),
inputChar, inputChar);
sem_post(&outputMutex);
}
return NULL;
}
static void* redrawThread(void* arg)
{
struct timespec currentTime;
struct timespec timeoutTime;
struct timespec debounceTime = {
.tv_sec = 0,
.tv_nsec = MSEC_TO_NSEC(300),
};
int retval;
(void)(arg);
while (1)
{
sem_wait(&redrawMutex);
sem_wait(&outputMutex);
if (invocOptions.verbose)
tidyStats(&procWindow);
else
clearScreen(&procWindow);
fflush(stdout);
debounce:
clock_gettime(CLOCK_REALTIME, ¤tTime);
timespecadd(¤tTime, &debounceTime, &timeoutTime);
retval = sem_timedwait(&redrawMutex, &timeoutTime);
// If we got the sem succesfully, that means the sigwinch interrupt
// fired, so go and wait again.
if (retval == 0)
goto debounce;
printStats(false, true, &procWindow, &invocOptions);
if ((!invocOptions.verbose) && (inputBuffer))
{
fputs((const char*)inputBuffer, stdout);
fflush(stdout);
}
sem_post(&outputMutex);
}
return NULL;
}
static void sigwinchHandler(int sigNum)
{
(void)sigNum;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &procWindow.termSize);
sem_post(&redrawMutex);
}
static noreturn void sigintHandler(int sigNum)
{
(void)sigNum;
if (invocOptions.debug)
fclose(debugFile);
if (outputFile)
fclose(outputFile);
tidyStats(&procWindow);
unsetTextFormat();
printf("\n(%s) %s (signal %d) after %.03fs\n", childProcessName, strsignal(sigNum),
sigNum, proc_runtime(&procWindow));
if (procWindow.alternateBuffer)
fputs("\e[?1049l", stdout); // Switch to normal screen buffer
if (invocOptions.useScrollingRegion)
setScrollArea(procWindow.termSize.ws_row);
fflush(stdout);
tcsetattr(STDIN_FILENO, TCSANOW, &termRestore);
exit(EXIT_SUCCESS);
}
static void sigtstpHandler(int sigNum)
{
sigset_t tstpMask, prevMask;
struct sigaction stpCatch;
(void)sigNum;
tidyStats(&procWindow);
unsetTextFormat();
if (procWindow.alternateBuffer)
fputs("\e[?1049l", stdout); // Switch to normal screen buffer
if (invocOptions.useScrollingRegion)
setScrollArea(procWindow.termSize.ws_row);
fflush(stdout);
tcsetattr(STDIN_FILENO, TCSANOW, &termRestore);
// Revert sigtstp hangler to default (i.e. the terminal)
if (signal(SIGTSTP, SIG_DFL) == SIG_ERR)
showError(EXIT_FAILURE, false, "Failed to set default sigtstp\n");
// Generate a further SIGTSTP to trigger the default terminal behaviour
raise(SIGTSTP);
// Unblock SIGTSTP, the pending SIGTSTP immediately suspends the program
// cppcheck-suppress unreachableCode
sigemptyset(&tstpMask);
sigaddset(&tstpMask, SIGTSTP);
if (sigprocmask(SIG_UNBLOCK, &tstpMask, &prevMask) == -1)
showError(EXIT_FAILURE, false, "Failed to unblock SIGTSTP\n");
// Execution resumes here after SIGCONT, re-apply previous signal mask
if (sigprocmask(SIG_SETMASK, &prevMask, NULL) == -1)
showError(EXIT_FAILURE, false, "Failed to reapply previous signal mask\n");
// Re-configure the signal handler
sigemptyset(&stpCatch.sa_mask);
stpCatch.sa_flags = SA_RESTART;
stpCatch.sa_handler = sigtstpHandler;
if (sigaction(SIGTSTP, &stpCatch, NULL) < 0)
showError(EXIT_FAILURE, false, "Failed sigaction for SIGTSTP\n");
}
static void setupInterupts(void)
{
struct sigaction intCatch;
struct sigaction tstpCatch;
struct sigaction winchCatch;
sigemptyset(&intCatch.sa_mask);
intCatch.sa_flags = 0;
intCatch.sa_handler = sigintHandler;
if (sigaction(SIGINT, &intCatch, NULL) < 0)
showError(EXIT_FAILURE, false, "sigaction for SIGINT failed\n");
if (sigaction(SIGTERM, &intCatch, NULL) < 0)
showError(EXIT_FAILURE, false, "sigaction for SIGTERM failed\n");
if (sigaction(SIGQUIT, &intCatch, NULL) < 0)
showError(EXIT_FAILURE, false, "sigaction for SIGQUIT failed\n");
sigemptyset(&tstpCatch.sa_mask);
tstpCatch.sa_flags = SA_RESTART;
tstpCatch.sa_handler = sigtstpHandler;
if (sigaction(SIGTSTP, &tstpCatch, NULL) < 0)
showError(EXIT_FAILURE, false, "sigaction for SIGTSTP failed\n");
sigemptyset(&winchCatch.sa_mask);
winchCatch.sa_flags = SA_RESTART;
winchCatch.sa_handler = sigwinchHandler;
if (sigaction(SIGWINCH, &winchCatch, NULL) < 0)
showError(EXIT_FAILURE, false, "sigaction for SIGWINCH failed\n");
}
noreturn static int runCommand(int outputPipe[2], int inputPipe[2],
const char** commandLine)
{
const char* command;
int status_code;
dup2(outputPipe[1], STDERR_FILENO);
dup2(outputPipe[1], STDOUT_FILENO);
dup2(inputPipe[0], STDIN_FILENO);
close(outputPipe[0]);
close(outputPipe[1]);
close(inputPipe[0]);
close(inputPipe[1]);
command = commandLine[0];
status_code = execvp(command, (char* const*)commandLine);
showError(EXIT_FAILURE, false, "cannot run %s, execvp returned %d\n", command,
status_code);
/* does not return */
}
static void readOutput(int outputPipe[2], int inputPipe[2])
{
pthread_t threadId, readThread, inputThread;
int exitStatus;
close(outputPipe[1]); // Close write end of fd, only need read
close(inputPipe[0]); // Close read end of fd, only need write
setupInterupts();
initConsole();
if (pthread_create(&readThread, NULL, &readLoop, &outputPipe[0]) != 0)
showError(EXIT_FAILURE, false, "pthread_create failed\n");
if (pthread_create(&threadId, NULL, &redrawThread, NULL) != 0)
showError(EXIT_FAILURE, false, "pthread_create failed\n");
if (pthread_create(&inputThread, NULL, &inputLoop, &inputPipe[1]) != 0)
showError(EXIT_FAILURE, false, "pthread_create failed\n");
tick_create(tickCallback, 1U, 0U, false);
// CPU usage needs to be taken over a time interval
tick_create(tickCallback, 0U, MSEC_TO_NSEC(50U), true);
wait(&exitStatus);
pthread_join(readThread, NULL); // Wait for everything to complete
if (procWindow.alternateBuffer)
fputs("\e[?1049l", stdout); // Switch to normal screen buffer
unsetTextFormat();
gotoStatLine(&procWindow);
if (invocOptions.useScrollingRegion)
setScrollArea(procWindow.termSize.ws_row);
tcsetattr(STDIN_FILENO, TCSANOW, &termRestore);
if (WIFSTOPPED(exitStatus))
printf("(%s) stopped by signal %d in %.03fs\n", childProcessName,
WSTOPSIG(exitStatus), proc_runtime(&procWindow));
else if (WIFSIGNALED(exitStatus))
printf("(%s) terminated by signal %d in %.03fs\n", childProcessName,
WTERMSIG(exitStatus), proc_runtime(&procWindow));
else if (WIFEXITED(exitStatus) && WEXITSTATUS(exitStatus))
printf("(%s) exited with non-zero status %d in %.03fs\n", childProcessName,
WEXITSTATUS(exitStatus), proc_runtime(&procWindow));
else
printf("(%s) finished in %.03fs\n", childProcessName, proc_runtime(&procWindow));
}
static void initDebugFile(const char* program_name)
{
time_t rawtime;
char time_string[32]; // Should be ~18 characters
char debug_filename[128]; // Should be plenty for a filename, excess will be
// truncated
time(&rawtime);
strftime(time_string, sizeof(time_string), "%d.%m.%Y-%H.%M.%S", localtime(&rawtime));
snprintf(debug_filename, sizeof(debug_filename), "%s_%s.log", program_name,
time_string);
debugFile = fopen(debug_filename, "w");
if (!debugFile)
showError(EXIT_FAILURE, false, "debug file creation failed\n");
}
int main(int argc, char** argv)
{
const char** commandLine;
int outputPipe[2];
int inputPipe[2];
pid_t pid;
if (pipe(outputPipe) != 0)
showError(EXIT_FAILURE, false, "pipe failed\n");
if (pipe(inputPipe) != 0)
showError(EXIT_FAILURE, false, "pipe failed\n");
if (sem_init(&outputMutex, false, 1) != 0)
showError(EXIT_FAILURE, false, "sem_init failed\n");
if (sem_init(&redrawMutex, false, 0) != 0)
showError(EXIT_FAILURE, false, "sem_init failed\n");
commandLine = getArgs(argc, argv, &outputFile, &invocOptions);
childProcessName = commandLine[0];
if (invocOptions.debug)
initDebugFile(childProcessName);
ioctl(0, TIOCGWINSZ, &procWindow.termSize);
clock_gettime(CLOCK_MONOTONIC, &procWindow.procStartTime);
pid = fork();
if (pid < 0)
showError(EXIT_FAILURE, false, "fork failed\n");
else if (pid == 0)
runCommand(outputPipe, inputPipe, commandLine);
else
readOutput(outputPipe, inputPipe);
if (procWindow.alternateBuffer)
fputs("\e[?1049l", stdout); // Switch to normal screen buffer
if (invocOptions.useScrollingRegion)
setScrollArea(procWindow.termSize.ws_row);
fflush(stdout);
sem_destroy(&outputMutex);
sem_destroy(&redrawMutex);
if (invocOptions.debug)
fclose(debugFile);
if (outputFile)
fclose(outputFile);
return 0;
}