/
qprocess_os2.cpp
1737 lines (1497 loc) · 59.8 KB
/
qprocess_os2.cpp
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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** Copyright (C) 2018 bww bitwise works GmbH. OS/2 parts.
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
//#define QPROCESS_DEBUG
#include "qplatformdefs.h"
#include <emx/umalloc.h> // for _lmalloc()
#if defined QPROCESS_DEBUG
#include "qdebug.h"
#include "qstring.h"
#include <ctype.h>
#include <qthread.h>
QT_BEGIN_NAMESPACE
// defined in qprocess.cpp
extern QByteArray qt_prettyDebug(const char *data, int len, int maxSize);
// redirect qDebug output to a file in the root directory of the current drive
static void msgHandler(QtMsgType, const QMessageLogContext &ctx, const QString &msg)
{
static FILE *f = 0;
if (!f) {
f = fopen("\\qprocess.dbg", "wb");
setbuf(f, NULL);
}
fprintf(f, "%s:%d: %s\n", ctx.function, ctx.line, msg.toLocal8Bit ().data ());
}
QT_END_NAMESPACE
#define DEBUG(a) qDebug a
#else
#define DEBUG(a) do {} while(0)
#endif
#include "qprocess.h"
#include "qprocess_p.h"
#include <qglobal.h>
#include <private/qcoreapplication_p.h>
#include <private/qthread_p.h>
#include <private/qsystemerror_p.h>
#include <qdatetime.h>
#include <qfile.h>
#include <qfileinfo.h>
#include <qhash.h>
#include <qmutex.h>
#include <qdir.h>
#define HF_STDIN HFILE(0)
#define HF_STDOUT HFILE(1)
#define HF_STDERR HFILE(2)
QT_BEGIN_NAMESPACE
// defined in qcoreapplication.cpp
extern QString qAppFileName();
#if QT_CONFIG(process)
// NOTE: Copied over from qprocess_unix.cpp.
QProcessEnvironment QProcessEnvironment::systemEnvironment()
{
QProcessEnvironment env;
const char *entry;
for (int count = 0; (entry = environ[count]); ++count) {
const char *equal = strchr(entry, '=');
if (!equal)
continue;
QByteArray name(entry, equal - entry);
QByteArray value(equal + 1);
env.d->vars.insert(QProcessEnvironmentPrivate::Key(name),
QProcessEnvironmentPrivate::Value(value));
}
return env;
}
enum
{
PIPE_SIZE_STDIN = 65512, // max (at least on eCS)
PIPE_SIZE_STDOUT = 65512, // max (at least on eCS)
PIPE_SIZE_STDERR = 4096,
};
class QProcessManager : public QThread
{
public:
enum { InvalidProcKey = USHORT(~0), MaxProcKey = (USHORT(~0) >> 2) };
static void addRef();
static void release();
static USHORT addProcess(QProcess *process);
static void removeProcess(USHORT procKey);
static QMutex *pipeStateLock() {
Q_ASSERT(instance);
return &instance->pipeStatLock;
}
private:
QProcessManager();
~QProcessManager();
void installSigHandler();
void uninstallSigHandler();
void run();
int refcnt;
bool finish;
HEV eventSem;
QAtomicInt eventSemGuard;
QAtomicInt deathFlag;
QMutex pipeStatLock;
typedef QHash<USHORT, QProcess *> ProcessList;
ProcessList processes;
USHORT lastProcKey;
void (*sa_old_sigchld_handler)(int);
static void sa_sigchld_handler(int signum);
static USHORT toPipeKey(USHORT procKey, QProcessPrivate::PipeType type) {
Q_ASSERT((procKey << 2) >> 2 == procKey);
return (procKey << 2) | type;
}
static USHORT toProcKey(USHORT key) { return key >> 2; }
static QProcessPrivate::PipeType toPipeType(USHORT key) {
return QProcessPrivate::PipeType(key & 0x3);
}
static QProcessManager *instance;
static QMutex mutex;
};
// static
QProcessManager *QProcessManager::instance = 0;
QMutex QProcessManager::mutex;
// static
void QProcessManager::sa_sigchld_handler(int signum)
{
#if defined (QPROCESS_DEBUG)
//fprintf(stderr, "*** SIGCHLD\n");
#endif
Q_ASSERT(instance);
// eventSemGuard is used as follows:
// 0 - QProcessManager is not operational
// 1 - QProcessManager is being run, eventSem is fine
// 2 - another signal handler is in action
if (!instance->eventSemGuard.testAndSetAcquire(1, 2))
return;
// set deathFlag to 1 and post the semaphore if not already done so
if (instance->deathFlag.testAndSetRelaxed(0, 1)) {
APIRET rc = DosPostEventSem(instance->eventSem);
Q_ASSERT(rc == NO_ERROR || rc == ERROR_ALREADY_POSTED);
Q_UNUSED(rc);
}
instance->eventSemGuard.testAndSetRelease(2, 1);
if (instance->sa_old_sigchld_handler &&
instance->sa_old_sigchld_handler != SIG_IGN)
instance->sa_old_sigchld_handler(signum);
}
// static
void QProcessManager::addRef()
{
QMutexLocker locker(&mutex);
if (instance == 0) {
instance = new QProcessManager();
}
++instance->refcnt;
}
// static
void QProcessManager::release()
{
QMutexLocker locker(&mutex);
Q_ASSERT(instance);
if (--instance->refcnt == 0) {
// make sure we don't globally exist anymore before leaving the lock
QProcessManager *instance = QProcessManager::instance;
QProcessManager::instance = 0;
// disable the signal handler and stop the thread if necessary
if (instance->isRunning()) {
Q_ASSERT(instance->eventSemGuard == 1 || instance->eventSemGuard == 2);
while (!instance->eventSemGuard.testAndSetRelease(1, 0))
DosSleep(0);
instance->uninstallSigHandler();
// stop the thread
instance->finish = true;
locker.unlock();
DosPostEventSem(instance->eventSem);
instance->wait();
}
delete instance;
}
}
// static
USHORT QProcessManager::addProcess(QProcess *process)
{
DEBUG(("%p", process));
QMutexLocker locker(&mutex);
Q_ASSERT(instance);
// lazily enable SIGCHLD handler and start the worker
if (instance->eventSemGuard.testAndSetAcquire(0, 1)) {
instance->installSigHandler();
instance->start();
}
QProcessPrivate *d = process->d_func();
USHORT procKey = instance->lastProcKey + 1;
if (procKey > MaxProcKey) {
// limit reached, find an unused number
procKey = 0;
while (++procKey <= MaxProcKey &&
instance->processes.contains(procKey));
Q_ASSERT(procKey <= MaxProcKey);
if (procKey > MaxProcKey) {
// oops, no more free keys!
locker.unlock();
d->setErrorAndEmit(QProcess::FailedToStart,
QProcess::tr("Resource error: Too many processes"));
return InvalidProcKey;
}
} else {
instance->lastProcKey = procKey;
}
// attach the semahpore to the pipes of the process
APIRET arc = NO_ERROR;
if (d->stdinChannel.type == QProcessPrivate::Channel::Normal &&
d->stdinChannel.pipe.server != INVALID_HPIPE) {
arc = DosSetNPipeSem(d->stdinChannel.pipe.server, (HSEM)instance->eventSem,
toPipeKey(procKey, QProcessPrivate::InPipe));
}
if (arc == NO_ERROR &&
d->stdoutChannel.type == QProcessPrivate::Channel::Normal &&
d->stdoutChannel.pipe.server != INVALID_HPIPE) {
arc = DosSetNPipeSem(d->stdoutChannel.pipe.server, (HSEM)instance->eventSem,
toPipeKey(procKey, QProcessPrivate::OutPipe));
}
if (arc == NO_ERROR &&
d->stderrChannel.type == QProcessPrivate::Channel::Normal &&
d->stderrChannel.pipe.server != INVALID_HPIPE) {
arc = DosSetNPipeSem(d->stderrChannel.pipe.server, (HSEM)instance->eventSem,
toPipeKey(procKey, QProcessPrivate::ErrPipe));
}
if (arc != NO_ERROR) {
if (procKey == instance->lastProcKey)
--instance->lastProcKey;
locker.unlock();
d->setErrorAndEmit(QProcess::FailedToStart,
QProcess::tr("Resource error: %1").arg(QSystemError::os2String(arc)));
return InvalidProcKey;
}
instance->processes[procKey] = process;
return procKey;
}
// static
void QProcessManager::removeProcess(USHORT procKey)
{
QMutexLocker locker(&mutex);
Q_ASSERT(instance);
Q_ASSERT(instance->processes.contains(procKey));
QProcess *process = instance->processes[procKey];
DEBUG(("%p", process));
// to guarantee that the given procKey may be reused, we must close all
// pipes in order to ensure that we won't get late NPSS_CLOSE for the
// removed process with the key that may be already associated with a new one
QProcessPrivate *d = process->d_func();
d->closeChannel(&d->stdinChannel);
d->closeChannel(&d->stdoutChannel);
d->closeChannel(&d->stderrChannel);
instance->processes.remove(procKey);
// small optimization: released the highest key
if (procKey == instance->lastProcKey)
--instance->lastProcKey;
}
QProcessManager::QProcessManager()
: refcnt(0), finish(false), eventSem(NULLHANDLE), sa_old_sigchld_handler(0)
{
DEBUG(());
APIRET rc = DosCreateEventSem(NULL, &eventSem,
DC_SEM_SHARED | DCE_AUTORESET | DCE_POSTONE,
FALSE);
Q_ASSERT(rc == NO_ERROR);
Q_UNUSED(rc);
lastProcKey = InvalidProcKey;
}
QProcessManager::~QProcessManager()
{
DEBUG(());
Q_ASSERT(!refcnt);
Q_ASSERT(!processes.size());
DosCloseEventSem(eventSem);
}
void QProcessManager::installSigHandler()
{
// set up the SIGCHLD handler which posts a semaphore whenever
// our child dies
struct sigaction oldAction;
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_handler = sa_sigchld_handler;
action.sa_flags = SA_NOCLDSTOP;
::sigaction(SIGCHLD, &action, &oldAction);
if (oldAction.sa_handler != sa_sigchld_handler)
sa_old_sigchld_handler = oldAction.sa_handler;
}
void QProcessManager::uninstallSigHandler()
{
struct sigaction oldAction;
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_handler = sa_old_sigchld_handler;
action.sa_flags = SA_NOCLDSTOP;
::sigaction(SIGCHLD, &action, &oldAction);
if (oldAction.sa_handler != sa_sigchld_handler) {
::sigaction(SIGCHLD, &oldAction, 0);
}
}
void QProcessManager::run()
{
DEBUG(() << "BEGIN");
// Note: the rationale behind using a worker thread for death detection is
// that calling complex functions from a signal handler is not really a good
// idea unless there is a 100% guarantee that they are reentrant. So, the
// handler only posts a semaphore (I *hope* DosPostEventSem is reentrant)
// and all complex work is done here asynchronously.
QMutexLocker locker(&mutex);
APIRET arc;
// an array for 1 process is initially enough
int pipeStatesSize = sizeof(PIPESEMSTATE) * (3 * 2 + 1);
PPIPESEMSTATE pipeStates = (PPIPESEMSTATE)::_lmalloc(pipeStatesSize);
do {
locker.unlock();
qDosNI(arc = DosWaitEventSem(eventSem, SEM_INDEFINITE_WAIT));
locker.relock();
if (finish)
break;
if (instance->deathFlag.testAndSetRelaxed(1, 0)) {
DEBUG(() << "child death signaled");
for (QProcess *proc : processes) {
DEBUG(() << "pid" << proc->d_func()->pid << "waitMode" << hex << proc->d_func()->waitMode);
if (proc->d_func()->waitMode) {
DosPostEventSem(proc->d_func()->waitSem);
} else {
QMetaObject::invokeMethod(proc, "_q_notified", Qt::QueuedConnection,
Q_ARG(int, QProcessPrivate::CanDie));
}
}
}
// we have no running processes, start over (note that QProcessPrivate
// will release us on destruction and this will cause thread termination)
if (processes.size() == 0)
continue;
DEBUG(() << "checking pipes");
// make sure the state array is big enough. The best size for sz pipes
// is sz * 2 (to be able to store both NPSS_RDATA/NPSS_WSPACE and
// NPSS_CLOSE for every pipe) + one for NPSS_EOI
int bestSize = sizeof(PIPESEMSTATE) * (processes.size() * 3 * 2 + 1);
if (pipeStatesSize < bestSize) {
pipeStates = (PPIPESEMSTATE)_lrealloc(pipeStates, bestSize);
pipeStatesSize = bestSize;
}
// Note: OS/2 posts the semaphore once for each new pipe event but
// DosQueryNPipeSemState() returns all previous events (already posted
// on their own) that are still up to date. This makes it impossible to
// distinguish between the repeated events and unique ones here. This is
// done in _q_notified() using some heuristic. Due to the same reason of
// duplicate events we do a lock here to be in sync with writeToStdin().
// Note that all this hassle would not be necessary at all if there were
// a method to get the number of free bytes in the write buf of the pipe
// (similar to DosPeekNPipe() that checks the read buf) but there isn't.
QMutexLocker lock(pipeStateLock());
arc = DosQueryNPipeSemState((HSEM)eventSem, pipeStates, pipeStatesSize);
if (arc != NO_ERROR) {
qWarning("QProcessManager::run: DosQueryNPipeSemState returned %lu", arc);
continue;
}
// In the returned information array, CLOSE and READ records for the
// same pipe key may be mixed. We need CLOSE messages to be posted after
// READ messages, so we do two passes.
// @todo We don't need two passes any more!
int pass = 0;
for (int i = 0; pass < 2; ++i) {
BYTE status = pipeStates[i].fStatus;
if (status == NPSS_EOI) {
++ pass;
i = -1;
continue;
}
if (pass == 0 && status != NPSS_RDATA && status != NPSS_WSPACE)
continue;
if (pass == 1 && status != NPSS_CLOSE)
continue;
DEBUG((" %d/%d: fStatus %u fFlag %02X usKey %04hX usAvail %hu",
pass, i, (uint) pipeStates[i].fStatus,
(uint) pipeStates[i].fFlag, pipeStates[i].usKey,
pipeStates[i].usAvail));
int procKey = toProcKey(pipeStates[i].usKey);
QProcessPrivate::PipeType type = toPipeType(pipeStates[i].usKey);
QProcess *proc = processes[procKey];
Q_ASSERT(proc);
DEBUG((" process %p pid %d type %d", proc, proc->d_func()->pid, type));
int flags = 0;
switch(type) {
case QProcessPrivate::InPipe:
Q_ASSERT(status == NPSS_CLOSE || status == NPSS_WSPACE);
flags |= QProcessPrivate::CanWrite;
// save the current number of free bytes in the pipe to let
// _q_canWrite() go (this is also used in tryCloseStdinPipe())
proc->d_func()->pipes[type]->bytes = pipeStates[i].usAvail;
break;
case QProcessPrivate::OutPipe:
Q_ASSERT(status == NPSS_CLOSE || status == NPSS_RDATA);
flags |= QProcessPrivate::CanReadStdOut;
break;
case QProcessPrivate::ErrPipe:
Q_ASSERT(status == NPSS_CLOSE || status == NPSS_RDATA);
flags |= QProcessPrivate::CanReadStdErr;
break;
}
if (proc->d_func()->waitMode) {
DosPostEventSem(proc->d_func()->waitSem);
} else {
QMetaObject::invokeMethod(proc, "_q_notified", Qt::QueuedConnection,
Q_ARG(int, flags));
}
}
} while (true);
::free(pipeStates);
DEBUG(() << "END");
}
void QProcessPrivate::init()
{
waitMode = 0;
waitSem = NULLHANDLE;
procKey = QProcessManager::InvalidProcKey;
QProcessManager::addRef();
}
void QProcessPrivate::uninit()
{
QProcessManager::release();
if (waitSem != NULLHANDLE)
DosCloseEventSem(waitSem);
}
void QProcessPrivate::ensureWaitSem()
{
if (waitSem == NULLHANDLE) {
APIRET rc = DosCreateEventSem(0, &waitSem, DCE_AUTORESET, FALSE);
Q_ASSERT(rc == NO_ERROR);
Q_UNUSED(rc);
}
}
bool QProcessPrivate::createPipe(PipeType type, Channel::Pipe &pipe,
const char *name /*= 0*/)
{
APIRET arc = NO_ERROR;
char pathBuf[CCHMAXPATH];
// we need the process identifier to guarantee pipe name unicity
PPIB ppib = NULL;
DosGetInfoBlocks(NULL, &ppib);
switch (type) {
case InPipe:
// create our end of the pipe
sprintf(pathBuf, "\\pipe\\Qt5\\%08lX\\QProcess\\%p\\%s",
ppib->pib_ulpid, this->q_func(), name ? name : "Stdin");
arc = DosCreateNPipe(pathBuf, &pipe.server,
NP_ACCESS_OUTBOUND | NP_NOINHERIT,
NP_NOWAIT | NP_TYPE_BYTE | 1,
PIPE_SIZE_STDIN, 0, 0);
if (arc == NO_ERROR) {
DosConnectNPipe(pipe.server);
// ensure the other end blocks (vital for process->process redirections)
DosSetNPHState(pipe.server, NP_WAIT);
// open the client end of the pipe
ULONG action = 0;
arc = DosOpen(pathBuf, &pipe.client, &action, 0, FILE_NORMAL, FILE_OPEN,
OPEN_ACCESS_READONLY | OPEN_SHARE_DENYREADWRITE |
OPEN_FLAGS_NOINHERIT, (PEAOP2)NULL);
if (arc == NO_ERROR) {
// set the initial number of free bytes
pipe.bytes = PIPE_SIZE_STDIN;
}
}
break;
case OutPipe:
case ErrPipe:
// create our end of the pipe
sprintf(pathBuf, "\\pipe\\Qt5\\%08lX\\QProcess\\%p\\%s",
ppib->pib_ulpid, this->q_func(),
name ? name : type == OutPipe ? "Stdout" : "Stderr");
arc = DosCreateNPipe(pathBuf, &pipe.server,
NP_ACCESS_INBOUND | NP_NOINHERIT,
NP_NOWAIT | NP_TYPE_BYTE | 1,
0, type == OutPipe ? PIPE_SIZE_STDOUT : PIPE_SIZE_STDERR, 0);
if (arc == NO_ERROR) {
DosConnectNPipe(pipe.server);
// ensure the other end blocks (vital for process->process redirections)
DosSetNPHState(pipe.server, NP_WAIT);
// open the client end of the pipe
ULONG action = 0;
arc = DosOpen(pathBuf, &pipe.client, &action, 0, FILE_NORMAL, FILE_OPEN,
OPEN_ACCESS_WRITEONLY | OPEN_SHARE_DENYREADWRITE |
OPEN_FLAGS_NOINHERIT, (PEAOP2)NULL);
}
break;
}
if (arc != NO_ERROR) {
qWarning("QProcessPrivate::createPipe: %s(%s) returned %lu",
pipe.server == INVALID_HPIPE ? "DosCreateNPipe" : "DosOpen",
pathBuf, arc);
setErrorAndEmit(QProcess::FailedToStart,
QProcess::tr("Resource error: %1").arg(QSystemError::os2String(arc)));
}
return arc == NO_ERROR;
}
void QProcessPrivate::destroyPipe(Channel::Pipe &pipe)
{
pipe.bytes = 0;
pipe.signaled = false;
pipe.closePending = false;
if (pipe.client != INVALID_HFILE) {
DosClose(pipe.client);
pipe.client = INVALID_HFILE;
}
if (pipe.server != INVALID_HPIPE) {
// Note: We do not call DosDisConnectNPipe() as this is not necessary
// and will only cause DosRead() on the other side to return
// ERROR_PIPE_NOT_CONNECTED that will be interpreted by LIBC read() and
// fread() as an error (ferror() will return true) and some programs
// don't like it (e.g. 7z, rar32 when reading data from stdin).
DosClose(pipe.server);
pipe.server = INVALID_HPIPE;
}
}
void QProcessPrivate::closeChannel(Channel *channel)
{
destroyPipe(channel->pipe);
}
/*
Create the pipes to a QProcessPrivate::Channel.
This function must be called in order: stdin, stdout, stderr
*/
bool QProcessPrivate::openChannel(Channel &channel)
{
DEBUG(() << "type" << channel.type);
PipeType type;
if (&channel == &stdinChannel) {
type = InPipe;
if (inputChannelMode == QProcess::ForwardedInputChannel)
return true;
} else if (&channel == &stdoutChannel) {
type = OutPipe;
if (processChannelMode == QProcess::ForwardedChannels ||
processChannelMode == QProcess::ForwardedOutputChannel)
return true;
} else if (&channel == &stderrChannel) {
type = ErrPipe;
if (processChannelMode == QProcess::MergedChannels ||
processChannelMode == QProcess::ForwardedChannels ||
processChannelMode == QProcess::ForwardedErrorChannel)
return true;
} else {
Q_ASSERT(false);
return false;
}
if (channel.type == Channel::Normal) {
// we're piping this channel to our own process
return createPipe(type, channel.pipe);
} else if (channel.type == Channel::Redirect) {
// we're redirecting the channel to/from a file
QByteArray fname = QFile::encodeName(channel.file);
DEBUG(() << "fname" << fname);
APIRET rc;
if (&channel == &stdinChannel) {
// try to open in read-only mode
ULONG action = 0;
rc = DosOpen(fname, &channel.pipe.client, &action, 0, FILE_NORMAL, FILE_OPEN,
OPEN_ACCESS_READONLY | OPEN_SHARE_DENYNONE | OPEN_FLAGS_NOINHERIT, (PEAOP2)NULL);
if (rc == NO_ERROR)
return true; // success
DEBUG(() << "DosOpen rc" << rc);
setErrorAndEmit(QProcess::FailedToStart,
QProcess::tr("Could not open input redirection for reading"));
} else {
int mode = FILE_CREATE;
if (channel.append)
mode |= FILE_OPEN;
else
mode |= FILE_TRUNCATE;
ULONG action = 0;
rc = DosOpen(fname, &channel.pipe.client, &action, 0, FILE_NORMAL, mode,
OPEN_ACCESS_WRITEONLY | OPEN_SHARE_DENYWRITE |
OPEN_FLAGS_NOINHERIT, (PEAOP2)NULL);
if (rc == NO_ERROR && channel.append) {
ULONG actual = 0;
rc = DosSetFilePtr(channel.pipe.client, 0, FILE_END, &actual);
}
if (rc == NO_ERROR)
return true; // success
DEBUG(() << "DosOpen rc" << rc);
setErrorAndEmit(QProcess::FailedToStart,
QProcess::tr("Could not open output redirection for writing"));
}
return false;
} else {
Q_ASSERT_X(channel.process, "QProcess::start", "Internal error");
// the first process started is the server, the second one is the client.
// the server stores handles to both ends in its channel.pipe member;
// the other part will pickup the handle of the client end from there.
if (channel.type == Channel::PipeSource) {
// we are the source
Q_ASSERT(&channel == &stdoutChannel);
Q_ASSERT(channel.process->stdinChannel.process == this &&
channel.process->stdinChannel.type == Channel::PipeSink);
if (channel.process->stdinChannel.pipe.server != INVALID_HPIPE) {
// the other process has already started and became the server
} else {
// note: InPipe, since the type is relative to the other side
createPipe(InPipe, channel.pipe, "Source");
}
} else {
// we are the sink (and the server)
Q_ASSERT(channel.type == Channel::PipeSink);
Q_ASSERT(&channel == &stdinChannel);
Q_ASSERT(channel.process->stdoutChannel.process == this &&
channel.process->stdoutChannel.type == Channel::PipeSource);
if (channel.process->stdoutChannel.pipe.server != INVALID_HPIPE) {
// the other process has already started and became the server
} else {
// note: OutPipe, since the type is relative to the other side
createPipe(OutPipe, channel.pipe, "Sink");
}
}
return true;
}
}
static int qt_startProcess(const QString &program, const QStringList &arguments,
const QString &workingDirectory,
const QStringList *environment, bool detached = false)
{
int mode = detached ? P_SESSION : P_NOWAIT;
// Create argument list with right number of elements (one extra is for
// the program name and one for the terminating 0). We also reserve 3
// elements in front of the array for a posssible command processor call
// insertion.
const char **argvBase = new const char *[arguments.count() + 2 + 3];
// Don't use leading elements by default
const char **argv = argvBase + 3;
// Set the final argument to 0
argv[arguments.count() + 1] = 0;
// Encode the program name.
QByteArray programName = QFile::encodeName(program);
// Add the program name to the argument list.
argv[0] = programName.data();
// Add every argument to the list
for (int i = 0; i < arguments.count(); ++i) {
QString arg = arguments.at(i);
argv[i + 1] = qstrdup(arg.toLocal8Bit().constData());
}
// Duplicate the environment.
int envc = 0;
char **envv;
if (environment && environment->count()) {
bool seenPATH = false;
bool seenCOMSPEC = false;
envv = new char *[environment->count() + 1 + 2 /* may be PATH + COMSPEC */];
for (; envc < environment->count(); ++envc) {
QString item = environment->at(envc);
envv[envc] = qstrdup(item.toLocal8Bit().constData());
if (!seenPATH)
seenPATH = !qstrncmp(envv[envc], "PATH=", 4);
if (!seenCOMSPEC)
seenCOMSPEC = !qstrncmp(envv[envc], "COMSPEC=", 8);
}
if (!seenPATH) {
// inherit PATH if missing (for convenience)
// (note that BEGINLIBPATH and ENDLIBPATH, if any, are automatically
// inherited, while LIBPATH is always a global setting)
QByteArray path = qgetenv("PATH");
path.prepend("PATH=");
envv[envc++] = qstrdup(path);
}
// inherit COMSPEC if missing (to let the child start .cmd and .bat)
if (!seenCOMSPEC) {
QByteArray comspec = qgetenv("COMSPEC");
comspec.prepend("COMSPEC=");
envv[envc++] = qstrdup(comspec);
}
envv[envc] = 0;
} else {
// inherit the parent environment
envv = environ;
}
// Set the working directory if it's non-empty
QString curDir;
if (!workingDirectory.isEmpty()) {
curDir = QDir::currentPath();
QDir::setCurrent(workingDirectory);
}
DEBUG(("workdir is \"%s\"", qPrintable(QDir::currentPath())));
// try to find the executable
QByteArray fullProgramName(CCHMAXPATH * 2, 0);
int rc = -1;
errno = ENOENT;
// don't go further if we got an empty program name: a file with such a name
// cannot exist on OS/2 and many QFileInfo funcs are undefined for this case
// (and we will simply return ENOENT to the caller if so)
if (!programName.isEmpty()) {
// While it's tempting to use a nice kLIBC _path2 function here, we
// don't do it because it a) doesn't search the current dir if no path
// info is given; b) doesn't resolve /@unixroot (and symlinks) to a real
// OS/2 path and we might need it for the DosStartSession case.
APIRET arc;
QFileInfo programInfo(program);
QStringList knownExts;
knownExts << QLatin1String("exe") << QLatin1String("cmd")
<< QLatin1String("bat"); // in order of CMD.EXE's precedence
QDir dir = programInfo.dir();
bool hasPath = dir.path() != QLatin1String(".");
QByteArray path;
// Use canonicalPath to resolve /@unixroot and symlinks if program has
// path information. If canonicalPath returns an empty string, this
// means "path not found", so we will stay with ENOENT in such a case.
if (!hasPath ||
!(path = QFile::encodeName(QDir::toNativeSeparators(dir.canonicalPath()))).isEmpty()) {
// run through all known exe extensions (+ no extension case)
for (int i = 0; i <= knownExts.size(); ++i) {
QByteArray name;
if (i == 0) {
// no extension case, only if a known extension is already there
if (knownExts.contains(programInfo.suffix(), Qt::CaseInsensitive))
name = QFile::encodeName(programInfo.fileName());
else
continue;
} else {
name = QFile::encodeName(programInfo.fileName() +
QLatin1String(".") + knownExts[i-1]);
}
if (hasPath) {
arc = DosSearchPath(0, path, name, fullProgramName.data(), fullProgramName.size());
} else {
arc = DosSearchPath(SEARCH_IGNORENETERRS | SEARCH_ENVIRONMENT |
SEARCH_CUR_DIRECTORY, "PATH",
name, fullProgramName.data(), fullProgramName.size());
}
if (arc == NO_ERROR) {
rc = 0;
break;
}
if (arc != ERROR_FILE_NOT_FOUND && arc != ERROR_PATH_NOT_FOUND) {
qWarning("qt_startProcess: DosSearchPath(%s) returned %lu",
qPrintable(QFile::decodeName(name)), arc);
break;
}
}
}
}
DEBUG(("found \"%s\" for \"%s\"",
qPrintable(QFile::decodeName(fullProgramName)),
qPrintable(QFile::decodeName(programName))));
int pid = -1;
if (rc != -1) {
// add the program's dir to BEGINLIBPATH to make sure the DLLs are
// serached there first (no, the OS/2 loader does't do it itself)
QFileInfo fullProgramInfo(QFile::decodeName(fullProgramName));
QString fullPath = QDir::toNativeSeparators(fullProgramInfo.absolutePath());
APIRET arc;
QStringList paths;
char libPathBuf[4096]; // @todo isn't it too small?
bool prependedLibPath = false;
arc = DosQueryExtLIBPATH(libPathBuf, BEGIN_LIBPATH);
Q_ASSERT(arc == NO_ERROR);
if (arc == NO_ERROR) {
QString path = QFile::decodeName(libPathBuf);
paths = path.split(QLatin1Char(';'), QString::SkipEmptyParts);
if (paths.contains(fullPath, Qt::CaseInsensitive)) {
DEBUG(("\"%s\" is already in BEGINLIBPATH",
qPrintable(fullPath)));
} else {
DEBUG(("prepending \"%s\" to BEGINLIBPATH",
qPrintable(fullPath)));
prependedLibPath = true;
QByteArray newLibPath = libPathBuf;
newLibPath.prepend(';').prepend(QFile::encodeName(fullPath));
DosSetExtLIBPATH(newLibPath, BEGIN_LIBPATH);
}
}
const char *programReal = fullProgramName.data();
const char **argvReal = argv;
if (mode == P_SESSION) {
// @todo P_SESSION isn't supported by kLIBC atm, use DosStartSession
// below
} else {
// get the application type of our program (note that we cannot use
// DosGetInfoBlocks/PIB because it could be overwritten there by e.g.
// morphing from VIO to PM which doesn't cancel the fact that we
// are VIO from the OS/2 loader's POV.
ULONG flags;
arc = DosQueryAppType(QFile::encodeName(qAppFileName()), &flags);
if (arc == NO_ERROR && (flags & 0x7) != FAPPTYP_WINDOWAPI) {
// we are originally not the PM application and thus DosExecPgm()
// won't be able to start PM applications directly (note that the
// other way around it works although undocumented). Check what
// the target program is.
arc = DosQueryAppType(fullProgramName, &flags);
if (arc == NO_ERROR && (flags & 0x7) == FAPPTYP_WINDOWAPI) {
// its PM, we need a proxy
// @todo use P_SESSION once it's implemented in kLIBC!
// @todo check if FS VIO apps need a proxy
programReal = ::getenv("COMSPEC"); // returns static!
if (programReal == 0)
programReal = "cmd.exe";
argvReal = argvBase + 1;
argvReal[0] = programReal;
argvReal[1] = "/c";
argv[0] = fullProgramName.data();
}
}
}
#if defined(QPROCESS_DEBUG)
DEBUG(("executable \"%s\"",
qPrintable(QFile::decodeName(programReal))));
for (int i = 0; argvReal[i]; ++i) {
DEBUG((" arg[%d] \"%s\"",
i, qPrintable(QFile::decodeName(argvReal[i]))));
}
#endif
// finally, start the thing (note that due to the incorrect definiton of
// spawnve we have to perform a pointless cast; the devinition for the
// 3rd and 4th arg should be: char const * const *)
if (mode == P_SESSION) {
// @todo P_SESSION isn't supported by kLIBC atm, use DosStartSession
bool needCmd = false;
int dot = fullProgramName.lastIndexOf('.');
Q_ASSERT(dot > 0);
if (dot > 0)
needCmd = qstricmp(fullProgramName.data() + dot, ".cmd") == 0 ||
qstricmp(fullProgramName.data() + dot, ".bat") == 0;
QByteArray args;
for (const QString &arg : arguments) {
if (!args.isEmpty())
args += ' ';
if (!arg.isEmpty())
args += '"' + QFile::encodeName(arg) + '"';
}