Improved error checking of standard I/O streams.
[tee-win32.git] / tee.c
blob7aba2ea4b56d4a48d9948717a958d4b9a6ab4f9f
1 /*
2 * tee for Windows
3 * Copyright (c) 2023 "dEajL3kA" <Cumpoing79@web.de>
5 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
6 * associated documentation files (the "Software"), to deal in the Software without restriction,
7 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
8 * sub license, and/or sell copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions: The above copyright notice and this
10 * permission notice shall be included in all copies or substantial portions of the Software.
12 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
13 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
14 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
16 * OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
18 #define WIN32_LEAN_AND_MEAN 1
19 #include <Windows.h>
20 #include <ShellAPI.h>
21 #include <intrin.h>
22 #include <stdarg.h>
23 #include "include/cpu.h"
24 #include "include/version.h"
26 #pragma intrinsic(_InterlockedCompareExchange, _InterlockedDecrement)
28 #define BUFF_SIZE (PROCESSOR_BITNESS * 128U)
29 #define BUFFERS 3U
30 #define MAX_THREADS MAXIMUM_WAIT_OBJECTS
32 // --------------------------------------------------------------------------
33 // Assertions
34 // --------------------------------------------------------------------------
36 #ifndef NDEBUG
37 #define ASSERT(CONDIATION, HANDLE_OUT, MESSAGE) do { \
38 static const wchar_t *const _message = L"[tee] Assertion Failed: " MESSAGE L"\n"; \
39 if (!(CONDIATION)) { \
40 write_text((HANDLE_OUT), _message); \
41 FatalExit(-1); \
42 } \
43 } while(0)
44 #else
45 #define ASSERT(CONDIATION, HANDLE_OUT, MESSAGE) ((void)0)
46 #endif
48 // --------------------------------------------------------------------------
49 // Utilities
50 // --------------------------------------------------------------------------
52 static wchar_t to_lower(const wchar_t c)
54 return ((c >= L'A') && (c <= L'Z')) ? (L'a' + (c - L'A')) : c;
57 static BOOL is_terminal(const HANDLE handle)
59 DWORD mode;
60 return GetConsoleMode(handle, &mode);
63 static DWORD count_handles(const HANDLE *const array, const size_t maximum)
65 DWORD counter;
66 for (counter = 0U; counter < maximum; ++counter)
68 if (!array[counter])
70 break;
74 return counter;
77 static const wchar_t *get_filename(const wchar_t *filePath)
79 for (const wchar_t *ptr = filePath; *ptr != L'\0'; ++ptr)
81 if ((*ptr == L'\\') || (*ptr == L'/'))
83 filePath = ptr + 1U;
87 return filePath;
90 static BOOL is_null_device(const wchar_t *filePath)
92 filePath = get_filename(filePath);
93 if ((to_lower(filePath[0U]) == L'n') && (to_lower(filePath[1U]) == L'u') && (to_lower(filePath[2U]) == L'l'))
95 return ((filePath[3U] == L'\0') || (filePath[3U] == L'.'));
98 return FALSE;
101 static wchar_t *format_string(const wchar_t *const format, ...)
103 wchar_t* buffer = NULL;
104 va_list ap;
106 va_start(ap, format);
107 const DWORD result = FormatMessageW(FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ALLOCATE_BUFFER, format, 0U, 0U, (LPWSTR)&buffer, 1U, &ap);
108 va_end(ap);
110 return result ? buffer : NULL;
113 static wchar_t *concat_va(const wchar_t *const first, ...)
115 const wchar_t *ptr;
116 va_list ap;
118 va_start(ap, first);
119 size_t len = 0U;
120 for (ptr = first; ptr != NULL; ptr = va_arg(ap, const wchar_t*))
122 len = lstrlenW(ptr);
124 va_end(ap);
126 wchar_t *const buffer = (wchar_t*)LocalAlloc(LPTR, sizeof(wchar_t) * (len + 1U));
127 if (buffer)
129 va_start(ap, first);
130 for (ptr = first; ptr != NULL; ptr = va_arg(ap, const wchar_t*))
132 lstrcatW(buffer, ptr);
134 va_end(ap);
137 return buffer;
140 #define CONCAT(...) concat_va(__VA_ARGS__, NULL)
142 #define VALID_HANDLE(HANDLE) (((HANDLE) != NULL) && ((HANDLE) != INVALID_HANDLE_VALUE))
144 #define FILL_ARRAY(ARRAY, VALUE) do \
146 for (size_t _index = 0U; _index < ARRAYSIZE(ARRAY); ++_index) \
148 ARRAY[_index] = (VALUE); \
151 while (0)
153 #define CLOSE_HANDLE(HANDLE) do \
155 if (VALID_HANDLE(HANDLE)) \
157 CloseHandle((HANDLE)); \
158 (HANDLE) = NULL; \
161 while (0)
163 // --------------------------------------------------------------------------
164 // Console CTRL+C handler
165 // --------------------------------------------------------------------------
167 static volatile BOOL g_stop = FALSE;
169 static BOOL WINAPI console_handler(const DWORD ctrlType)
171 switch (ctrlType)
173 case CTRL_C_EVENT:
174 case CTRL_BREAK_EVENT:
175 case CTRL_CLOSE_EVENT:
176 g_stop = TRUE;
177 return TRUE;
178 default:
179 return FALSE;
183 // --------------------------------------------------------------------------
184 // Text output
185 // --------------------------------------------------------------------------
187 static char *utf16_to_utf8(const wchar_t *const input)
189 const int buff_size = WideCharToMultiByte(CP_UTF8, 0, input, -1, NULL, 0, NULL, NULL);
190 if (buff_size > 0)
192 char *const buffer = (char*)LocalAlloc(LPTR, buff_size);
193 if (buffer)
195 const int result = WideCharToMultiByte(CP_UTF8, 0, input, -1, buffer, buff_size, NULL, NULL);
196 if ((result > 0) && (result <= buff_size))
198 return buffer;
200 LocalFree(buffer);
204 return NULL;
207 static BOOL write_text(const HANDLE handle, const wchar_t *const text)
209 BOOL result = FALSE;
210 DWORD written;
212 if (GetConsoleMode(handle, &written))
214 result = WriteConsoleW(handle, text, lstrlenW(text), &written, NULL);
216 else
218 char *const utf8_text = utf16_to_utf8(text);
219 if (utf8_text)
221 result = WriteFile(handle, utf8_text, lstrlenA(utf8_text), &written, NULL);
222 LocalFree(utf8_text);
226 return result;
229 #define WRITE_TEXT(...) do \
231 wchar_t* const _message = CONCAT(__VA_ARGS__); \
232 if (_message) \
234 write_text(hStdErr, _message); \
235 LocalFree(_message); \
238 while (0)
240 // --------------------------------------------------------------------------
241 // Writer thread
242 // --------------------------------------------------------------------------
244 #define INCREMENT_INDEX(INDEX, FLAG) do { if (++(INDEX) >= BUFFERS) { (INDEX) = 0U; if (++(FLAG) > 2U) { (FLAG) = 1U; } } } while (0)
246 typedef struct _thread
248 HANDLE hOutput, hError;
249 BOOL flush;
251 thread_t;
253 static thread_t g_threadData[MAX_THREADS];
254 static BYTE g_buffer[BUFFERS][BUFF_SIZE], g_state[BUFF_SIZE] = { 0U, 0U, 0U };
255 static DWORD g_bytesTotal[BUFF_SIZE] = { 0U, 0U, 0U };
256 static volatile LONG g_pending[BUFF_SIZE] = { 0L, 0L, 0L };
257 static SRWLOCK g_rwLocks[BUFFERS];
258 static CONDITION_VARIABLE g_condIsReady[BUFFERS], g_condAllDone[BUFFERS];
260 static DWORD WINAPI writer_thread_start_routine(const LPVOID lpThreadParameter)
262 DWORD bytesWritten = 0U, myIndex = 0U, pendingThreads = 0U;
263 BYTE myFlag = 1U;
264 BOOL writeErrors = FALSE;
265 const thread_t *const param = &g_threadData[(DWORD_PTR)lpThreadParameter];
267 for (;;)
269 ASSERT(myIndex < BUFFERS, param->hError, L"Current buffer index is out of range!");
271 AcquireSRWLockShared(&g_rwLocks[myIndex]);
273 while (!(g_state[myIndex] & myFlag))
275 if (!SleepConditionVariableSRW(&g_condIsReady[myIndex], &g_rwLocks[myIndex], INFINITE, CONDITION_VARIABLE_LOCKMODE_SHARED))
277 ReleaseSRWLockShared(&g_rwLocks[myIndex]);
278 write_text(param->hError, L"[tee] System error: Failed to sleep on the conditional variable!\n");
279 return 1U;
283 if (g_state[myIndex] > 2U)
285 ReleaseSRWLockShared(&g_rwLocks[myIndex]);
286 if (writeErrors)
288 write_text(param->hError, L"[tee] Error: Not all data could be written!\n");
290 return 0U;
293 for (DWORD offset = 0U; offset < g_bytesTotal[myIndex]; offset += bytesWritten)
295 const BOOL result = WriteFile(param->hOutput, g_buffer[myIndex] + offset, g_bytesTotal[myIndex] - offset, &bytesWritten, NULL);
296 if ((!result) || (!bytesWritten))
298 writeErrors = TRUE;
299 break;
303 ASSERT(g_pending > 0U, param->hError, L"Pending threads counter must be a positive value!");
305 pendingThreads = _InterlockedDecrement(&g_pending[myIndex]);
307 ReleaseSRWLockShared(&g_rwLocks[myIndex]);
309 if (!pendingThreads)
311 WakeConditionVariable(&g_condAllDone[myIndex]);
314 INCREMENT_INDEX(myIndex, myFlag);
316 if (param->flush)
318 FlushFileBuffers(param->hOutput);
323 // --------------------------------------------------------------------------
324 // Options
325 // --------------------------------------------------------------------------
327 typedef struct
329 BOOL append, delay, flush, help, ignore, version;
331 options_t;
333 #define PARSE_OPTION(SHRT, NAME) do \
335 if ((lc == L##SHRT) || (name && (lstrcmpiW(name, L#NAME) == 0))) \
337 options->NAME = TRUE; \
338 return TRUE; \
341 while (0)
343 static BOOL parse_option(options_t *const options, const wchar_t c, const wchar_t *const name)
345 const wchar_t lc = to_lower(c);
347 PARSE_OPTION('a', append);
348 PARSE_OPTION('d', delay);
349 PARSE_OPTION('f', flush);
350 PARSE_OPTION('h', help);
351 PARSE_OPTION('i', ignore);
352 PARSE_OPTION('v', version);
354 return FALSE;
357 static BOOL parse_argument(options_t *const options, const wchar_t *const argument)
359 if ((argument[0U] != L'-') || (argument[1U] == L'\0'))
361 return FALSE;
364 if (argument[1U] == L'-')
366 return (argument[2U] != L'\0') && parse_option(options, L'\0', argument + 2U);
368 else
370 for (const wchar_t* ptr = argument + 1U; *ptr != L'\0'; ++ptr)
372 if (!parse_option(options, *ptr, NULL))
374 return FALSE;
377 return TRUE;
381 // --------------------------------------------------------------------------
382 // MAIN
383 // --------------------------------------------------------------------------
385 int wmain(const int argc, const wchar_t *const argv[])
387 HANDLE hThreads[MAX_THREADS], hMyFiles[MAX_THREADS - 1U];
388 int exitCode = 1, argOff = 1;
389 DWORD fileCount = 0U, threadCount = 0U, myIndex = 0U;
390 options_t options;
392 /* Initialize local variables */
393 FILL_ARRAY(hMyFiles, INVALID_HANDLE_VALUE);
394 FILL_ARRAY(hThreads, NULL);
395 SecureZeroMemory(&options, sizeof(options_t));
397 /* Initialize standard streams */
398 const HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE), hStdOut = GetStdHandle(STD_OUTPUT_HANDLE), hStdErr = GetStdHandle(STD_ERROR_HANDLE);
399 if (!(VALID_HANDLE(hStdIn) && VALID_HANDLE(hStdOut) && VALID_HANDLE(hStdErr)))
401 if (VALID_HANDLE(hStdErr))
403 write_text(hStdErr, L"[tee] System error: Failed to initialize standard I/O handles!\n");
405 return -1;
408 /* Initialize read/write locks and condition variables */
409 for (DWORD index = 0; index < BUFFERS; ++index)
411 InitializeSRWLock(&g_rwLocks[index]);
412 InitializeConditionVariable(&g_condIsReady[index]);
413 InitializeConditionVariable(&g_condAllDone[index]);
416 /* Set up CRTL+C handler */
417 SetConsoleCtrlHandler(console_handler, TRUE);
419 /* Parse command-line options */
420 while ((argOff < argc) && (argv[argOff][0U] == L'-') && (argv[argOff][1U] != L'\0'))
422 const wchar_t *const argValue= argv[argOff++];
423 if ((argValue[1U] == L'-') && (argValue[2U] == L'\0'))
425 break; /*stop!*/
427 else if (!parse_argument(&options, argValue))
429 WRITE_TEXT(L"[tee] Error: Invalid option \"", argValue, L"\" encountered!\n");
430 return 1;
434 /* Print manual page */
435 if (options.help || options.version)
437 wchar_t *const versionString = format_string(L"tee for Windows v%1!u!.%2!u!.%3!u! [%4!s!] [%5!s!]\n", APP_VERSION_MAJOR, APP_VERSION_MINOR, APP_VERSION_PATCH, PROCESSOR_ARCHITECTURE, TEXT(__DATE__));
438 write_text(hStdErr, versionString ? versionString : L"tee for Windows\n");
439 if (options.help)
441 write_text(hStdErr, L"\n"
442 L"Copy standard input to output file(s), and also to standard output.\n\n"
443 L"Usage:\n"
444 L" gizmo.exe [...] | tee.exe [options] <file_1> ... <file_n>\n\n"
445 L"Options:\n"
446 L" -a --append Append to the existing file, instead of truncating\n"
447 L" -f --flush Flush output file after each write operation\n"
448 L" -i --ignore Ignore the interrupt signal (SIGINT), e.g. CTRL+C\n"
449 L" -d --delay Add a small delay after each read operation\n\n");
451 if (versionString)
453 LocalFree(versionString);
455 return 0;
458 /* Check output file name */
459 if (argOff >= argc)
461 write_text(hStdErr, L"[tee] Error: Output file name is missing. Type \"tee --help\" for details!\n");
462 return 1;
465 /* Determine input type */
466 const DWORD inputType = GetFileType(hStdIn);
467 if (inputType == FILE_TYPE_UNKNOWN)
469 if (GetLastError() != NO_ERROR)
471 write_text(hStdErr, L"[tee] System error: Failed to initialize standard input stream!\n");
472 return -1;
476 /* Validate output stream */
477 if (GetFileType(hStdOut) == FILE_TYPE_UNKNOWN)
479 if (GetLastError() != NO_ERROR)
481 write_text(hStdErr, L"[tee] System error: Failed to initialize standard output stream!\n");
482 return -1;
486 /* Open output file(s) */
487 while ((argOff < argc) && (fileCount < ARRAYSIZE(hMyFiles)))
489 const wchar_t* const fileName = argv[argOff++];
490 if (!is_null_device(fileName))
492 const HANDLE hFile = CreateFileW(fileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, options.append ? OPEN_ALWAYS : CREATE_ALWAYS, 0U, NULL);
493 if ((hMyFiles[fileCount++] = hFile) == INVALID_HANDLE_VALUE)
495 WRITE_TEXT(L"[tee] Error: Failed to open the output file \"", fileName, L"\" for writing!\n");
496 goto cleanup;
498 else if (options.append)
500 LARGE_INTEGER offset = { .QuadPart = 0LL };
501 if (!SetFilePointerEx(hFile, offset, NULL, FILE_END))
503 write_text(hStdErr, L"[tee] Error: Failed to move the file pointer to the end of the file!\n");
504 goto cleanup;
510 /* Check output file name */
511 if (argOff < argc)
513 write_text(hStdErr, L"[tee] Warning: Too many input files, ignoring excess files!\n");
516 /* Determine number of outputs */
517 const DWORD outputCount = fileCount + 1U;
519 /* Start threads */
520 for (DWORD threadId = 0; threadId < outputCount; ++threadId)
522 g_threadData[threadId].hOutput = (threadId > 0U) ? hMyFiles[threadId - 1U] : hStdOut;
523 g_threadData[threadId].hError = hStdErr;
524 g_threadData[threadId].flush = options.flush && (!is_terminal(g_threadData[threadId].hOutput));
525 if (!(hThreads[threadCount++] = CreateThread(NULL, 0U, writer_thread_start_routine, (LPVOID)(DWORD_PTR)threadId, 0U, NULL)))
527 write_text(hStdErr, L"[tee] System error: Failed to create thread!\n");
528 goto cleanup;
532 /* Initialize the index */
533 BYTE myFlag = 1U;
535 /* Process all input from STDIN stream */
538 ASSERT(myIndex < BUFFERS, hStdErr, L"Current buffer index is out of range!");
540 AcquireSRWLockExclusive(&g_rwLocks[myIndex]);
542 while (_InterlockedCompareExchange(&g_pending[myIndex], threadCount, 0L))
544 if (!SleepConditionVariableSRW(&g_condAllDone[myIndex], &g_rwLocks[myIndex], INFINITE, 0U))
546 ReleaseSRWLockExclusive(&g_rwLocks[myIndex]);
547 write_text(hStdErr, L"[tee] System error: Failed to sleep on the conditional variable!\n");
548 goto cleanup;
552 if (!ReadFile(hStdIn, g_buffer[myIndex], BUFF_SIZE, &g_bytesTotal[myIndex], NULL))
554 const DWORD error = GetLastError();
555 ReleaseSRWLockExclusive(&g_rwLocks[myIndex]);
556 if (error != ERROR_BROKEN_PIPE)
558 write_text(hStdErr, L"[tee] Error: Failed to read input data!\n");
559 goto cleanup;
561 break;
564 if (!g_bytesTotal[myIndex])
566 ReleaseSRWLockExclusive(&g_rwLocks[myIndex]);
567 if (inputType == FILE_TYPE_PIPE)
569 continue; /*pipes may return zero bytes, even when more data can become available later!*/
571 break;
574 g_state[myIndex] = myFlag;
576 ReleaseSRWLockExclusive(&g_rwLocks[myIndex]);
577 WakeAllConditionVariable(&g_condIsReady[myIndex]);
579 INCREMENT_INDEX(myIndex, myFlag);
581 if (options.delay)
583 Sleep(1U);
586 while ((!g_stop) || options.ignore);
588 exitCode = 0;
590 cleanup:
592 /* Stop the worker threads */
593 AcquireSRWLockExclusive(&g_rwLocks[myIndex]);
594 g_state[myIndex] = MAXBYTE;
595 g_pending[myIndex] = MAX_THREADS;
596 ReleaseSRWLockExclusive(&g_rwLocks[myIndex]);
597 WakeAllConditionVariable(&g_condIsReady[myIndex]);
599 /* Wait for worker threads to exit */
600 const DWORD pendingThreads = count_handles(hThreads, ARRAYSIZE(hThreads));
601 if (pendingThreads > 0U)
603 const DWORD result = WaitForMultipleObjects(pendingThreads, hThreads, TRUE, 10000U);
604 if (!((result >= WAIT_OBJECT_0) && (result < WAIT_OBJECT_0 + pendingThreads)))
606 for (DWORD threadId = 0U; threadId < pendingThreads; ++threadId)
608 if (WaitForSingleObject(hThreads[threadId], 125U) != WAIT_OBJECT_0)
610 write_text(hStdErr, L"[tee] Error: Worker thread did not exit cleanly!\n");
611 TerminateThread(hThreads[threadId], 1U);
617 /* Flush the output file */
618 if (options.flush)
620 for (size_t fileIndex = 0U; fileIndex < ARRAYSIZE(hMyFiles); ++fileIndex)
622 if (hMyFiles[fileIndex] != INVALID_HANDLE_VALUE)
624 FlushFileBuffers(hMyFiles[fileIndex]);
629 /* Close worker threads */
630 for (DWORD threadId = 0U; threadId < ARRAYSIZE(hThreads); ++threadId)
632 CLOSE_HANDLE(hThreads[threadId]);
635 /* Close the output file(s) */
636 for (size_t fileIndex = 0U; fileIndex < ARRAYSIZE(hMyFiles); ++fileIndex)
638 CLOSE_HANDLE(hMyFiles[fileIndex]);
641 /* Exit */
642 return exitCode;
645 // --------------------------------------------------------------------------
646 // CRT Startup
647 // --------------------------------------------------------------------------
649 #ifndef _DEBUG
650 #pragma warning(disable: 4702)
652 int _startup(void)
654 SetErrorMode(SEM_FAILCRITICALERRORS);
656 int nArgs;
657 LPWSTR *const szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
658 if (!szArglist)
660 OutputDebugStringA("[tee-win32] System error: Failed to initialize command-line arguments!\n");
661 ExitProcess((UINT)-1);
664 const int retval = wmain(nArgs, szArglist);
665 LocalFree(szArglist);
666 ExitProcess((UINT)retval);
668 return 0;
671 #endif