summaryrefslogtreecommitdiffstats
path: root/src/VBox/Runtime/r3/win/pipe-win.cpp
blob: 93bf9afcf5396106f8f9bb0ac136c08b011eb81b (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
/* $Id: pipe-win.cpp $ */
/** @file
 * IPRT - Anonymous Pipes, Windows Implementation.
 */

/*
 * Copyright (C) 2010-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
 * in the VirtualBox distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 *
 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#include <iprt/nt/nt-and-windows.h>

#include <iprt/pipe.h>
#include "internal/iprt.h"

#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/critsect.h>
#include <iprt/err.h>
#include <iprt/log.h>
#include <iprt/mem.h>
#include <iprt/string.h>
#include <iprt/poll.h>
#include <iprt/process.h>
#include <iprt/thread.h>
#include <iprt/time.h>
#include "internal/pipe.h"
#include "internal/magics.h"
#include "internal-r3-win.h"


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
/** The pipe buffer size we prefer. */
#define RTPIPE_NT_SIZE      _64K


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
typedef struct RTPIPEINTERNAL
{
    /** Magic value (RTPIPE_MAGIC). */
    uint32_t            u32Magic;
    /** The pipe handle. */
    HANDLE              hPipe;
    /** Set if this is the read end, clear if it's the write end. */
    bool                fRead;
    /** RTPipeFromNative: Leave native handle open on RTPipeClose. */
    bool                fLeaveOpen;
    /** Set if there is already pending I/O. */
    bool                fIOPending;
    /** Set if the zero byte read that the poll code using is pending. */
    bool                fZeroByteRead;
    /** Set if the pipe is broken. */
    bool                fBrokenPipe;
    /** Set if we've promised that the handle is writable. */
    bool                fPromisedWritable;
    /** Set if created inheritable. */
    bool                fCreatedInheritable;
    /** Usage counter. */
    uint32_t            cUsers;
    /** The overlapped I/O structure we use. */
    OVERLAPPED          Overlapped;
    /** Bounce buffer for writes. */
    uint8_t            *pbBounceBuf;
    /** Amount of used buffer space. */
    size_t              cbBounceBufUsed;
    /** Amount of allocated buffer space. */
    size_t              cbBounceBufAlloc;
    /** The handle of the poll set currently polling on this pipe.
     *  We can only have one poller at the time (lazy bird). */
    RTPOLLSET           hPollSet;
    /** Critical section protecting the above members.
     * (Taking the lazy/simple approach.) */
    RTCRITSECT          CritSect;
    /** Buffer for the zero byte read. */
    uint8_t             abBuf[8];
} RTPIPEINTERNAL;



/**
 * Wrapper for getting FILE_PIPE_LOCAL_INFORMATION via the NT API.
 *
 * @returns Success indicator (true/false).
 * @param   pThis               The pipe.
 * @param   pInfo               The info structure.
 */
static bool rtPipeQueryNtInfo(RTPIPEINTERNAL *pThis, FILE_PIPE_LOCAL_INFORMATION *pInfo)
{
    IO_STATUS_BLOCK Ios;
    RT_ZERO(Ios);
    RT_ZERO(*pInfo);
    NTSTATUS rcNt = NtQueryInformationFile(pThis->hPipe, &Ios, pInfo, sizeof(*pInfo), FilePipeLocalInformation);
    return rcNt >= 0;
}


RTDECL(int)  RTPipeCreate(PRTPIPE phPipeRead, PRTPIPE phPipeWrite, uint32_t fFlags)
{
    AssertPtrReturn(phPipeRead, VERR_INVALID_POINTER);
    AssertPtrReturn(phPipeWrite, VERR_INVALID_POINTER);
    AssertReturn(!(fFlags & ~RTPIPE_C_VALID_MASK), VERR_INVALID_PARAMETER);

    /*
     * Create the read end of the pipe.
     */
    DWORD   dwErr;
    HANDLE  hPipeR;
    HANDLE  hPipeW;
    int     rc;
    for (;;)
    {
        static volatile uint32_t    g_iNextPipe = 0;
        char                        szName[128];
        RTStrPrintf(szName, sizeof(szName), "\\\\.\\pipe\\iprt-pipe-%u-%u", RTProcSelf(), ASMAtomicIncU32(&g_iNextPipe));

        SECURITY_ATTRIBUTES  SecurityAttributes;
        PSECURITY_ATTRIBUTES pSecurityAttributes = NULL;
        if (fFlags & RTPIPE_C_INHERIT_READ)
        {
            SecurityAttributes.nLength              = sizeof(SecurityAttributes);
            SecurityAttributes.lpSecurityDescriptor = NULL;
            SecurityAttributes.bInheritHandle       = TRUE;
            pSecurityAttributes = &SecurityAttributes;
        }

        DWORD dwOpenMode = PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED;
#ifdef FILE_FLAG_FIRST_PIPE_INSTANCE
        dwOpenMode |= FILE_FLAG_FIRST_PIPE_INSTANCE;
#endif

        DWORD dwPipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT;
#ifdef PIPE_REJECT_REMOTE_CLIENTS
        dwPipeMode |= PIPE_REJECT_REMOTE_CLIENTS;
#endif

        hPipeR = CreateNamedPipeA(szName, dwOpenMode, dwPipeMode, 1 /*nMaxInstances*/, RTPIPE_NT_SIZE, RTPIPE_NT_SIZE,
                                  NMPWAIT_USE_DEFAULT_WAIT, pSecurityAttributes);
#ifdef PIPE_REJECT_REMOTE_CLIENTS
        if (hPipeR == INVALID_HANDLE_VALUE && GetLastError() == ERROR_INVALID_PARAMETER)
        {
            dwPipeMode &= ~PIPE_REJECT_REMOTE_CLIENTS;
            hPipeR = CreateNamedPipeA(szName, dwOpenMode, dwPipeMode, 1 /*nMaxInstances*/, RTPIPE_NT_SIZE, RTPIPE_NT_SIZE,
                                      NMPWAIT_USE_DEFAULT_WAIT, pSecurityAttributes);
        }
#endif
#ifdef FILE_FLAG_FIRST_PIPE_INSTANCE
        if (hPipeR == INVALID_HANDLE_VALUE && GetLastError() == ERROR_INVALID_PARAMETER)
        {
            dwOpenMode &= ~FILE_FLAG_FIRST_PIPE_INSTANCE;
            hPipeR = CreateNamedPipeA(szName, dwOpenMode, dwPipeMode, 1 /*nMaxInstances*/, RTPIPE_NT_SIZE, RTPIPE_NT_SIZE,
                                      NMPWAIT_USE_DEFAULT_WAIT, pSecurityAttributes);
        }
#endif
        if (hPipeR != INVALID_HANDLE_VALUE)
        {
            /*
             * Connect to the pipe (the write end).
             * We add FILE_READ_ATTRIBUTES here to make sure we can query the
             * pipe state later on.
             */
            pSecurityAttributes = NULL;
            if (fFlags & RTPIPE_C_INHERIT_WRITE)
            {
                SecurityAttributes.nLength              = sizeof(SecurityAttributes);
                SecurityAttributes.lpSecurityDescriptor = NULL;
                SecurityAttributes.bInheritHandle       = TRUE;
                pSecurityAttributes = &SecurityAttributes;
            }

            hPipeW = CreateFileA(szName,
                                 GENERIC_WRITE | FILE_READ_ATTRIBUTES /*dwDesiredAccess*/,
                                 0 /*dwShareMode*/,
                                 pSecurityAttributes,
                                 OPEN_EXISTING /* dwCreationDisposition */,
                                 FILE_FLAG_OVERLAPPED /*dwFlagsAndAttributes*/,
                                 NULL /*hTemplateFile*/);
            if (hPipeW != INVALID_HANDLE_VALUE)
                break;
            dwErr = GetLastError();
            CloseHandle(hPipeR);
        }
        else
            dwErr = GetLastError();
        if (   dwErr != ERROR_PIPE_BUSY     /* already exist - compatible */
            && dwErr != ERROR_ACCESS_DENIED /* already exist - incompatible */)
            return RTErrConvertFromWin32(dwErr);
        /* else: try again with a new name */
    }

    /*
     * Create the two handles.
     */
    RTPIPEINTERNAL *pThisR = (RTPIPEINTERNAL *)RTMemAllocZ(sizeof(RTPIPEINTERNAL));
    if (pThisR)
    {
        RTPIPEINTERNAL *pThisW = (RTPIPEINTERNAL *)RTMemAllocZ(sizeof(RTPIPEINTERNAL));
        if (pThisW)
        {
            rc = RTCritSectInit(&pThisR->CritSect);
            if (RT_SUCCESS(rc))
            {
                rc = RTCritSectInit(&pThisW->CritSect);
                if (RT_SUCCESS(rc))
                {
                    pThisR->Overlapped.hEvent = CreateEvent(NULL, TRUE /*fManualReset*/,
                                                            TRUE /*fInitialState*/, NULL /*pName*/);
                    if (pThisR->Overlapped.hEvent != NULL)
                    {
                        pThisW->Overlapped.hEvent = CreateEvent(NULL, TRUE /*fManualReset*/,
                                                                TRUE /*fInitialState*/, NULL /*pName*/);
                        if (pThisW->Overlapped.hEvent != NULL)
                        {
                            pThisR->u32Magic            = RTPIPE_MAGIC;
                            pThisW->u32Magic            = RTPIPE_MAGIC;
                            pThisR->hPipe               = hPipeR;
                            pThisW->hPipe               = hPipeW;
                            pThisR->fRead               = true;
                            pThisW->fRead               = false;
                            pThisR->fLeaveOpen          = false;
                            pThisW->fLeaveOpen          = false;
                            //pThisR->fIOPending        = false;
                            //pThisW->fIOPending        = false;
                            //pThisR->fZeroByteRead     = false;
                            //pThisW->fZeroByteRead     = false;
                            //pThisR->fBrokenPipe       = false;
                            //pThisW->fBrokenPipe       = false;
                            //pThisW->fPromisedWritable = false;
                            //pThisR->fPromisedWritable = false;
                            pThisW->fCreatedInheritable = RT_BOOL(fFlags & RTPIPE_C_INHERIT_WRITE);
                            pThisR->fCreatedInheritable = RT_BOOL(fFlags & RTPIPE_C_INHERIT_READ);
                            //pThisR->cUsers            = 0;
                            //pThisW->cUsers            = 0;
                            //pThisR->pbBounceBuf       = NULL;
                            //pThisW->pbBounceBuf       = NULL;
                            //pThisR->cbBounceBufUsed   = 0;
                            //pThisW->cbBounceBufUsed   = 0;
                            //pThisR->cbBounceBufAlloc  = 0;
                            //pThisW->cbBounceBufAlloc  = 0;
                            pThisR->hPollSet            = NIL_RTPOLLSET;
                            pThisW->hPollSet            = NIL_RTPOLLSET;

                            *phPipeRead  = pThisR;
                            *phPipeWrite = pThisW;
                            return VINF_SUCCESS;
                        }
                        CloseHandle(pThisR->Overlapped.hEvent);
                    }
                    RTCritSectDelete(&pThisW->CritSect);
                }
                RTCritSectDelete(&pThisR->CritSect);
            }
            RTMemFree(pThisW);
        }
        else
            rc = VERR_NO_MEMORY;
        RTMemFree(pThisR);
    }
    else
        rc = VERR_NO_MEMORY;

    CloseHandle(hPipeR);
    CloseHandle(hPipeW);
    return rc;
}


/**
 * Common worker for handling I/O completion.
 *
 * This is used by RTPipeClose, RTPipeWrite and RTPipeWriteBlocking.
 *
 * @returns IPRT status code.
 * @param   pThis               The pipe instance handle.
 */
static int rtPipeWriteCheckCompletion(RTPIPEINTERNAL *pThis)
{
    int rc;
    DWORD dwRc = WaitForSingleObject(pThis->Overlapped.hEvent, 0);
    if (dwRc == WAIT_OBJECT_0)
    {
        DWORD cbWritten = 0;
        if (GetOverlappedResult(pThis->hPipe, &pThis->Overlapped, &cbWritten, TRUE))
        {
            for (;;)
            {
                if (cbWritten >= pThis->cbBounceBufUsed)
                {
                    pThis->fIOPending = false;
                    rc = VINF_SUCCESS;
                    break;
                }

                /* resubmit the remainder of the buffer - can this actually happen? */
                pThis->cbBounceBufUsed -= cbWritten;
                memmove(&pThis->pbBounceBuf[0], &pThis->pbBounceBuf[cbWritten], pThis->cbBounceBufUsed);
                rc = ResetEvent(pThis->Overlapped.hEvent); Assert(rc == TRUE);
                if (!WriteFile(pThis->hPipe, pThis->pbBounceBuf, (DWORD)pThis->cbBounceBufUsed, &cbWritten, &pThis->Overlapped))
                {
                    DWORD const dwErr = GetLastError();
                    if (dwErr == ERROR_IO_PENDING)
                        rc = VINF_TRY_AGAIN;
                    else
                    {
                        pThis->fIOPending = false;
                        if (dwErr == ERROR_NO_DATA)
                            rc = VERR_BROKEN_PIPE;
                        else
                            rc = RTErrConvertFromWin32(GetLastError());
                        if (rc == VERR_BROKEN_PIPE)
                            pThis->fBrokenPipe = true;
                    }
                    break;
                }
                Assert(cbWritten > 0);
            }
        }
        else
        {
            pThis->fIOPending = false;
            rc = RTErrConvertFromWin32(GetLastError());
        }
    }
    else if (dwRc == WAIT_TIMEOUT)
        rc = VINF_TRY_AGAIN;
    else
    {
        pThis->fIOPending = false;
        if (dwRc == WAIT_ABANDONED)
            rc = VERR_INVALID_HANDLE;
        else
            rc = RTErrConvertFromWin32(GetLastError());
    }
    return rc;
}



RTDECL(int)  RTPipeCloseEx(RTPIPE hPipe, bool fLeaveOpen)
{
    RTPIPEINTERNAL *pThis = hPipe;
    if (pThis == NIL_RTPIPE)
        return VINF_SUCCESS;
    AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, VERR_INVALID_HANDLE);

    /*
     * Do the cleanup.
     */
    AssertReturn(ASMAtomicCmpXchgU32(&pThis->u32Magic, ~RTPIPE_MAGIC, RTPIPE_MAGIC), VERR_INVALID_HANDLE);
    RTCritSectEnter(&pThis->CritSect);
    Assert(pThis->cUsers == 0);

    if (!pThis->fRead && pThis->fIOPending)
        rtPipeWriteCheckCompletion(pThis);

    if (!fLeaveOpen && !pThis->fLeaveOpen)
        CloseHandle(pThis->hPipe);
    pThis->hPipe = INVALID_HANDLE_VALUE;

    CloseHandle(pThis->Overlapped.hEvent);
    pThis->Overlapped.hEvent = NULL;

    RTMemFree(pThis->pbBounceBuf);
    pThis->pbBounceBuf = NULL;

    RTCritSectLeave(&pThis->CritSect);
    RTCritSectDelete(&pThis->CritSect);

    RTMemFree(pThis);

    return VINF_SUCCESS;
}


RTDECL(int)  RTPipeClose(RTPIPE hPipe)
{
    return RTPipeCloseEx(hPipe, false /*fLeaveOpen*/);
}


RTDECL(int)  RTPipeFromNative(PRTPIPE phPipe, RTHCINTPTR hNativePipe, uint32_t fFlags)
{
    AssertPtrReturn(phPipe, VERR_INVALID_POINTER);
    AssertReturn(!(fFlags & ~RTPIPE_N_VALID_MASK_FN), VERR_INVALID_PARAMETER);
    AssertReturn(!!(fFlags & RTPIPE_N_READ) != !!(fFlags & RTPIPE_N_WRITE), VERR_INVALID_PARAMETER);

    /*
     * Get and validate the pipe handle info.
     */
    HANDLE hNative = (HANDLE)hNativePipe;
    AssertReturn(GetFileType(hNative) == FILE_TYPE_PIPE, VERR_INVALID_HANDLE);

    DWORD cMaxInstances;
    DWORD fInfo;
    if (!GetNamedPipeInfo(hNative, &fInfo, NULL, NULL, &cMaxInstances))
        return RTErrConvertFromWin32(GetLastError());
    /* Doesn't seem to matter to much if the pipe is message or byte type. Cygwin
       seems to hand us such pipes when capturing output (@bugref{9397}), so just
       ignore skip this check:
    AssertReturn(!(fInfo & PIPE_TYPE_MESSAGE), VERR_INVALID_HANDLE); */
    AssertReturn(cMaxInstances == 1, VERR_INVALID_HANDLE);

    DWORD cInstances;
    DWORD fState;
    if (!GetNamedPipeHandleState(hNative, &fState, &cInstances, NULL, NULL, NULL, 0))
        return RTErrConvertFromWin32(GetLastError());
    AssertReturn(!(fState & PIPE_NOWAIT), VERR_INVALID_HANDLE);
    AssertReturn(!(fState & PIPE_READMODE_MESSAGE), VERR_INVALID_HANDLE);
    AssertReturn(cInstances <= 1, VERR_INVALID_HANDLE);

    /*
     * Looks kind of OK, create a handle so we can try rtPipeQueryNtInfo on it
     * and see if we need to duplicate it to make that call work.
     */
    RTPIPEINTERNAL *pThis = (RTPIPEINTERNAL *)RTMemAllocZ(sizeof(RTPIPEINTERNAL));
    if (!pThis)
        return VERR_NO_MEMORY;
    int rc = RTCritSectInit(&pThis->CritSect);
    if (RT_SUCCESS(rc))
    {
        pThis->Overlapped.hEvent = CreateEvent(NULL, TRUE /*fManualReset*/,
                                               TRUE /*fInitialState*/, NULL /*pName*/);
        if (pThis->Overlapped.hEvent != NULL)
        {
            pThis->u32Magic             = RTPIPE_MAGIC;
            pThis->hPipe                = hNative;
            pThis->fRead                = RT_BOOL(fFlags & RTPIPE_N_READ);
            pThis->fLeaveOpen           = RT_BOOL(fFlags & RTPIPE_N_LEAVE_OPEN);
            //pThis->fIOPending         = false;
            //pThis->fZeroByteRead      = false;
            //pThis->fBrokenPipe        = false;
            //pThis->fPromisedWritable  = false;
            pThis->fCreatedInheritable  = RT_BOOL(fFlags & RTPIPE_N_INHERIT);
            //pThis->cUsers             = 0;
            //pThis->pbBounceBuf        = NULL;
            //pThis->cbBounceBufUsed    = 0;
            //pThis->cbBounceBufAlloc   = 0;
            pThis->hPollSet             = NIL_RTPOLLSET;

            HANDLE                      hNative2 = INVALID_HANDLE_VALUE;
            FILE_PIPE_LOCAL_INFORMATION Info;
            RT_ZERO(Info);
            if (   g_pfnSetHandleInformation
                && rtPipeQueryNtInfo(pThis, &Info))
                rc = VINF_SUCCESS;
            else
            {
                if (DuplicateHandle(GetCurrentProcess() /*hSrcProcess*/, hNative /*hSrcHandle*/,
                                    GetCurrentProcess() /*hDstProcess*/, &hNative2 /*phDstHandle*/,
                                    pThis->fRead ? GENERIC_READ : GENERIC_WRITE | FILE_READ_ATTRIBUTES /*dwDesiredAccess*/,
                                    !!(fFlags & RTPIPE_N_INHERIT) /*fInheritHandle*/,
                                    0 /*dwOptions*/))
                {
                    pThis->hPipe = hNative2;
                    if (rtPipeQueryNtInfo(pThis, &Info))
                    {
                        pThis->fLeaveOpen = false;
                        rc = VINF_SUCCESS;
                    }
                    else
                    {
                        rc = VERR_ACCESS_DENIED;
                        CloseHandle(hNative2);
                    }
                }
                else
                    hNative2 = INVALID_HANDLE_VALUE;
            }
            if (RT_SUCCESS(rc))
            {
                /*
                 * Verify the pipe state and correct the inheritability.
                 */
                AssertStmt(   Info.NamedPipeState == FILE_PIPE_CONNECTED_STATE
                           || Info.NamedPipeState == FILE_PIPE_CLOSING_STATE
                           || Info.NamedPipeState == FILE_PIPE_DISCONNECTED_STATE,
                           VERR_INVALID_HANDLE);
                AssertStmt(      Info.NamedPipeConfiguration
                              == (   Info.NamedPipeEnd == FILE_PIPE_SERVER_END
                                  ? (pThis->fRead ? FILE_PIPE_INBOUND  : FILE_PIPE_OUTBOUND)
                                  : (pThis->fRead ? FILE_PIPE_OUTBOUND : FILE_PIPE_INBOUND) )
                           || Info.NamedPipeConfiguration == FILE_PIPE_FULL_DUPLEX,
                           VERR_INVALID_HANDLE);
                if (   RT_SUCCESS(rc)
                    && hNative2 == INVALID_HANDLE_VALUE
                    && !g_pfnSetHandleInformation(hNative,
                                                  HANDLE_FLAG_INHERIT /*dwMask*/,
                                                  fFlags & RTPIPE_N_INHERIT ? HANDLE_FLAG_INHERIT : 0))
                {
                    rc = RTErrConvertFromWin32(GetLastError());
                    AssertMsgFailed(("%Rrc\n", rc));
                }
                if (RT_SUCCESS(rc))
                {
                    /*
                     * Ok, we're good!  If we replaced the handle, make sure it's not a standard
                     * handle if we think we need to close it.
                     */
                    if (hNative2 != INVALID_HANDLE_VALUE)
                    {
                        if (   !(fFlags & RTPIPE_N_LEAVE_OPEN)
                            && hNative != GetStdHandle(STD_INPUT_HANDLE)
                            && hNative != GetStdHandle(STD_OUTPUT_HANDLE)
                            && hNative != GetStdHandle(STD_ERROR_HANDLE) )
                            CloseHandle(hNative);
                    }
                    *phPipe = pThis;
                    return VINF_SUCCESS;
                }
            }

            /* Bail out. */
            if (hNative2 != INVALID_HANDLE_VALUE)
                CloseHandle(hNative2);
            CloseHandle(pThis->Overlapped.hEvent);
        }
        RTCritSectDelete(&pThis->CritSect);
    }
    RTMemFree(pThis);
    return rc;
}


RTDECL(RTHCINTPTR) RTPipeToNative(RTPIPE hPipe)
{
    RTPIPEINTERNAL *pThis = hPipe;
    AssertPtrReturn(pThis, -1);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, -1);

    return (RTHCINTPTR)pThis->hPipe;
}


RTDECL(int) RTPipeGetCreationInheritability(RTPIPE hPipe)
{
    RTPIPEINTERNAL *pThis = hPipe;
    AssertPtrReturn(pThis, false);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, false);

    return pThis->fCreatedInheritable;
}


RTDECL(int) RTPipeRead(RTPIPE hPipe, void *pvBuf, size_t cbToRead, size_t *pcbRead)
{
    RTPIPEINTERNAL *pThis = hPipe;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(pThis->fRead, VERR_ACCESS_DENIED);
    AssertPtr(pcbRead);
    AssertPtr(pvBuf);

    int rc = RTCritSectEnter(&pThis->CritSect);
    if (RT_SUCCESS(rc))
    {
        /* No concurrent readers, sorry. */
        if (pThis->cUsers == 0)
        {
            pThis->cUsers++;

            /*
             * Kick off a an overlapped read.  It should return immediately if
             * there are bytes in the buffer.  If not, we'll cancel it and see
             * what we get back.
             */
            rc = ResetEvent(pThis->Overlapped.hEvent); Assert(rc == TRUE);
            DWORD cbRead = 0;
            if (   cbToRead == 0
                || ReadFile(pThis->hPipe, pvBuf,
                            cbToRead <= ~(DWORD)0 ? (DWORD)cbToRead : ~(DWORD)0,
                            &cbRead, &pThis->Overlapped))
            {
                *pcbRead = cbRead;
                rc = VINF_SUCCESS;
            }
            else if (GetLastError() == ERROR_IO_PENDING)
            {
                pThis->fIOPending = true;
                RTCritSectLeave(&pThis->CritSect);

                /* We use NtCancelIoFile here because the CancelIo API
                   providing access to it wasn't available till NT4.  This
                   code needs to work (or at least load) with NT 3.1 */
                IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
                NTSTATUS rcNt = NtCancelIoFile(pThis->hPipe, &Ios);
                if (!NT_SUCCESS(rcNt))
                    WaitForSingleObject(pThis->Overlapped.hEvent, INFINITE);

                if (GetOverlappedResult(pThis->hPipe, &pThis->Overlapped, &cbRead, TRUE /*fWait*/))
                {
                    *pcbRead = cbRead;
                    rc = VINF_SUCCESS;
                }
                else if (GetLastError() == ERROR_OPERATION_ABORTED)
                {
                    *pcbRead = 0;
                    rc = VINF_TRY_AGAIN;
                }
                else
                    rc = RTErrConvertFromWin32(GetLastError());

                RTCritSectEnter(&pThis->CritSect);
                pThis->fIOPending = false;
            }
            else
                rc = RTErrConvertFromWin32(GetLastError());
            if (rc == VERR_BROKEN_PIPE)
                pThis->fBrokenPipe = true;

            pThis->cUsers--;
        }
        else
            rc = VERR_WRONG_ORDER;
        RTCritSectLeave(&pThis->CritSect);
    }
    return rc;
}


RTDECL(int) RTPipeReadBlocking(RTPIPE hPipe, void *pvBuf, size_t cbToRead, size_t *pcbRead)
{
    RTPIPEINTERNAL *pThis = hPipe;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(pThis->fRead, VERR_ACCESS_DENIED);
    AssertPtr(pvBuf);

    int rc = RTCritSectEnter(&pThis->CritSect);
    if (RT_SUCCESS(rc))
    {
        /* No concurrent readers, sorry. */
        if (pThis->cUsers == 0)
        {
            pThis->cUsers++;

            size_t cbTotalRead = 0;
            while (cbToRead > 0)
            {
                /*
                 * Kick of a an overlapped read.  It should return immediately if
                 * there is bytes in the buffer.  If not, we'll cancel it and see
                 * what we get back.
                 */
                rc = ResetEvent(pThis->Overlapped.hEvent); Assert(rc == TRUE);
                DWORD cbRead = 0;
                pThis->fIOPending = true;
                RTCritSectLeave(&pThis->CritSect);

                if (ReadFile(pThis->hPipe, pvBuf,
                             cbToRead <= ~(DWORD)0 ? (DWORD)cbToRead : ~(DWORD)0,
                             &cbRead, &pThis->Overlapped))
                    rc = VINF_SUCCESS;
                else if (GetLastError() == ERROR_IO_PENDING)
                {
                    WaitForSingleObject(pThis->Overlapped.hEvent, INFINITE);
                    if (GetOverlappedResult(pThis->hPipe, &pThis->Overlapped, &cbRead, TRUE /*fWait*/))
                        rc = VINF_SUCCESS;
                    else
                        rc = RTErrConvertFromWin32(GetLastError());
                }
                else
                    rc = RTErrConvertFromWin32(GetLastError());

                RTCritSectEnter(&pThis->CritSect);
                pThis->fIOPending = false;
                if (RT_FAILURE(rc))
                    break;

                /* advance */
                cbToRead    -= cbRead;
                cbTotalRead += cbRead;
                pvBuf        = (uint8_t *)pvBuf + cbRead;
            }

            if (rc == VERR_BROKEN_PIPE)
                pThis->fBrokenPipe = true;

            if (pcbRead)
            {
                *pcbRead = cbTotalRead;
                if (   RT_FAILURE(rc)
                    && cbTotalRead
                    && rc != VERR_INVALID_POINTER)
                    rc = VINF_SUCCESS;
            }

            pThis->cUsers--;
        }
        else
            rc = VERR_WRONG_ORDER;
        RTCritSectLeave(&pThis->CritSect);
    }
    return rc;
}


RTDECL(int) RTPipeWrite(RTPIPE hPipe, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
{
    RTPIPEINTERNAL *pThis = hPipe;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(!pThis->fRead, VERR_ACCESS_DENIED);
    AssertPtr(pcbWritten);
    AssertPtr(pvBuf);

    int rc = RTCritSectEnter(&pThis->CritSect);
    if (RT_SUCCESS(rc))
    {
        /* No concurrent writers, sorry. */
        if (pThis->cUsers == 0)
        {
            pThis->cUsers++;

            /* If I/O is pending, check if it has completed. */
            if (pThis->fIOPending)
                rc = rtPipeWriteCheckCompletion(pThis);
            else
                rc = VINF_SUCCESS;
            if (rc == VINF_SUCCESS)
            {
                Assert(!pThis->fIOPending);

                /* Adjust the number of bytes to write to fit into the current
                   buffer quota, unless we've promised stuff in RTPipeSelectOne.
                   WriteQuotaAvailable better not be zero when it shouldn't!! */
                FILE_PIPE_LOCAL_INFORMATION Info;
                if (   !pThis->fPromisedWritable
                    && cbToWrite > 0
                    && rtPipeQueryNtInfo(pThis, &Info))
                {
                    if (Info.NamedPipeState == FILE_PIPE_CLOSING_STATE)
                        rc = VERR_BROKEN_PIPE;
                    /** @todo fixme: To get the pipe writing support to work the
                     *               block below needs to be commented out until a
                     *               way is found to address the problem of the incorrectly
                     *               set field Info.WriteQuotaAvailable.
                     * Update: We now just write up to RTPIPE_NT_SIZE more.  This is quite
                     *         possibely what lead to the misunderstanding here wrt to
                     *         WriteQuotaAvailable updating. */
#if 0
                    else if (   cbToWrite >= Info.WriteQuotaAvailable
                             && Info.OutboundQuota != 0
                             && (Info.WriteQuotaAvailable || pThis->cbBounceBufAlloc)
                            )
                    {
                        cbToWrite = Info.WriteQuotaAvailable;
                        if (!cbToWrite)
                            rc = VINF_TRY_AGAIN;
                    }
#endif
                }
                pThis->fPromisedWritable = false;

                /* Do the bounce buffering. */
                if (    pThis->cbBounceBufAlloc < cbToWrite
                    &&  pThis->cbBounceBufAlloc < RTPIPE_NT_SIZE)
                {
                    if (cbToWrite > RTPIPE_NT_SIZE)
                        cbToWrite = RTPIPE_NT_SIZE;
                    void *pv = RTMemRealloc(pThis->pbBounceBuf, RT_ALIGN_Z(cbToWrite, _1K));
                    if (pv)
                    {
                        pThis->pbBounceBuf = (uint8_t *)pv;
                        pThis->cbBounceBufAlloc = RT_ALIGN_Z(cbToWrite, _1K);
                    }
                    else
                        rc = VERR_NO_MEMORY;
                }
                else if (cbToWrite > RTPIPE_NT_SIZE)
                    cbToWrite = RTPIPE_NT_SIZE;
                if (RT_SUCCESS(rc) && cbToWrite)
                {
                    memcpy(pThis->pbBounceBuf, pvBuf, cbToWrite);
                    pThis->cbBounceBufUsed = (uint32_t)cbToWrite;

                    /* Submit the write. */
                    rc = ResetEvent(pThis->Overlapped.hEvent); Assert(rc == TRUE);
                    DWORD cbWritten = 0;
                    if (WriteFile(pThis->hPipe, pThis->pbBounceBuf, (DWORD)pThis->cbBounceBufUsed,
                                  &cbWritten, &pThis->Overlapped))
                    {
                        *pcbWritten = RT_MIN(cbWritten, cbToWrite); /* paranoia^3 */
                        rc = VINF_SUCCESS;
                    }
                    else if (GetLastError() == ERROR_IO_PENDING)
                    {
                        *pcbWritten = cbToWrite;
                        pThis->fIOPending = true;
                        rc = VINF_SUCCESS;
                    }
                    else if (GetLastError() == ERROR_NO_DATA)
                        rc = VERR_BROKEN_PIPE;
                    else
                        rc = RTErrConvertFromWin32(GetLastError());
                }
                else if (RT_SUCCESS(rc))
                    *pcbWritten = 0;
            }
            else if (RT_SUCCESS(rc))
                *pcbWritten = 0;

            if (rc == VERR_BROKEN_PIPE)
                pThis->fBrokenPipe = true;

            pThis->cUsers--;
        }
        else
            rc = VERR_WRONG_ORDER;
        RTCritSectLeave(&pThis->CritSect);
    }
    return rc;
}


RTDECL(int) RTPipeWriteBlocking(RTPIPE hPipe, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
{
    RTPIPEINTERNAL *pThis = hPipe;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(!pThis->fRead, VERR_ACCESS_DENIED);
    AssertPtr(pvBuf);
    AssertPtrNull(pcbWritten);

    int rc = RTCritSectEnter(&pThis->CritSect);
    if (RT_SUCCESS(rc))
    {
        /* No concurrent writers, sorry. */
        if (pThis->cUsers == 0)
        {
            pThis->cUsers++;

            /*
             * If I/O is pending, wait for it to complete.
             */
            if (pThis->fIOPending)
            {
                rc = rtPipeWriteCheckCompletion(pThis);
                while (rc == VINF_TRY_AGAIN)
                {
                    Assert(pThis->fIOPending);
                    HANDLE hEvent = pThis->Overlapped.hEvent;
                    RTCritSectLeave(&pThis->CritSect);
                    WaitForSingleObject(hEvent, INFINITE);
                    RTCritSectEnter(&pThis->CritSect);
                }
            }
            if (RT_SUCCESS(rc))
            {
                Assert(!pThis->fIOPending);
                pThis->fPromisedWritable = false;

                /*
                 * Try write everything.
                 * No bounce buffering, cUsers protects us.
                 */
                size_t cbTotalWritten = 0;
                while (cbToWrite > 0)
                {
                    rc = ResetEvent(pThis->Overlapped.hEvent); Assert(rc == TRUE);
                    pThis->fIOPending = true;
                    RTCritSectLeave(&pThis->CritSect);

                    DWORD cbWritten = 0;
                    DWORD const cbToWriteInThisIteration = cbToWrite <= ~(DWORD)0 ? (DWORD)cbToWrite : ~(DWORD)0;
                    if (WriteFile(pThis->hPipe, pvBuf, cbToWriteInThisIteration, &cbWritten, &pThis->Overlapped))
                        rc = VINF_SUCCESS;
                    else if (GetLastError() == ERROR_IO_PENDING)
                    {
                        WaitForSingleObject(pThis->Overlapped.hEvent, INFINITE);
                        if (GetOverlappedResult(pThis->hPipe, &pThis->Overlapped, &cbWritten, TRUE /*fWait*/))
                            rc = VINF_SUCCESS;
                        else
                            rc = RTErrConvertFromWin32(GetLastError());
                    }
                    else if (GetLastError() == ERROR_NO_DATA)
                        rc = VERR_BROKEN_PIPE;
                    else
                        rc = RTErrConvertFromWin32(GetLastError());

                    RTCritSectEnter(&pThis->CritSect);
                    pThis->fIOPending = false;
                    if (RT_FAILURE(rc))
                        break;

                    /* advance */
                    if (cbWritten > cbToWriteInThisIteration) /* paranoia^3 */
                        cbWritten = cbToWriteInThisIteration;
                    pvBuf           = (char const *)pvBuf + cbWritten;
                    cbTotalWritten += cbWritten;
                    cbToWrite      -= cbWritten;
                }

                if (pcbWritten)
                {
                    *pcbWritten = cbTotalWritten;
                    if (   RT_FAILURE(rc)
                        && cbTotalWritten
                        && rc != VERR_INVALID_POINTER)
                        rc = VINF_SUCCESS;
                }
            }

            if (rc == VERR_BROKEN_PIPE)
                pThis->fBrokenPipe = true;

            pThis->cUsers--;
        }
        else
            rc = VERR_WRONG_ORDER;
        RTCritSectLeave(&pThis->CritSect);
    }
    return rc;

#if 0 /** @todo r=bird: What's this? */
    int rc = rtPipeTryBlocking(pThis);
    if (RT_SUCCESS(rc))
    {
        size_t cbTotalWritten = 0;
        while (cbToWrite > 0)
        {
            ssize_t cbWritten = write(pThis->fd, pvBuf, RT_MIN(cbToWrite, SSIZE_MAX));
            if (cbWritten < 0)
            {
                rc = RTErrConvertFromErrno(errno);
                break;
            }

            /* advance */
            pvBuf           = (char const *)pvBuf + cbWritten;
            cbTotalWritten += cbWritten;
            cbToWrite      -= cbWritten;
        }

        if (pcbWritten)
        {
            *pcbWritten = cbTotalWritten;
            if (   RT_FAILURE(rc)
                && cbTotalWritten
                && rc != VERR_INVALID_POINTER)
                rc = VINF_SUCCESS;
        }

        ASMAtomicDecU32(&pThis->u32State);
    }
    return rc;
#endif
}


RTDECL(int) RTPipeFlush(RTPIPE hPipe)
{
    RTPIPEINTERNAL *pThis = hPipe;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(!pThis->fRead, VERR_ACCESS_DENIED);

    if (!FlushFileBuffers(pThis->hPipe))
    {
        int rc = RTErrConvertFromWin32(GetLastError());
        if (rc == VERR_BROKEN_PIPE)
            pThis->fBrokenPipe = true;
        return rc;
    }
    return VINF_SUCCESS;
}


RTDECL(int) RTPipeSelectOne(RTPIPE hPipe, RTMSINTERVAL cMillies)
{
    RTPIPEINTERNAL *pThis = hPipe;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, VERR_INVALID_HANDLE);

    uint64_t const StartMsTS = RTTimeMilliTS();

    int rc = RTCritSectEnter(&pThis->CritSect);
    if (RT_FAILURE(rc))
        return rc;
    for (unsigned iLoop = 0;; iLoop++)
    {
        HANDLE  hWait = INVALID_HANDLE_VALUE;
        if (pThis->fRead)
        {
            if (pThis->fIOPending)
                hWait = pThis->Overlapped.hEvent;
            else
            {
                /* Peek at the pipe buffer and see how many bytes it contains. */
                DWORD cbAvailable;
                if (   PeekNamedPipe(pThis->hPipe, NULL, 0, NULL, &cbAvailable, NULL)
                    && cbAvailable > 0)
                {
                    rc = VINF_SUCCESS;
                    break;
                }

                /* Start a zero byte read operation that we can wait on. */
                if (cMillies == 0)
                {
                    rc = VERR_TIMEOUT;
                    break;
                }
                AssertBreakStmt(pThis->cUsers == 0, rc = VERR_INTERNAL_ERROR_5);
                rc = ResetEvent(pThis->Overlapped.hEvent); Assert(rc == TRUE);
                DWORD cbRead = 0;
                if (ReadFile(pThis->hPipe, pThis->abBuf, 0, &cbRead, &pThis->Overlapped))
                {
                    rc = VINF_SUCCESS;
                    if (iLoop > 10)
                        RTThreadYield();
                }
                else if (GetLastError() == ERROR_IO_PENDING)
                {
                    pThis->cUsers++;
                    pThis->fIOPending = true;
                    pThis->fZeroByteRead = true;
                    hWait = pThis->Overlapped.hEvent;
                }
                else
                    rc = RTErrConvertFromWin32(GetLastError());
            }
        }
        else
        {
            if (pThis->fIOPending)
            {
                rc = rtPipeWriteCheckCompletion(pThis);
                if (RT_FAILURE(rc))
                    break;
            }
            if (pThis->fIOPending)
                hWait = pThis->Overlapped.hEvent;
            else
            {
                FILE_PIPE_LOCAL_INFORMATION Info;
#if 1
                /* We can always write one bounce buffer full of data regardless of
                   the pipe buffer state.  We must of course take this into account,
                   or code like "Full write buffer" test in tstRTPipe gets confused. */
                rc = VINF_SUCCESS;
                if (rtPipeQueryNtInfo(pThis, &Info))
                {
                    /* Check for broken pipe. */
                    if (Info.NamedPipeState != FILE_PIPE_CLOSING_STATE)
                        pThis->fPromisedWritable = true;
                    else
                        rc = VERR_BROKEN_PIPE;
                }
                else
                    pThis->fPromisedWritable = true;
                break;

#else /* old code: */
                if (rtPipeQueryNtInfo(pThis, &Info))
                {
                    /* Check for broken pipe. */
                    if (Info.NamedPipeState == FILE_PIPE_CLOSING_STATE)
                    {
                        rc = VERR_BROKEN_PIPE;
                        break;
                    }

                    /* Check for available write buffer space. */
                    if (Info.WriteQuotaAvailable > 0)
                    {
                        pThis->fPromisedWritable = false;
                        rc = VINF_SUCCESS;
                        break;
                    }

                    /* delayed buffer alloc or timeout: phony promise
                       later: See if we still can associate a semaphore with
                              the pipe, like on OS/2. */
                    if (Info.OutboundQuota == 0 || cMillies)
                    {
                        pThis->fPromisedWritable = true;
                        rc = VINF_SUCCESS;
                        break;
                    }
                }
                else
                {
                    pThis->fPromisedWritable = true;
                    rc = VINF_SUCCESS;
                    break;
                }
#endif
            }
        }
        if (RT_FAILURE(rc))
            break;

        /*
         * Check for timeout.
         */
        DWORD cMsMaxWait = INFINITE;
        if (   cMillies != RT_INDEFINITE_WAIT
            && (   hWait != INVALID_HANDLE_VALUE
                || iLoop > 10)
           )
        {
            uint64_t cElapsed = RTTimeMilliTS() - StartMsTS;
            if (cElapsed >= cMillies)
            {
                rc = VERR_TIMEOUT;
                break;
            }
            cMsMaxWait = cMillies - (uint32_t)cElapsed;
        }

        /*
         * Wait.
         */
        if (hWait != INVALID_HANDLE_VALUE)
        {
            RTCritSectLeave(&pThis->CritSect);

            DWORD dwRc = WaitForSingleObject(hWait, cMsMaxWait);
            if (dwRc == WAIT_OBJECT_0)
                rc = VINF_SUCCESS;
            else if (dwRc == WAIT_TIMEOUT)
                rc = VERR_TIMEOUT;
            else if (dwRc == WAIT_ABANDONED)
                rc = VERR_INVALID_HANDLE;
            else
                rc = RTErrConvertFromWin32(GetLastError());
            if (   RT_FAILURE(rc)
                && pThis->u32Magic != RTPIPE_MAGIC)
                return rc;

            RTCritSectEnter(&pThis->CritSect);
            if (pThis->fZeroByteRead)
            {
                pThis->cUsers--;
                pThis->fIOPending = false;
                if (rc != VINF_SUCCESS)
                {
                    IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
                    NtCancelIoFile(pThis->hPipe, &Ios);
                }
                DWORD cbRead = 0;
                GetOverlappedResult(pThis->hPipe, &pThis->Overlapped, &cbRead, TRUE /*fWait*/);
            }
            if (RT_FAILURE(rc))
                break;
        }
    }

    if (rc == VERR_BROKEN_PIPE)
        pThis->fBrokenPipe = true;

    RTCritSectLeave(&pThis->CritSect);
    return rc;
}


RTDECL(int) RTPipeQueryReadable(RTPIPE hPipe, size_t *pcbReadable)
{
    RTPIPEINTERNAL *pThis = hPipe;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(pThis->fRead, VERR_PIPE_NOT_READ);
    AssertPtrReturn(pcbReadable, VERR_INVALID_POINTER);

    int rc = RTCritSectEnter(&pThis->CritSect);
    if (RT_FAILURE(rc))
        return rc;

    /** @todo The file size should give the same info and be slightly faster... */
    DWORD cbAvailable = 0;
    if (PeekNamedPipe(pThis->hPipe, NULL, 0, NULL, &cbAvailable, NULL))
    {
#if ARCH_BITS == 32
        /*
         * Kludge!
         *
         * Prior to XP SP1 (?), the returned cbAvailable value was not adjusted
         * by the read position in the current message/buffer, so it could
         * potentially be too high.  This may cause the caller to try read more
         * data than what's actually available, which may cause the read to
         * block when the caller thought it wouldn't.
         *
         * To get an accurate readable size, we have to provide an output
         * buffer and see how much we actually get back in it, as the data
         * peeking works correctly (as you would expect).
         */
        if (cbAvailable == 0 || g_enmWinVer >= kRTWinOSType_XP64)
        { /* No data available or kernel shouldn't be affected. */ }
        else
        {
            for (unsigned i = 0; ; i++)
            {
                uint8_t abBufStack[_16K];
                void   *pvBufFree = NULL;
                void   *pvBuf;
                DWORD   cbBuf     = RT_ALIGN_32(cbAvailable + i * 256, 64);
                if (cbBuf <= sizeof(abBufStack))
                {
                    pvBuf = abBufStack;
                    /* No cbBuf = sizeof(abBufStack) here! PeekNamedPipe bounce buffers the request on the heap. */
                }
                else
                {
                    pvBufFree = pvBuf = RTMemTmpAlloc(cbBuf);
                    if (!pvBuf)
                    {
                        rc = VERR_NO_TMP_MEMORY;
                        cbAvailable = 1;
                        break;
                    }
                }

                DWORD cbAvailable2 = 0;
                DWORD cbRead       = 0;
                BOOL fRc = PeekNamedPipe(pThis->hPipe, pvBuf, cbBuf, &cbRead, &cbAvailable2, NULL);
                Log(("RTPipeQueryReadable: #%u: cbAvailable=%#x cbRead=%#x cbAvailable2=%#x (cbBuf=%#x)\n",
                     i, cbAvailable, cbRead, cbAvailable2, cbBuf));

                RTMemTmpFree(pvBufFree);

                if (fRc)
                {
                    if (cbAvailable2 <= cbBuf || i >= 10)
                        cbAvailable = cbRead;
                    else
                    {
                        cbAvailable = cbAvailable2;
                        continue;
                    }
                }
                else
                {
                    rc = RTErrConvertFromWin32(GetLastError());
                    cbAvailable = 1;
                }
                break;
            }
        }
#endif
        *pcbReadable = cbAvailable;
    }
    else
        rc = RTErrConvertFromWin32(GetLastError());

    RTCritSectLeave(&pThis->CritSect);
    return rc;
}


RTDECL(int) RTPipeQueryInfo(RTPIPE hPipe, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    RTPIPEINTERNAL *pThis = hPipe;
    AssertPtrReturn(pThis, 0);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, 0);

    int rc = RTCritSectEnter(&pThis->CritSect);
    AssertRCReturn(rc, 0);

    rtPipeFakeQueryInfo(pObjInfo, enmAddAttr, pThis->fRead);

    FILE_PIPE_LOCAL_INFORMATION Info;
    if (rtPipeQueryNtInfo(pThis, &Info))
    {
        pObjInfo->cbAllocated = pThis->fRead ? Info.InboundQuota : Info.OutboundQuota;
        pObjInfo->cbObject    = pThis->fRead ? Info.ReadDataAvailable : Info.WriteQuotaAvailable;
    }

    RTCritSectLeave(&pThis->CritSect);
    return VINF_SUCCESS;
}


int rtPipePollGetHandle(RTPIPE hPipe, uint32_t fEvents, PRTHCINTPTR phNative)
{
    RTPIPEINTERNAL *pThis = hPipe;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, VERR_INVALID_HANDLE);

    AssertReturn(!(fEvents & RTPOLL_EVT_READ)  || pThis->fRead,  VERR_INVALID_PARAMETER);
    AssertReturn(!(fEvents & RTPOLL_EVT_WRITE) || !pThis->fRead, VERR_INVALID_PARAMETER);

    /* Later: Try register an event handle with the pipe like on OS/2, there is
       a file control for doing this obviously intended for the OS/2 subsys.
       The question is whether this still exists on Vista and W7. */
    *phNative = (RTHCINTPTR)pThis->Overlapped.hEvent;
    return VINF_SUCCESS;
}


/**
 * Checks for pending events.
 *
 * @returns Event mask or 0.
 * @param   pThis               The pipe handle.
 * @param   fEvents             The desired events.
 */
static uint32_t rtPipePollCheck(RTPIPEINTERNAL *pThis, uint32_t fEvents)
{
    uint32_t fRetEvents = 0;
    if (pThis->fBrokenPipe)
        fRetEvents |= RTPOLL_EVT_ERROR;
    else if (pThis->fRead)
    {
        if (!pThis->fIOPending)
        {
            DWORD cbAvailable;
            if (PeekNamedPipe(pThis->hPipe, NULL, 0, NULL, &cbAvailable, NULL))
            {
                if (   (fEvents & RTPOLL_EVT_READ)
                    && cbAvailable > 0)
                    fRetEvents |= RTPOLL_EVT_READ;
            }
            else
            {
                if (GetLastError() == ERROR_BROKEN_PIPE)
                    pThis->fBrokenPipe = true;
                fRetEvents |= RTPOLL_EVT_ERROR;
            }
        }
    }
    else
    {
        if (pThis->fIOPending)
        {
            rtPipeWriteCheckCompletion(pThis);
            if (pThis->fBrokenPipe)
                fRetEvents |= RTPOLL_EVT_ERROR;
        }
        if (   !pThis->fIOPending
            && !fRetEvents)
        {
            FILE_PIPE_LOCAL_INFORMATION Info;
            if (rtPipeQueryNtInfo(pThis, &Info))
            {
                /* Check for broken pipe. */
                if (Info.NamedPipeState == FILE_PIPE_CLOSING_STATE)
                {
                    fRetEvents = RTPOLL_EVT_ERROR;
                    pThis->fBrokenPipe = true;
                }

                /* Check if there is available buffer space. */
                if (   !fRetEvents
                    && (fEvents & RTPOLL_EVT_WRITE)
                    && (   Info.WriteQuotaAvailable > 0
                        || Info.OutboundQuota == 0)
                    )
                    fRetEvents |= RTPOLL_EVT_WRITE;
            }
            else if (fEvents & RTPOLL_EVT_WRITE)
                fRetEvents |= RTPOLL_EVT_WRITE;
        }
    }

    return fRetEvents;
}


/**
 * Internal RTPoll helper that polls the pipe handle and, if @a fNoWait is
 * clear, starts whatever actions we've got running during the poll call.
 *
 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
 *          Event mask (in @a fEvents) and no actions if the handle is ready
 *          already.
 *          UINT32_MAX (asserted) if the pipe handle is busy in I/O or a
 *          different poll set.
 *
 * @param   hPipe               The pipe handle.
 * @param   hPollSet            The poll set handle (for access checks).
 * @param   fEvents             The events we're polling for.
 * @param   fFinalEntry         Set if this is the final entry for this handle
 *                              in this poll set.  This can be used for dealing
 *                              with duplicate entries.
 * @param   fNoWait             Set if it's a zero-wait poll call.  Clear if
 *                              we'll wait for an event to occur.
 */
uint32_t rtPipePollStart(RTPIPE hPipe, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
{
    /** @todo All this polling code could be optimized to make fewer system
     *        calls; like for instance the ResetEvent calls. */
    RTPIPEINTERNAL *pThis = hPipe;
    AssertPtrReturn(pThis, UINT32_MAX);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, UINT32_MAX);
    RT_NOREF_PV(fFinalEntry);

    int rc = RTCritSectEnter(&pThis->CritSect);
    AssertRCReturn(rc, UINT32_MAX);

    /* Check that this is the only current use of this pipe. */
    uint32_t fRetEvents;
    if (   pThis->cUsers   == 0
        || pThis->hPollSet == hPollSet)
    {
        /* Check what the current events are. */
        fRetEvents = rtPipePollCheck(pThis, fEvents);
        if (   !fRetEvents
            && !fNoWait)
        {
            /* Make sure the event semaphore has been reset. */
            if (!pThis->fIOPending)
            {
                rc = ResetEvent(pThis->Overlapped.hEvent);
                Assert(rc == TRUE);
            }

            /* Kick off the zero byte read thing if applicable. */
            if (   !pThis->fIOPending
                && pThis->fRead
                && (fEvents & RTPOLL_EVT_READ)
               )
            {
                DWORD cbRead = 0;
                if (ReadFile(pThis->hPipe, pThis->abBuf, 0, &cbRead, &pThis->Overlapped))
                    fRetEvents = rtPipePollCheck(pThis, fEvents);
                else if (GetLastError() == ERROR_IO_PENDING)
                {
                    pThis->fIOPending    = true;
                    pThis->fZeroByteRead = true;
                }
                else
                    fRetEvents = RTPOLL_EVT_ERROR;
            }

            /* If we're still set for the waiting, record the poll set and
               mark the pipe used. */
            if (!fRetEvents)
            {
                pThis->cUsers++;
                pThis->hPollSet = hPollSet;
            }
        }
    }
    else
    {
        AssertFailed();
        fRetEvents = UINT32_MAX;
    }

    RTCritSectLeave(&pThis->CritSect);
    return fRetEvents;
}


/**
 * Called after a WaitForMultipleObjects returned in order to check for pending
 * events and stop whatever actions that rtPipePollStart() initiated.
 *
 * @returns Event mask or 0.
 *
 * @param   hPipe               The pipe handle.
 * @param   fEvents             The events we're polling for.
 * @param   fFinalEntry         Set if this is the final entry for this handle
 *                              in this poll set.  This can be used for dealing
 *                              with duplicate entries.  Only keep in mind that
 *                              this method is called in reverse order, so the
 *                              first call will have this set (when the entire
 *                              set was processed).
 * @param   fHarvestEvents      Set if we should check for pending events.
 */
uint32_t rtPipePollDone(RTPIPE hPipe, uint32_t fEvents, bool fFinalEntry, bool fHarvestEvents)
{
    RTPIPEINTERNAL *pThis = hPipe;
    AssertPtrReturn(pThis, 0);
    AssertReturn(pThis->u32Magic == RTPIPE_MAGIC, 0);
    RT_NOREF_PV(fFinalEntry);
    RT_NOREF_PV(fHarvestEvents);

    int rc = RTCritSectEnter(&pThis->CritSect);
    AssertRCReturn(rc, 0);

    Assert(pThis->cUsers > 0);


    /* Cancel the zero byte read. */
    uint32_t fRetEvents = 0;
    if (pThis->fZeroByteRead)
    {
        IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
        NtCancelIoFile(pThis->hPipe, &Ios);

        DWORD cbRead = 0;
        if (   !GetOverlappedResult(pThis->hPipe, &pThis->Overlapped, &cbRead, TRUE /*fWait*/)
            && GetLastError() != ERROR_OPERATION_ABORTED)
            fRetEvents = RTPOLL_EVT_ERROR;

        pThis->fIOPending    = false;
        pThis->fZeroByteRead = false;
    }

    /* harvest events. */
    fRetEvents |= rtPipePollCheck(pThis, fEvents);

    /* update counters. */
    pThis->cUsers--;
    /** @todo This isn't sane, or is it? See OS/2 impl. */
    if (!pThis->cUsers)
        pThis->hPollSet = NIL_RTPOLLSET;

    RTCritSectLeave(&pThis->CritSect);
    return fRetEvents;
}