summaryrefslogtreecommitdiff
path: root/desktop/win32/source/guistdio/guistdio.inc
blob: 5617d889a402423e8f81f37806270253c04f74a2 (plain)
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#define UNICODE
#define WIN32_LEAN_AND_MEAN
#ifdef _MSC_VER
#pragma warning(push,1) // disable warnings within system headers
#endif
#include <windows.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif

#define _UNICODE
#include <tchar.h>

#include <string.h>
#include <stdlib.h>
#include <systools/win32/uwinapi.h>

#include <stdio.h>
#include <sal/macros.h>

#ifdef UNOPKG

DWORD passOutputToConsole(HANDLE readPipe, HANDLE console)
{
    BYTE aBuffer[1024];
    DWORD dwRead = 0;
    HANDLE hReadPipe = readPipe;
    DWORD dwWritten;

    //Indicates that we read an odd number of bytes. That is, we only read half of the last
    //wchar_t
    bool bIncompleteWchar = false;
    //fprintf, fwprintf will both send char data without the terminating zero.
    //fwprintf converts the unicode string first.
    //We expect here to receive unicode without the terminating zero.
    //unopkg and the extension manager code MUST
    //use dp_misc::writeConsole instead of using fprintf, etc.

    DWORD dwToRead = sizeof(aBuffer);
    BYTE * pBuffer = aBuffer;
    while ( ReadFile( hReadPipe, pBuffer, dwToRead, &dwRead, nullptr ) )
    {
        //If the previous ReadFile call read an odd number of bytes, then the last one was
        //put at the front of the buffer. We increase the number of read bytes by one to reflect
        //that one byte.
        if (bIncompleteWchar)
            dwRead++;
        //We must make sure that only complete wchar_t|s are written. WriteConsolse takes
        //the number of wchar_t|s as argument. ReadFile, however, reads bytes.
        bIncompleteWchar = (dwRead % 2) != 0;
        if (bIncompleteWchar)
        {
            //To test this case, give aBuffer a small odd size, e.g. aBuffer[3]
            //The last byte, which is the incomplete wchar_t (half of it), will not be written.
            (void) WriteConsoleW( console, aBuffer,
                (dwRead - 1) / 2, &dwWritten, nullptr );

            //Move the last byte to the front of the buffer, so that it is the start of the
            //next string
            aBuffer[0] = aBuffer[dwRead - 1];

            //Make sure that ReadFile does not overwrite the first byte the next time
            dwToRead = sizeof(aBuffer) - 1;
            pBuffer = aBuffer + 1;

        }
        else
        {   //We have read an even number of bytes. Therefore, we do not put the last incomplete
            //wchar_t at the front of the buffer. We will use the complete buffer the next time
            //when ReadFile is called.
            dwToRead = sizeof(aBuffer);
            pBuffer = aBuffer;
            (void) WriteConsoleW( console,
                aBuffer, dwRead / 2, &dwWritten, nullptr );
        }
    }

    return 0;
}

#endif

#ifdef UNOPKG
DWORD WINAPI OutputThread( LPVOID pParam )
{
    return passOutputToConsole(static_cast<HANDLE>(pParam), GetStdHandle( STD_OUTPUT_HANDLE ));
}

#else
DWORD WINAPI OutputThread( LPVOID pParam )
{
    BYTE    aBuffer[256];
    DWORD   dwRead = 0;
    HANDLE  hReadPipe = (HANDLE)pParam;
    while ( ReadFile( hReadPipe, &aBuffer, sizeof(aBuffer), &dwRead, NULL ) )
    {
        DWORD   dwWritten;

        (void) WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), aBuffer, dwRead, &dwWritten, NULL );
    }

    return 0;
}
#endif

// Thread that reads from child process standard error pipe


#ifdef UNOPKG
DWORD WINAPI ErrorThread( LPVOID pParam )
{
    return passOutputToConsole(static_cast<HANDLE>(pParam), GetStdHandle( STD_ERROR_HANDLE ));
}

#else
DWORD WINAPI ErrorThread( LPVOID pParam )
{
    BYTE    aBuffer[256];
    DWORD   dwRead = 0;
    HANDLE  hReadPipe = (HANDLE)pParam;

    while ( ReadFile( hReadPipe, &aBuffer, sizeof(aBuffer), &dwRead, NULL ) )
    {
        DWORD   dwWritten;

        (void) WriteFile( GetStdHandle( STD_ERROR_HANDLE ), aBuffer, dwRead, &dwWritten, NULL );
    }

    return 0;
}
#endif

// Thread that writes to child process standard input pipe

#ifdef UNOPKG

DWORD WINAPI InputThread( LPVOID pParam )
{
    DWORD   dwRead = 0;
    HANDLE  hWritePipe = static_cast<HANDLE>(pParam);

    //We need to read in the complete input until we encounter a new line before
    //converting to Unicode. This is necessary because the input string can use
    //characters of one, two, and more bytes. If the last character is not
    //complete, then it will not be converted properly.

    //Find out how a new line (0xd 0xa) looks like with the used code page.
    //Characters may have one or multiple bytes and different byte ordering
    //can be used (little and big endian);
    int cNewLine = WideCharToMultiByte(
        GetConsoleCP(), 0, L"\r\n", 2, nullptr, 0, nullptr, nullptr);
    char * mbBuff = new char[cNewLine];
    WideCharToMultiByte(
        GetConsoleCP(), 0, L"\r\n", 2, mbBuff, cNewLine, nullptr, nullptr);

    const DWORD dwBufferSize = 256;
    char* readBuf = static_cast<char*>(malloc(dwBufferSize));
    int readAll = 0;
    DWORD curBufSize = dwBufferSize;

    while ( ReadFile( GetStdHandle( STD_INPUT_HANDLE ),
                      readBuf + readAll,
                      curBufSize - readAll, &dwRead, nullptr ) )
    {
        readAll += dwRead;
        int lastBufSize = curBufSize;
        //Grow the buffer if necessary
        if (readAll > curBufSize * 0.7)
        {
            curBufSize *= 2;
            readBuf = static_cast<char *>(realloc(readBuf, curBufSize));
        }

        //If the buffer was filled completely then
        //there could be more input coming. But if we read from the console
        //and the console input fits exactly in the buffer, then the next
        //ReadFile would block until the users presses return, etc.
        //Therefore we check if last character is a new line.
        //To test this, set dwBufferSize to 4 and enter "no". This should produce
        //4 bytes with most code pages.
        if ( readAll == lastBufSize
             && memcmp(readBuf + lastBufSize - cNewLine, mbBuff, cNewLine) != 0)
        {
            //The buffer was completely filled and the last byte(s) are no
            //new line, so there is more to come.
            continue;
        }
        //Obtain the size of the buffer for the converted string.
        int sizeWBuf = MultiByteToWideChar(
            GetConsoleCP(), MB_PRECOMPOSED, readBuf, readAll, nullptr, 0);

        wchar_t * wideBuf = new wchar_t[sizeWBuf];

        //Do the conversion.
        MultiByteToWideChar(
            GetConsoleCP(), MB_PRECOMPOSED, readBuf, readAll, wideBuf, sizeWBuf);

        DWORD   dwWritten;
        (void)WriteFile( hWritePipe, wideBuf, sizeWBuf * 2, &dwWritten, nullptr );

        delete[] wideBuf;
        readAll = 0;
    }
    delete[] mbBuff;
    free(readBuf);
    return 0;
}
#else
DWORD WINAPI InputThread( LPVOID pParam )
{
    BYTE    aBuffer[256];
    DWORD   dwRead = 0;
    HANDLE  hWritePipe = (HANDLE)pParam;

    while ( ReadFile( GetStdHandle( STD_INPUT_HANDLE ), &aBuffer, sizeof(aBuffer), &dwRead, NULL ) )
    {
        DWORD dwWritten;
        (void) WriteFile( hWritePipe, aBuffer, dwRead, &dwWritten, NULL );
    }

    return 0;
}
#endif


// Thread that waits until child process reached input idle


DWORD WINAPI WaitForUIThread( LPVOID pParam )
{
#ifndef UNOPKG
    HANDLE  hProcess = (HANDLE)pParam;

    if ( !_tgetenv( TEXT("UNOPKG") ) )
        WaitForInputIdle( hProcess, INFINITE );
#else
    (void) pParam;
#endif

    return 0;
}



// Ctrl-Break handler that terminates the child process if Ctrl-C was pressed


HANDLE  hTargetProcess = INVALID_HANDLE_VALUE;

BOOL WINAPI CtrlBreakHandler(
  DWORD   //  control signal type
)
{
    TerminateProcess( hTargetProcess, 255 );
    return TRUE;
}

int _tmain( int, _TCHAR ** )
{
    TCHAR               szTargetFileName[MAX_PATH] = TEXT("");
    STARTUPINFO         aStartupInfo;
    PROCESS_INFORMATION aProcessInfo;

    ZeroMemory( &aStartupInfo, sizeof(aStartupInfo) );
    aStartupInfo.cb = sizeof(aStartupInfo);
    aStartupInfo.dwFlags = STARTF_USESTDHANDLES;

    // Create an output pipe where the write end is inheritable

    HANDLE  hOutputRead, hOutputWrite;

    if ( CreatePipe( &hOutputRead, &hOutputWrite, nullptr, 0 ) )
    {
        HANDLE  hTemp;

        DuplicateHandle( GetCurrentProcess(), hOutputWrite, GetCurrentProcess(), &hTemp, 0, TRUE, DUPLICATE_SAME_ACCESS );
        CloseHandle( hOutputWrite );
        hOutputWrite = hTemp;

        aStartupInfo.hStdOutput = hOutputWrite;
    }

    // Create an error pipe where the write end is inheritable

    HANDLE  hErrorRead, hErrorWrite;

    if ( CreatePipe( &hErrorRead, &hErrorWrite, nullptr, 0 ) )
    {
        HANDLE  hTemp;

        DuplicateHandle( GetCurrentProcess(), hErrorWrite, GetCurrentProcess(), &hTemp, 0, TRUE, DUPLICATE_SAME_ACCESS );
        CloseHandle( hErrorWrite );
        hErrorWrite = hTemp;

        aStartupInfo.hStdError = hErrorWrite;
    }

    // Create an input pipe where the read end is inheritable

    HANDLE  hInputRead, hInputWrite;

    if ( CreatePipe( &hInputRead, &hInputWrite, nullptr, 0 ) )
    {
        HANDLE  hTemp;

        DuplicateHandle( GetCurrentProcess(), hInputRead, GetCurrentProcess(), &hTemp, 0, TRUE, DUPLICATE_SAME_ACCESS );
        CloseHandle( hInputRead );
        hInputRead = hTemp;

        aStartupInfo.hStdInput = hInputRead;
    }

    // Get image path with same name but with .exe extension

    TCHAR               szModuleFileName[MAX_PATH];

    GetModuleFileName( nullptr, szModuleFileName, MAX_PATH );
    _TCHAR  *lpLastDot = _tcsrchr( szModuleFileName, '.' );
    if ( lpLastDot && 0 == _tcsicmp( lpLastDot, _T(".COM") ) )
    {
        size_t len = lpLastDot - szModuleFileName;
        _tcsncpy( szTargetFileName, szModuleFileName, len );
        _tcsncpy( szTargetFileName + len, _T(".EXE"), SAL_N_ELEMENTS(szTargetFileName) - len );
    }

    // Create process with same command line, environment and stdio handles which
    // are directed to the created pipes

    BOOL    fSuccess = CreateProcess(
        szTargetFileName,
        GetCommandLine(),
        nullptr,
        nullptr,
        TRUE,
        0,
        nullptr,
        nullptr,
        &aStartupInfo,
        &aProcessInfo );

    if ( fSuccess )
    {
        // These pipe ends are inherited by the child process and no longer used
        CloseHandle( hOutputWrite );
        CloseHandle( hErrorWrite );
        CloseHandle( hInputRead );

        // Set the Ctrl-Break handler
        hTargetProcess = aProcessInfo.hProcess;
        SetConsoleCtrlHandler( CtrlBreakHandler, TRUE );

        // Create threads that redirect remote pipe io to current process's console stdio

        DWORD   dwOutputThreadId, dwErrorThreadId, dwInputThreadId;

        HANDLE  hOutputThread = CreateThread( nullptr, 0, OutputThread, static_cast<LPVOID>(hOutputRead), 0, &dwOutputThreadId );
        HANDLE  hErrorThread = CreateThread( nullptr, 0, OutputThread, static_cast<LPVOID>(hErrorRead), 0, &dwErrorThreadId );
        HANDLE  hInputThread = CreateThread( nullptr, 0, InputThread, static_cast<LPVOID>(hInputWrite), 0, &dwInputThreadId );

        // Create thread that wait until child process entered input idle

        DWORD   dwWaitForUIThreadId;
        HANDLE  hWaitForUIThread = CreateThread( nullptr, 0, WaitForUIThread, static_cast<LPVOID>(aProcessInfo.hProcess), 0, &dwWaitForUIThreadId );

        HANDLE  hObjects[] =
            {
                hTargetProcess,
                hWaitForUIThread,
                hOutputThread,
                hErrorThread
            };

 #ifdef UNOPKG
        WaitForMultipleObjects( SAL_N_ELEMENTS(hObjects), hObjects, TRUE, INFINITE );
 #else
        bool    bDetach = false;
        int     nOpenPipes = 2;
        do
        {
            DWORD dwWaitResult = WaitForMultipleObjects( SAL_N_ELEMENTS(hObjects), hObjects, FALSE, INFINITE );

            switch ( dwWaitResult )
            {
            case WAIT_OBJECT_0: // The child process has terminated
            case WAIT_OBJECT_0 + 1: // The child process entered input idle
                bDetach = true;
                break;
            case WAIT_OBJECT_0 + 2: // The remote end of stdout pipe was closed
            case WAIT_OBJECT_0 + 3: // The remote end of stderr pipe was closed
                bDetach = --nOpenPipes <= 0;
                break;
            default: // Something went wrong
                bDetach = true;
                break;
            }
        } while( !bDetach );

#endif

        CloseHandle( hOutputThread );
        CloseHandle( hErrorThread );
        CloseHandle( hInputThread );
        CloseHandle( hWaitForUIThread );

        DWORD   dwExitCode = 0;
        GetExitCodeProcess( aProcessInfo.hProcess, &dwExitCode );
        CloseHandle( aProcessInfo.hProcess );
        CloseHandle( aProcessInfo.hThread );

        return dwExitCode;
    }

    return -1;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */