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
23 #include "include/cpu.h"
24 #include "include/version.h"
26 #pragma intrinsic(_InterlockedIncrement, _InterlockedDecrement)
28 #define BUFFER_SIZE (PROCESSOR_BITNESS * 128U)
30 #define MAX_THREADS MAXIMUM_WAIT_OBJECTS
32 // --------------------------------------------------------------------------
34 // --------------------------------------------------------------------------
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); \
45 #define ASSERT(CONDIATION, HANDLE_OUT, MESSAGE) ((void)0)
48 // --------------------------------------------------------------------------
50 // --------------------------------------------------------------------------
52 #define POS_LONG(X) ((LONG)((X) & MAXLONG))
53 #define NEG_LONG(X) (-POS_LONG(X))
55 static wchar_t to_lower(const wchar_t c
)
57 return ((c
>= L
'A') && (c
<= L
'Z')) ? (L
'a' + (c
- L
'A')) : c
;
60 static BOOL
is_terminal(const HANDLE handle
)
63 return GetConsoleMode(handle
, &mode
);
66 static DWORD
count_handles(const HANDLE
*const array
, const size_t maximum
)
69 for (counter
= 0U; counter
< maximum
; ++counter
)
80 static const wchar_t *get_filename(const wchar_t *filePath
)
82 for (const wchar_t *ptr
= filePath
; *ptr
!= L
'\0'; ++ptr
)
84 if ((*ptr
== L
'\\') || (*ptr
== L
'/'))
93 static BOOL
is_null_device(const wchar_t *filePath
)
95 filePath
= get_filename(filePath
);
96 if ((to_lower(filePath
[0U]) == L
'n') && (to_lower(filePath
[1U]) == L
'u') && (to_lower(filePath
[2U]) == L
'l'))
98 return ((filePath
[3U] == L
'\0') || (filePath
[3U] == L
'.'));
104 static wchar_t *format_string(const wchar_t *const format
, ...)
106 wchar_t* buffer
= NULL
;
109 va_start(ap
, format
);
110 const DWORD result
= FormatMessageW(FORMAT_MESSAGE_FROM_STRING
| FORMAT_MESSAGE_ALLOCATE_BUFFER
, format
, 0U, 0U, (LPWSTR
)&buffer
, 1U, &ap
);
113 return result
? buffer
: NULL
;
116 static wchar_t *concat_va(const wchar_t *const first
, ...)
123 for (ptr
= first
; ptr
!= NULL
; ptr
= va_arg(ap
, const wchar_t*))
129 wchar_t *const buffer
= (wchar_t*)LocalAlloc(LPTR
, sizeof(wchar_t) * (len
+ 1U));
133 for (ptr
= first
; ptr
!= NULL
; ptr
= va_arg(ap
, const wchar_t*))
135 lstrcatW(buffer
, ptr
);
143 #define CONCAT(...) concat_va(__VA_ARGS__, NULL)
145 #define VALID_HANDLE(HANDLE) (((HANDLE) != NULL) && ((HANDLE) != INVALID_HANDLE_VALUE))
147 #define FILL_ARRAY(ARRAY, VALUE) do \
149 for (size_t _index = 0U; _index < ARRAYSIZE(ARRAY); ++_index) \
151 ARRAY[_index] = (VALUE); \
156 #define CLOSE_HANDLE(HANDLE) do \
158 if (VALID_HANDLE(HANDLE)) \
160 CloseHandle((HANDLE)); \
166 // --------------------------------------------------------------------------
167 // Console CTRL+C handler
168 // --------------------------------------------------------------------------
170 static volatile BOOL g_stop
= FALSE
;
172 static BOOL WINAPI
console_handler(const DWORD ctrlType
)
177 case CTRL_BREAK_EVENT
:
178 case CTRL_CLOSE_EVENT
:
186 // --------------------------------------------------------------------------
188 // --------------------------------------------------------------------------
190 static char *utf16_to_utf8(const wchar_t *const input
)
192 const int buff_size
= WideCharToMultiByte(CP_UTF8
, 0, input
, -1, NULL
, 0, NULL
, NULL
);
195 char *const buffer
= (char*)LocalAlloc(LPTR
, buff_size
);
198 const int result
= WideCharToMultiByte(CP_UTF8
, 0, input
, -1, buffer
, buff_size
, NULL
, NULL
);
199 if ((result
> 0) && (result
<= buff_size
))
210 static BOOL
write_text(const HANDLE handle
, const wchar_t *const text
)
215 if (GetConsoleMode(handle
, &written
))
217 result
= WriteConsoleW(handle
, text
, lstrlenW(text
), &written
, NULL
);
221 char *const utf8_text
= utf16_to_utf8(text
);
224 result
= WriteFile(handle
, utf8_text
, lstrlenA(utf8_text
), &written
, NULL
);
225 LocalFree(utf8_text
);
232 #define WRITE_TEXT(...) do \
234 wchar_t* const _message = CONCAT(__VA_ARGS__); \
237 write_text(hStdErr, _message); \
238 LocalFree(_message); \
243 // --------------------------------------------------------------------------
245 // --------------------------------------------------------------------------
247 #define INCREMENT_INDEX(INDEX, FLAG) do { if (++(INDEX) >= BUFFERS) { (INDEX) = 0U; (FLAG) = (!(FLAG)); } } while (0)
249 typedef struct _thread
251 HANDLE hOutput
, hError
;
256 static BYTE g_buffer
[BUFFERS
][BUFFER_SIZE
];
257 static DWORD g_bytesTotal
[BUFFERS
] = { 0U, 0U, 0U };
258 static volatile LONG g_pending
[BUFFERS
] = { 0L, 0L, 0L };
259 static SRWLOCK g_rwLocks
[BUFFERS
];
260 static CONDITION_VARIABLE g_condIsReady
[BUFFERS
], g_condAllDone
[BUFFERS
];
262 static DWORD WINAPI
writer_thread_start_routine(const LPVOID lpThreadParameter
)
264 DWORD bytesWritten
= 0U, myIndex
= 0U;
266 BOOL myFlag
= TRUE
, writeErrors
= FALSE
;
267 const thread_t
*const param
= (const thread_t
*)lpThreadParameter
;
271 ASSERT(myIndex
< BUFFERS
, param
->hError
, L
"Current buffer index is out of range!");
273 AcquireSRWLockShared(&g_rwLocks
[myIndex
]);
275 pending
= g_pending
[myIndex
];
277 while (!(myFlag
? (pending
> 0L) : (pending
< 0L)))
279 if (!SleepConditionVariableSRW(&g_condIsReady
[myIndex
], &g_rwLocks
[myIndex
], INFINITE
, CONDITION_VARIABLE_LOCKMODE_SHARED
))
281 ReleaseSRWLockShared(&g_rwLocks
[myIndex
]);
282 write_text(param
->hError
, L
"[tee] Operating system error: SleepConditionVariableSRW() has failed!\n");
283 TerminateProcess(GetCurrentProcess(), 1U);
285 pending
= g_pending
[myIndex
];
288 const DWORD bytesTotal
= g_bytesTotal
[myIndex
];
289 if (bytesTotal
== MAXDWORD
)
291 ReleaseSRWLockShared(&g_rwLocks
[myIndex
]);
294 write_text(param
->hError
, L
"[tee] I/O error: Not all data could be written!\n");
299 for (DWORD offset
= 0U; offset
< bytesTotal
; offset
+= bytesWritten
)
301 const BOOL result
= WriteFile(param
->hOutput
, g_buffer
[myIndex
] + offset
, g_bytesTotal
[myIndex
] - offset
, &bytesWritten
, NULL
);
302 if ((!result
) || (!bytesWritten
))
309 ASSERT(g_pending
> 0U, param
->hError
, L
"Pending threads counter must be a positive value!");
311 pending
= myFlag
? _InterlockedDecrement(&g_pending
[myIndex
]) : _InterlockedIncrement(&g_pending
[myIndex
]);
313 ReleaseSRWLockShared(&g_rwLocks
[myIndex
]);
317 WakeConditionVariable(&g_condAllDone
[myIndex
]);
320 INCREMENT_INDEX(myIndex
, myFlag
);
324 FlushFileBuffers(param
->hOutput
);
329 // --------------------------------------------------------------------------
331 // --------------------------------------------------------------------------
335 BOOL append
, delay
, flush
, help
, ignore
, version
;
339 #define PARSE_OPTION(SHRT, NAME) do \
341 if ((lc == L##SHRT) || (name && (lstrcmpiW(name, L#NAME) == 0))) \
343 options->NAME = TRUE; \
349 static BOOL
parse_option(options_t
*const options
, const wchar_t c
, const wchar_t *const name
)
351 const wchar_t lc
= to_lower(c
);
353 PARSE_OPTION('a', append
);
354 PARSE_OPTION('d', delay
);
355 PARSE_OPTION('f', flush
);
356 PARSE_OPTION('h', help
);
357 PARSE_OPTION('i', ignore
);
358 PARSE_OPTION('v', version
);
363 static BOOL
parse_argument(options_t
*const options
, const wchar_t *const argument
)
365 if ((argument
[0U] != L
'-') || (argument
[1U] == L
'\0'))
370 if (argument
[1U] == L
'-')
372 return (argument
[2U] != L
'\0') && parse_option(options
, L
'\0', argument
+ 2U);
376 for (const wchar_t* ptr
= argument
+ 1U; *ptr
!= L
'\0'; ++ptr
)
378 if (!parse_option(options
, *ptr
, NULL
))
387 // --------------------------------------------------------------------------
389 // --------------------------------------------------------------------------
391 int wmain(const int argc
, const wchar_t *const argv
[])
393 HANDLE hThreads
[MAX_THREADS
], hMyFiles
[MAX_THREADS
- 1U];
394 int exitCode
= 1, argOff
= 1;
396 DWORD fileCount
= 0U, threadCount
= 0U, myIndex
= 0U;
398 static thread_t threadData
[MAX_THREADS
];
400 /* Initialize local variables */
401 FILL_ARRAY(hMyFiles
, INVALID_HANDLE_VALUE
);
402 FILL_ARRAY(hThreads
, NULL
);
403 SecureZeroMemory(&options
, sizeof(options
));
404 SecureZeroMemory(&threadData
, sizeof(threadData
));
406 /* Initialize standard streams */
407 const HANDLE hStdIn
= GetStdHandle(STD_INPUT_HANDLE
), hStdOut
= GetStdHandle(STD_OUTPUT_HANDLE
), hStdErr
= GetStdHandle(STD_ERROR_HANDLE
);
408 if (!(VALID_HANDLE(hStdIn
) && VALID_HANDLE(hStdOut
) && VALID_HANDLE(hStdErr
)))
410 if (VALID_HANDLE(hStdErr
))
412 write_text(hStdErr
, L
"[tee] Operating system error: GetStdHandle() has failed!\n");
417 /* Initialize read/write locks and condition variables */
418 for (DWORD index
= 0; index
< BUFFERS
; ++index
)
420 InitializeSRWLock(&g_rwLocks
[index
]);
421 InitializeConditionVariable(&g_condIsReady
[index
]);
422 InitializeConditionVariable(&g_condAllDone
[index
]);
425 /* Set up CRTL+C handler */
426 SetConsoleCtrlHandler(console_handler
, TRUE
);
428 /* Parse command-line options */
429 while ((argOff
< argc
) && (argv
[argOff
][0U] == L
'-') && (argv
[argOff
][1U] != L
'\0'))
431 const wchar_t *const argValue
= argv
[argOff
++];
432 if ((argValue
[1U] == L
'-') && (argValue
[2U] == L
'\0'))
436 else if (!parse_argument(&options
, argValue
))
438 WRITE_TEXT(L
"[tee] Error: Invalid option \"", argValue
, L
"\" encountered!\n");
443 /* Print manual page */
444 if (options
.help
|| options
.version
)
446 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__
));
447 write_text(hStdErr
, versionString
? versionString
: L
"tee for Windows\n");
450 write_text(hStdErr
, L
"\n"
451 L
"Copy standard input to output file(s), and also to standard output.\n\n"
453 L
" gizmo.exe [...] | tee.exe [options] <file_1> ... <file_n>\n\n"
455 L
" -a --append Append to the existing file, instead of truncating\n"
456 L
" -f --flush Flush output file after each write operation\n"
457 L
" -i --ignore Ignore the interrupt signal (SIGINT), e.g. CTRL+C\n"
458 L
" -d --delay Add a small delay after each read operation\n\n");
462 LocalFree(versionString
);
467 /* Check output file name */
470 write_text(hStdErr
, L
"[tee] Error: Output file name is missing. Type \"tee --help\" for details!\n");
474 /* Determine input type */
475 const DWORD inputType
= GetFileType(hStdIn
);
476 if (inputType
== FILE_TYPE_UNKNOWN
)
478 if (GetLastError() != NO_ERROR
)
480 write_text(hStdErr
, L
"[tee] Operating system error: GetFileType(hStdIn) has failed!\n");
485 /* Validate output stream */
486 if (GetFileType(hStdOut
) == FILE_TYPE_UNKNOWN
)
488 if (GetLastError() != NO_ERROR
)
490 write_text(hStdErr
, L
"[tee] Operating system error: GetFileType(hStdOut) has failed!\n");
495 /* Open output file(s) */
496 while ((argOff
< argc
) && (fileCount
< ARRAYSIZE(hMyFiles
)))
498 const wchar_t* const fileName
= argv
[argOff
++];
499 if (!is_null_device(fileName
))
501 const HANDLE hFile
= CreateFileW(fileName
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
, options
.append
? OPEN_ALWAYS
: CREATE_ALWAYS
, 0U, NULL
);
502 if ((hMyFiles
[fileCount
++] = hFile
) == INVALID_HANDLE_VALUE
)
504 WRITE_TEXT(L
"[tee] Error: Failed to open the output file \"", fileName
, L
"\" for writing!\n");
507 else if (options
.append
)
509 LARGE_INTEGER offset
= { .QuadPart
= 0LL };
510 if (!SetFilePointerEx(hFile
, offset
, NULL
, FILE_END
))
512 write_text(hStdErr
, L
"[tee] Error: Failed to move the file pointer to the end of the file!\n");
519 /* Check output file name */
522 write_text(hStdErr
, L
"[tee] Warning: Too many input files, ignoring excess files!\n");
525 /* Determine number of outputs */
526 const DWORD outputCount
= fileCount
+ 1U;
529 for (DWORD threadId
= 0; threadId
< outputCount
; ++threadId
)
531 threadData
[threadId
].hOutput
= (threadId
> 0U) ? hMyFiles
[threadId
- 1U] : hStdOut
;
532 threadData
[threadId
].hError
= hStdErr
;
533 threadData
[threadId
].flush
= options
.flush
&& (!is_terminal(threadData
[threadId
].hOutput
));
534 if (!(hThreads
[threadCount
++] = CreateThread(NULL
, 0U, writer_thread_start_routine
, (LPVOID
)&threadData
[threadId
], 0U, NULL
)))
536 write_text(hStdErr
, L
"[tee] Operating system error: CreateThread() has failed!\n");
541 /* Process all input from STDIN stream */
544 ASSERT(myIndex
< BUFFERS
, hStdErr
, L
"Current buffer index is out of range!");
546 AcquireSRWLockExclusive(&g_rwLocks
[myIndex
]);
548 while (g_pending
[myIndex
])
550 if (!SleepConditionVariableSRW(&g_condAllDone
[myIndex
], &g_rwLocks
[myIndex
], INFINITE
, 0U))
552 ReleaseSRWLockExclusive(&g_rwLocks
[myIndex
]);
553 write_text(hStdErr
, L
"[tee] Operating system error: SleepConditionVariableSRW() has failed!\n");
554 TerminateProcess(GetCurrentProcess(), 1U);
558 if (!ReadFile(hStdIn
, g_buffer
[myIndex
], BUFFER_SIZE
, &g_bytesTotal
[myIndex
], NULL
))
560 const DWORD error
= GetLastError();
561 ReleaseSRWLockExclusive(&g_rwLocks
[myIndex
]);
562 if (error
!= ERROR_BROKEN_PIPE
)
564 write_text(hStdErr
, L
"[tee] I/O error: Failed to read input data!\n");
570 if (!g_bytesTotal
[myIndex
])
572 ReleaseSRWLockExclusive(&g_rwLocks
[myIndex
]);
573 if (inputType
== FILE_TYPE_PIPE
)
575 continue; /*pipes may return zero bytes, even when more data can become available later!*/
580 g_pending
[myIndex
] = myFlag
? POS_LONG(threadCount
) : NEG_LONG(threadCount
);
582 ReleaseSRWLockExclusive(&g_rwLocks
[myIndex
]);
583 WakeAllConditionVariable(&g_condIsReady
[myIndex
]);
585 INCREMENT_INDEX(myIndex
, myFlag
);
592 while ((!g_stop
) || options
.ignore
);
598 /* Stop the worker threads */
599 AcquireSRWLockExclusive(&g_rwLocks
[myIndex
]);
600 g_bytesTotal
[myIndex
] = MAXDWORD
;
601 g_pending
[myIndex
] = myFlag
? MAXLONG
: MINLONG
;
602 ReleaseSRWLockExclusive(&g_rwLocks
[myIndex
]);
603 WakeAllConditionVariable(&g_condIsReady
[myIndex
]);
605 /* Wait for worker threads to exit */
606 const DWORD pendingThreads
= count_handles(hThreads
, ARRAYSIZE(hThreads
));
607 if (pendingThreads
> 0U)
609 const DWORD result
= WaitForMultipleObjects(pendingThreads
, hThreads
, TRUE
, 10000U);
610 if (!((result
>= WAIT_OBJECT_0
) && (result
< WAIT_OBJECT_0
+ pendingThreads
)))
612 for (DWORD threadId
= 0U; threadId
< pendingThreads
; ++threadId
)
614 if (WaitForSingleObject(hThreads
[threadId
], 125U) != WAIT_OBJECT_0
)
616 write_text(hStdErr
, L
"[tee] Internal error: Worker thread did not exit cleanly!\n");
617 TerminateThread(hThreads
[threadId
], 1U);
623 /* Flush the output file */
626 for (size_t fileIndex
= 0U; fileIndex
< ARRAYSIZE(hMyFiles
); ++fileIndex
)
628 if (hMyFiles
[fileIndex
] != INVALID_HANDLE_VALUE
)
630 FlushFileBuffers(hMyFiles
[fileIndex
]);
635 /* Close worker threads */
636 for (DWORD threadId
= 0U; threadId
< ARRAYSIZE(hThreads
); ++threadId
)
638 CLOSE_HANDLE(hThreads
[threadId
]);
641 /* Close the output file(s) */
642 for (size_t fileIndex
= 0U; fileIndex
< ARRAYSIZE(hMyFiles
); ++fileIndex
)
644 CLOSE_HANDLE(hMyFiles
[fileIndex
]);
651 // --------------------------------------------------------------------------
653 // --------------------------------------------------------------------------
656 #pragma warning(disable: 4702)
660 SetErrorMode(SEM_FAILCRITICALERRORS
);
663 LPWSTR
*const szArglist
= CommandLineToArgvW(GetCommandLineW(), &nArgs
);
666 OutputDebugStringA("[tee-win32] System error: Failed to initialize command-line arguments!\n");
667 ExitProcess((UINT
)-1);
670 const int retval
= wmain(nArgs
, szArglist
);
671 LocalFree(szArglist
);
672 ExitProcess((UINT
)retval
);