]> git.saurik.com Git - wxWidgets.git/blame - src/msw/utilsexc.cpp
Add more checks for wxUSE_DYNLIB_CLASS to wxMSW.
[wxWidgets.git] / src / msw / utilsexc.cpp
CommitLineData
32592631 1/////////////////////////////////////////////////////////////////////////////
9cd03a43 2// Name: src/msw/utilsexc.cpp
79066131 3// Purpose: wxExecute implementation for MSW
32592631
GL
4// Author: Julian Smart
5// Modified by:
6// Created: 04/01/98
7// RCS-ID: $Id$
77ffb593 8// Copyright: (c) 1998-2002 wxWidgets dev team
65571936 9// Licence: wxWindows licence
32592631
GL
10/////////////////////////////////////////////////////////////////////////////
11
b568d04f
VZ
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
32592631
GL
20// For compilers that support precompilation, includes "wx.h".
21#include "wx/wxprec.h"
22
23#ifdef __BORLANDC__
b568d04f 24 #pragma hdrstop
32592631
GL
25#endif
26
27#ifndef WX_PRECOMP
b568d04f
VZ
28 #include "wx/utils.h"
29 #include "wx/app.h"
30 #include "wx/intl.h"
068a7cfe 31 #include "wx/log.h"
530ecef0
WS
32 #if wxUSE_STREAMS
33 #include "wx/stream.h"
34 #endif
02761f6c 35 #include "wx/module.h"
2ae8a353 36#endif
32592631 37
eccd1992 38#include "wx/process.h"
204abcd4 39#include "wx/thread.h"
e2478fde 40#include "wx/apptrait.h"
dbbcfbb6 41#include "wx/evtloop.h"
5a8561fc 42#include "wx/vector.h"
e2478fde 43
eccd1992 44
32592631 45#include "wx/msw/private.h"
dbeac4bd 46
32592631
GL
47#include <ctype.h>
48
f172cb82 49#if !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
b568d04f 50 #include <direct.h>
17dff81c 51#ifndef __MWERKS__
b568d04f 52 #include <dos.h>
32592631 53#endif
17dff81c 54#endif
32592631 55
b39dbf34 56#if defined(__GNUWIN32__)
b568d04f
VZ
57 #include <sys/unistd.h>
58 #include <sys/stat.h>
57c208c5 59#endif
32592631 60
eccd1992
VZ
61#if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
62 #ifndef __UNIX__
63 #include <io.h>
64 #endif
32592631 65
eccd1992
VZ
66 #ifndef __GNUWIN32__
67 #include <shellapi.h>
68 #endif
32592631
GL
69#endif
70
71#include <stdio.h>
72#include <stdlib.h>
73#include <string.h>
74#ifndef __WATCOMC__
3f4a0c5b
VZ
75 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
76 #include <errno.h>
77 #endif
32592631
GL
78#endif
79#include <stdarg.h>
80
731dd422
VZ
81#if wxUSE_IPC
82 #include "wx/dde.h" // for WX_DDE hack in wxExecute
83#endif // wxUSE_IPC
5bd3a2da 84
eccd1992 85// implemented in utils.cpp
487f2d58 86extern "C" WXDLLIMPEXP_BASE HWND
eccd1992
VZ
87wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc);
88
b568d04f
VZ
89// ----------------------------------------------------------------------------
90// constants
91// ----------------------------------------------------------------------------
92
cb6827a8
VZ
93// this message is sent when the process we're waiting for terminates
94#define wxWM_PROC_TERMINATED (WM_USER + 10000)
32592631 95
b568d04f
VZ
96// ----------------------------------------------------------------------------
97// this module globals
98// ----------------------------------------------------------------------------
99
100// we need to create a hidden window to receive the process termination
101// notifications and for this we need a (Win) class name for it which we will
102// register the first time it's needed
eccd1992 103static const wxChar *wxMSWEXEC_WNDCLASSNAME = wxT("_wxExecute_Internal_Class");
b568d04f
VZ
104static const wxChar *gs_classForHiddenWindow = NULL;
105
5a8561fc
VZ
106// event used to wake up threads waiting in wxExecuteThread
107static HANDLE gs_heventShutdown = NULL;
108
109// handles of all threads monitoring the execution of asynchronously running
110// processes
111static wxVector<HANDLE> gs_asyncThreads;
112
b568d04f
VZ
113// ----------------------------------------------------------------------------
114// private types
115// ----------------------------------------------------------------------------
116
cb6827a8
VZ
117// structure describing the process we're being waiting for
118struct wxExecuteData
119{
120public:
121 ~wxExecuteData()
122 {
123 if ( !::CloseHandle(hProcess) )
124 {
f6bcfd97 125 wxLogLastError(wxT("CloseHandle(hProcess)"));
cb6827a8
VZ
126 }
127 }
128
129 HWND hWnd; // window to send wxWM_PROC_TERMINATED to
130 HANDLE hProcess; // handle of the process
131 DWORD dwProcessId; // pid of the process
132 wxProcess *handler;
133 DWORD dwExitCode; // the exit code of the process
27d2dbbc 134 bool state; // set to false when the process finishes
32592631
GL
135};
136
eccd1992
VZ
137class wxExecuteModule : public wxModule
138{
139public:
140 virtual bool OnInit() { return true; }
141 virtual void OnExit()
142 {
5a8561fc
VZ
143 if ( gs_heventShutdown )
144 {
145 // stop any threads waiting for the termination of asynchronously
146 // running processes
147 if ( !::SetEvent(gs_heventShutdown) )
148 {
9a83f860 149 wxLogDebug(wxT("Failed to set shutdown event in wxExecuteModule"));
5a8561fc
VZ
150 }
151
152 ::CloseHandle(gs_heventShutdown);
153 gs_heventShutdown = NULL;
154
155 // now wait until they terminate
156 if ( !gs_asyncThreads.empty() )
157 {
158 const size_t numThreads = gs_asyncThreads.size();
159
160 if ( ::WaitForMultipleObjects
161 (
162 numThreads,
163 &gs_asyncThreads[0],
164 TRUE, // wait for all of them to become signalled
165 3000 // long but finite value
166 ) == WAIT_TIMEOUT )
167 {
9a83f860 168 wxLogDebug(wxT("Failed to stop all wxExecute monitor threads"));
5a8561fc
VZ
169 }
170
171 for ( size_t n = 0; n < numThreads; n++ )
172 {
173 ::CloseHandle(gs_asyncThreads[n]);
174 }
175
176 gs_asyncThreads.clear();
177 }
178 }
179
9978ac8e 180 if ( gs_classForHiddenWindow )
eccd1992
VZ
181 {
182 if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME, wxGetInstance()) )
183 {
9a83f860 184 wxLogLastError(wxT("UnregisterClass(wxExecClass)"));
eccd1992
VZ
185 }
186
187 gs_classForHiddenWindow = NULL;
188 }
189 }
190
191private:
192 DECLARE_DYNAMIC_CLASS(wxExecuteModule)
193};
194
5a8561fc
VZ
195IMPLEMENT_DYNAMIC_CLASS(wxExecuteModule, wxModule)
196
eccd1992 197#if wxUSE_STREAMS && !defined(__WXWINCE__)
8b33ae2d 198
8b33ae2d
GL
199// ----------------------------------------------------------------------------
200// wxPipeStreams
201// ----------------------------------------------------------------------------
202
f6bcfd97
BP
203class wxPipeInputStream: public wxInputStream
204{
8b33ae2d
GL
205public:
206 wxPipeInputStream(HANDLE hInput);
79066131 207 virtual ~wxPipeInputStream();
8b33ae2d 208
27d2dbbc 209 // returns true if the pipe is still opened
79066131
VZ
210 bool IsOpened() const { return m_hInput != INVALID_HANDLE_VALUE; }
211
27d2dbbc 212 // returns true if there is any data to be read from the pipe
2b5f62a0 213 virtual bool CanRead() const;
f6bcfd97 214
8b33ae2d
GL
215protected:
216 size_t OnSysRead(void *buffer, size_t len);
217
218protected:
219 HANDLE m_hInput;
22f3361e 220
c0c133e1 221 wxDECLARE_NO_COPY_CLASS(wxPipeInputStream);
8b33ae2d
GL
222};
223
f6bcfd97
BP
224class wxPipeOutputStream: public wxOutputStream
225{
8b33ae2d
GL
226public:
227 wxPipeOutputStream(HANDLE hOutput);
8f0ff178
RN
228 virtual ~wxPipeOutputStream() { Close(); }
229 bool Close();
8b33ae2d
GL
230
231protected:
232 size_t OnSysWrite(const void *buffer, size_t len);
233
234protected:
235 HANDLE m_hOutput;
22f3361e 236
c0c133e1 237 wxDECLARE_NO_COPY_CLASS(wxPipeOutputStream);
8b33ae2d
GL
238};
239
79066131
VZ
240// define this to let wxexec.cpp know that we know what we're doing
241#define _WX_USED_BY_WXEXECUTE_
242#include "../common/execcmn.cpp"
243
244// ----------------------------------------------------------------------------
245// wxPipe represents a Win32 anonymous pipe
246// ----------------------------------------------------------------------------
247
248class wxPipe
249{
250public:
251 // the symbolic names for the pipe ends
252 enum Direction
253 {
254 Read,
255 Write
256 };
257
258 // default ctor doesn't do anything
259 wxPipe() { m_handles[Read] = m_handles[Write] = INVALID_HANDLE_VALUE; }
260
27d2dbbc 261 // create the pipe, return true if ok, false on error
79066131
VZ
262 bool Create()
263 {
264 // default secutiry attributes
265 SECURITY_ATTRIBUTES security;
266
267 security.nLength = sizeof(security);
268 security.lpSecurityDescriptor = NULL;
269 security.bInheritHandle = TRUE; // to pass it to the child
270
271 if ( !::CreatePipe(&m_handles[0], &m_handles[1], &security, 0) )
272 {
273 wxLogSysError(_("Failed to create an anonymous pipe"));
274
27d2dbbc 275 return false;
79066131
VZ
276 }
277
27d2dbbc 278 return true;
79066131
VZ
279 }
280
27d2dbbc 281 // return true if we were created successfully
79066131
VZ
282 bool IsOk() const { return m_handles[Read] != INVALID_HANDLE_VALUE; }
283
284 // return the descriptor for one of the pipe ends
82baa5e4 285 HANDLE operator[](Direction which) const { return m_handles[which]; }
79066131
VZ
286
287 // detach a descriptor, meaning that the pipe dtor won't close it, and
288 // return it
289 HANDLE Detach(Direction which)
290 {
79066131
VZ
291 HANDLE handle = m_handles[which];
292 m_handles[which] = INVALID_HANDLE_VALUE;
293
294 return handle;
295 }
296
297 // close the pipe descriptors
298 void Close()
299 {
300 for ( size_t n = 0; n < WXSIZEOF(m_handles); n++ )
301 {
302 if ( m_handles[n] != INVALID_HANDLE_VALUE )
303 {
304 ::CloseHandle(m_handles[n]);
305 m_handles[n] = INVALID_HANDLE_VALUE;
306 }
307 }
308 }
309
310 // dtor closes the pipe descriptors
311 ~wxPipe() { Close(); }
312
313private:
314 HANDLE m_handles[2];
315};
316
317#endif // wxUSE_STREAMS
318
319// ============================================================================
320// implementation
321// ============================================================================
322
79066131
VZ
323// ----------------------------------------------------------------------------
324// process termination detecting support
325// ----------------------------------------------------------------------------
326
327// thread function for the thread monitoring the process termination
328static DWORD __stdcall wxExecuteThread(void *arg)
329{
45d5a0c6 330 wxExecuteData * const data = (wxExecuteData *)arg;
79066131 331
5a8561fc
VZ
332 // create the shutdown event if we're the first thread starting to wait
333 if ( !gs_heventShutdown )
79066131 334 {
5a8561fc
VZ
335 // create a manual initially non-signalled event object
336 gs_heventShutdown = ::CreateEvent(NULL, TRUE, FALSE, NULL);
337 if ( !gs_heventShutdown )
338 {
9a83f860 339 wxLogDebug(wxT("CreateEvent() in wxExecuteThread failed"));
5a8561fc 340 }
79066131
VZ
341 }
342
5a8561fc
VZ
343 HANDLE handles[2] = { data->hProcess, gs_heventShutdown };
344 switch ( ::WaitForMultipleObjects(2, handles, FALSE, INFINITE) )
79066131 345 {
5a8561fc
VZ
346 case WAIT_OBJECT_0:
347 // process terminated, get its exit code
348 if ( !::GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
349 {
350 wxLogLastError(wxT("GetExitCodeProcess"));
351 }
352
353 wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
354 wxT("process should have terminated") );
79066131 355
5a8561fc
VZ
356 // send a message indicating process termination to the window
357 ::SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
358 break;
359
360 case WAIT_OBJECT_0 + 1:
361 // we're shutting down but the process is still running -- leave it
362 // run but clean up the associated data
363 if ( !data->state )
364 {
365 delete data;
366 }
367 //else: exiting while synchronously executing process is still
368 // running? this shouldn't happen...
369 break;
79066131 370
5a8561fc 371 default:
9a83f860 372 wxLogDebug(wxT("Waiting for the process termination failed!"));
5a8561fc 373 }
79066131
VZ
374
375 return 0;
376}
377
378// window procedure of a hidden window which is created just to receive
379// the notification message when a process exits
380LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message,
381 WPARAM wParam, LPARAM lParam)
382{
383 if ( message == wxWM_PROC_TERMINATED )
384 {
385 DestroyWindow(hWnd); // we don't need it any more
386
45d5a0c6 387 wxExecuteData * const data = (wxExecuteData *)lParam;
79066131
VZ
388 if ( data->handler )
389 {
390 data->handler->OnTerminate((int)data->dwProcessId,
391 (int)data->dwExitCode);
392 }
393
394 if ( data->state )
395 {
396 // we're executing synchronously, tell the waiting thread
397 // that the process finished
5a8561fc 398 data->state = false;
79066131
VZ
399 }
400 else
401 {
402 // asynchronous execution - we should do the clean up
403 delete data;
404 }
405
406 return 0;
407 }
408 else
409 {
45d5a0c6 410 return ::DefWindowProc(hWnd, message, wParam, lParam);
79066131
VZ
411 }
412}
413
414// ============================================================================
415// implementation of IO redirection support classes
416// ============================================================================
417
4676948b 418#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
419
420// ----------------------------------------------------------------------------
421// wxPipeInputStreams
422// ----------------------------------------------------------------------------
8b33ae2d
GL
423
424wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
425{
426 m_hInput = hInput;
cd6ce4a9 427}
8b33ae2d
GL
428
429wxPipeInputStream::~wxPipeInputStream()
430{
79066131
VZ
431 if ( m_hInput != INVALID_HANDLE_VALUE )
432 ::CloseHandle(m_hInput);
8b33ae2d
GL
433}
434
2b5f62a0 435bool wxPipeInputStream::CanRead() const
8b33ae2d 436{
386a2898
VZ
437 // we can read if there's something in the put back buffer
438 // even pipe is closed
439 if ( m_wbacksize > m_wbackcur )
440 return true;
441
442 wxPipeInputStream * const self = wxConstCast(this, wxPipeInputStream);
443
79066131 444 if ( !IsOpened() )
386a2898
VZ
445 {
446 // set back to mark Eof as it may have been unset by Ungetch()
447 self->m_lasterror = wxSTREAM_EOF;
27d2dbbc 448 return false;
386a2898 449 }
79066131 450
f6bcfd97
BP
451 DWORD nAvailable;
452
453 // function name is misleading, it works with anon pipes as well
454 DWORD rc = ::PeekNamedPipe
455 (
456 m_hInput, // handle
457 NULL, 0, // ptr to buffer and its size
458 NULL, // [out] bytes read
459 &nAvailable, // [out] bytes available
460 NULL // [out] bytes left
461 );
462
463 if ( !rc )
464 {
465 if ( ::GetLastError() != ERROR_BROKEN_PIPE )
466 {
467 // unexpected error
9a83f860 468 wxLogLastError(wxT("PeekNamedPipe"));
f6bcfd97 469 }
8b33ae2d 470
3103e8a9 471 // don't try to continue reading from a pipe if an error occurred or if
f6bcfd97 472 // it had been closed
79066131
VZ
473 ::CloseHandle(m_hInput);
474
2b5f62a0
VZ
475 self->m_hInput = INVALID_HANDLE_VALUE;
476 self->m_lasterror = wxSTREAM_EOF;
477
478 nAvailable = 0;
f6bcfd97 479 }
79066131
VZ
480
481 return nAvailable != 0;
f6bcfd97
BP
482}
483
484size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
485{
2b5f62a0 486 if ( !IsOpened() )
79066131
VZ
487 {
488 m_lasterror = wxSTREAM_EOF;
489
f6bcfd97 490 return 0;
79066131
VZ
491 }
492
f6bcfd97
BP
493 DWORD bytesRead;
494 if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) )
495 {
2b5f62a0
VZ
496 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
497 ? wxSTREAM_EOF
498 : wxSTREAM_READ_ERROR;
8b33ae2d 499 }
f6bcfd97 500
3103e8a9 501 // bytesRead is set to 0, as desired, if an error occurred
8b33ae2d
GL
502 return bytesRead;
503}
504
79066131 505// ----------------------------------------------------------------------------
8b33ae2d 506// wxPipeOutputStream
79066131 507// ----------------------------------------------------------------------------
8b33ae2d
GL
508
509wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
510{
511 m_hOutput = hOutput;
3338a5bd
VZ
512
513 // unblock the pipe to prevent deadlocks when we're writing to the pipe
514 // from which the child process can't read because it is writing in its own
515 // end of it
516 DWORD mode = PIPE_READMODE_BYTE | PIPE_NOWAIT;
517 if ( !::SetNamedPipeHandleState
518 (
519 m_hOutput,
520 &mode,
521 NULL, // collection count (we don't set it)
522 NULL // timeout (we don't set it neither)
523 ) )
524 {
9a83f860 525 wxLogLastError(wxT("SetNamedPipeHandleState(PIPE_NOWAIT)"));
3338a5bd 526 }
cd6ce4a9 527}
8b33ae2d 528
8f0ff178 529bool wxPipeOutputStream::Close()
8b33ae2d 530{
8f0ff178 531 return ::CloseHandle(m_hOutput) != 0;
8b33ae2d
GL
532}
533
8f0ff178 534
8b33ae2d
GL
535size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
536{
2b5f62a0 537 m_lasterror = wxSTREAM_NO_ERROR;
3338a5bd
VZ
538
539 DWORD totalWritten = 0;
540 while ( len > 0 )
f6bcfd97 541 {
3338a5bd
VZ
542 DWORD chunkWritten;
543 if ( !::WriteFile(m_hOutput, buffer, len, &chunkWritten, NULL) )
544 {
545 m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE
546 ? wxSTREAM_EOF
547 : wxSTREAM_WRITE_ERROR;
548 break;
549 }
550
551 if ( !chunkWritten )
552 break;
553
554 buffer = (char *)buffer + chunkWritten;
555 totalWritten += chunkWritten;
556 len -= chunkWritten;
8b33ae2d 557 }
f6bcfd97 558
3338a5bd 559 return totalWritten;
8b33ae2d
GL
560}
561
79066131
VZ
562#endif // wxUSE_STREAMS
563
b568d04f 564// ============================================================================
79066131 565// wxExecute functions family
b568d04f 566// ============================================================================
5260b1c5 567
ca289436
VZ
568#if wxUSE_IPC
569
570// connect to the given server via DDE and ask it to execute the command
42d0df00
VZ
571bool
572wxExecuteDDE(const wxString& ddeServer,
573 const wxString& ddeTopic,
574 const wxString& ddeCommand)
ca289436 575{
999836aa 576 bool ok wxDUMMY_INITIALIZE(false);
ca289436
VZ
577
578 wxDDEClient client;
42d0df00
VZ
579 wxConnectionBase *
580 conn = client.MakeConnection(wxEmptyString, ddeServer, ddeTopic);
ca289436
VZ
581 if ( !conn )
582 {
27d2dbbc 583 ok = false;
ca289436
VZ
584 }
585 else // connected to DDE server
586 {
4dd03db9
VZ
587 // the added complication here is that although most programs use
588 // XTYP_EXECUTE for their DDE API, some important ones -- like Word
589 // and other MS stuff - use XTYP_REQUEST!
ca289436 590 //
4dd03db9
VZ
591 // moreover, anotheri mportant program (IE) understands both but
592 // returns an error from Execute() so we must try Request() first
593 // to avoid doing it twice
ca289436 594 {
4dd03db9 595 // we're prepared for this one to fail, so don't show errors
ca289436 596 wxLogNull noErrors;
4dd03db9
VZ
597
598 ok = conn->Request(ddeCommand) != NULL;
ca289436
VZ
599 }
600
601 if ( !ok )
602 {
4dd03db9
VZ
603 // now try execute -- but show the errors
604 ok = conn->Execute(ddeCommand);
ca289436
VZ
605 }
606 }
607
608 return ok;
609}
610
611#endif // wxUSE_IPC
612
164db92c
VZ
613long wxExecute(const wxString& cmd, int flags, wxProcess *handler,
614 const wxExecuteEnv *env)
32592631 615{
c3fad64b 616 wxCHECK_MSG( !cmd.empty(), 0, wxT("empty command in wxExecute") );
5bd3a2da 617
647b8e37
VZ
618#if wxUSE_THREADS
619 // for many reasons, the code below breaks down if it's called from another
620 // thread -- this could be fixed, but as Unix versions don't support this
621 // neither I don't want to waste time on this now
622 wxASSERT_MSG( wxThread::IsMain(),
9a83f860 623 wxT("wxExecute() can be called only from the main thread") );
647b8e37
VZ
624#endif // wxUSE_THREADS
625
039f62f4 626 wxString command;
6ba63600 627
731dd422 628#if wxUSE_IPC
5bd3a2da
VZ
629 // DDE hack: this is really not pretty, but we need to allow this for
630 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
631 // returns the command which should be run to view/open/... a file of the
632 // given type. Sometimes, however, this command just launches the server
633 // and an additional DDE request must be made to really open the file. To
634 // keep all this well hidden from the application, we allow a special form
6ba63600 635 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
5bd3a2da 636 // case we execute just <command> and process the rest below
039f62f4 637 wxString ddeServer, ddeTopic, ddeCommand;
5bd3a2da 638 static const size_t lenDdePrefix = 7; // strlen("WX_DDE:")
9a83f860 639 if ( cmd.Left(lenDdePrefix) == wxT("WX_DDE#") )
5bd3a2da 640 {
ca289436
VZ
641 // speed up the concatenations below
642 ddeServer.reserve(256);
643 ddeTopic.reserve(256);
644 ddeCommand.reserve(256);
645
5bd3a2da 646 const wxChar *p = cmd.c_str() + 7;
9a83f860 647 while ( *p && *p != wxT('#') )
5bd3a2da
VZ
648 {
649 command += *p++;
650 }
651
652 if ( *p )
653 {
654 // skip '#'
655 p++;
656 }
657 else
658 {
9a83f860 659 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
5bd3a2da
VZ
660 }
661
9a83f860 662 while ( *p && *p != wxT('#') )
5bd3a2da
VZ
663 {
664 ddeServer += *p++;
665 }
666
667 if ( *p )
668 {
669 // skip '#'
670 p++;
671 }
672 else
673 {
9a83f860 674 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
5bd3a2da
VZ
675 }
676
9a83f860 677 while ( *p && *p != wxT('#') )
5bd3a2da
VZ
678 {
679 ddeTopic += *p++;
680 }
681
682 if ( *p )
683 {
684 // skip '#'
685 p++;
686 }
687 else
688 {
9a83f860 689 wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute"));
5bd3a2da
VZ
690 }
691
692 while ( *p )
693 {
694 ddeCommand += *p++;
695 }
6ba63600 696
ca289436
VZ
697 // if we want to just launch the program and not wait for its
698 // termination, try to execute DDE command right now, it can succeed if
699 // the process is already running - but as it fails if it's not
700 // running, suppress any errors it might generate
fbf456aa 701 if ( !(flags & wxEXEC_SYNC) )
6ba63600 702 {
ca289436
VZ
703 wxLogNull noErrors;
704 if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCommand) )
705 {
706 // a dummy PID - this is a hack, of course, but it's well worth
707 // it as we don't open a new server each time we're called
708 // which would be quite bad
709 return -1;
710 }
6ba63600 711 }
5bd3a2da
VZ
712 }
713 else
731dd422 714#endif // wxUSE_IPC
5bd3a2da
VZ
715 {
716 // no DDE
717 command = cmd;
718 }
32592631 719
f6bcfd97
BP
720 // the IO redirection is only supported with wxUSE_STREAMS
721 BOOL redirect = FALSE;
79066131 722
4676948b 723#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
724 wxPipe pipeIn, pipeOut, pipeErr;
725
726 // we'll save here the copy of pipeIn[Write]
33ac7e6f 727 HANDLE hpipeStdinWrite = INVALID_HANDLE_VALUE;
8b33ae2d 728
cd6ce4a9 729 // open the pipes to which child process IO will be redirected if needed
cd6ce4a9
VZ
730 if ( handler && handler->IsRedirected() )
731 {
79066131
VZ
732 // create pipes for redirecting stdin, stdout and stderr
733 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
cd6ce4a9 734 {
79066131 735 wxLogSysError(_("Failed to redirect the child process IO"));
8b33ae2d 736
fbf456aa
VZ
737 // indicate failure: we need to return different error code
738 // depending on the sync flag
739 return flags & wxEXEC_SYNC ? -1 : 0;
8b33ae2d
GL
740 }
741
f6bcfd97 742 redirect = TRUE;
8b33ae2d 743 }
f6bcfd97 744#endif // wxUSE_STREAMS
5bd3a2da 745
cb6827a8
VZ
746 // create the process
747 STARTUPINFO si;
11c7d5b6 748 wxZeroMemory(si);
cb6827a8
VZ
749 si.cb = sizeof(si);
750
4676948b 751#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97 752 if ( redirect )
cb6827a8 753 {
fbf456aa 754 si.dwFlags = STARTF_USESTDHANDLES;
f6bcfd97 755
79066131
VZ
756 si.hStdInput = pipeIn[wxPipe::Read];
757 si.hStdOutput = pipeOut[wxPipe::Write];
758 si.hStdError = pipeErr[wxPipe::Write];
f6bcfd97 759
fbf456aa
VZ
760 // when the std IO is redirected, we don't show the (console) process
761 // window by default, but this can be overridden by the caller by
762 // specifying wxEXEC_NOHIDE flag
763 if ( !(flags & wxEXEC_NOHIDE) )
764 {
765 si.dwFlags |= STARTF_USESHOWWINDOW;
766 si.wShowWindow = SW_HIDE;
767 }
f6bcfd97
BP
768
769 // we must duplicate the handle to the write side of stdin pipe to make
79066131
VZ
770 // it non inheritable: indeed, we must close the writing end of pipeIn
771 // before launching the child process as otherwise this handle will be
f6bcfd97
BP
772 // inherited by the child which will never close it and so the pipe
773 // will never be closed and the child will be left stuck in ReadFile()
79066131 774 HANDLE pipeInWrite = pipeIn.Detach(wxPipe::Write);
f6bcfd97
BP
775 if ( !::DuplicateHandle
776 (
79066131
VZ
777 ::GetCurrentProcess(),
778 pipeInWrite,
779 ::GetCurrentProcess(),
f6bcfd97
BP
780 &hpipeStdinWrite,
781 0, // desired access: unused here
782 FALSE, // not inherited
783 DUPLICATE_SAME_ACCESS // same access as for src handle
784 ) )
cd6ce4a9 785 {
9a83f860 786 wxLogLastError(wxT("DuplicateHandle"));
8b33ae2d 787 }
cd6ce4a9 788
79066131 789 ::CloseHandle(pipeInWrite);
f6bcfd97
BP
790 }
791#endif // wxUSE_STREAMS
cb6827a8 792
f6bcfd97 793 PROCESS_INFORMATION pi;
4676948b 794 DWORD dwFlags = CREATE_SUSPENDED;
78c743d8 795
4676948b
JS
796#ifndef __WXWINCE__
797 dwFlags |= CREATE_DEFAULT_ERROR_MODE ;
78c743d8 798#else
9cd03a43
WS
799 // we are assuming commands without spaces for now
800 wxString moduleName = command.BeforeFirst(wxT(' '));
801 wxString arguments = command.AfterFirst(wxT(' '));
4676948b 802#endif
f6bcfd97 803
164db92c
VZ
804 wxWxCharBuffer envBuffer;
805 bool useCwd = false;
806 if ( env )
807 {
808 useCwd = !env->cwd.empty();
809
810 // Translate environment variable map into NUL-terminated list of
811 // NUL-terminated strings.
812 if ( !env->env.empty() )
813 {
814#if wxUSE_UNICODE
815 // Environment variables can contain non-ASCII characters. We could
816 // check for it and not use this flag if everything is really ASCII
817 // only but there doesn't seem to be any reason to do it so just
818 // assume Unicode by default.
819 dwFlags |= CREATE_UNICODE_ENVIRONMENT;
820#endif // wxUSE_UNICODE
821
822 wxEnvVariableHashMap::const_iterator it;
823
824 size_t envSz = 1; // ending '\0'
825 for ( it = env->env.begin(); it != env->env.end(); ++it )
826 {
827 // Add size of env variable name and value, and '=' char and
828 // ending '\0'
829 envSz += it->first.length() + it->second.length() + 2;
830 }
831
832 envBuffer.extend(envSz);
833
834 wxChar *p = envBuffer.data();
835 for ( it = env->env.begin(); it != env->env.end(); ++it )
836 {
837 const wxString line = it->first + wxS("=") + it->second;
838
839 // Include the trailing NUL which will always terminate the
840 // buffer returned by t_str().
841 const size_t len = line.length() + 1;
842
843 wxTmemcpy(p, line.t_str(), len);
844
845 p += len;
846 }
847
848 // And another NUL to terminate the list of NUL-terminated strings.
849 *p = 0;
850 }
851 }
852
f6bcfd97
BP
853 bool ok = ::CreateProcess
854 (
9cd03a43 855 // WinCE requires appname to be non null
78c743d8
JS
856 // Win32 allows for null
857#ifdef __WXWINCE__
858 (wxChar *)
c9f78968 859 moduleName.wx_str(),// application name
78c743d8 860 (wxChar *)
c9f78968 861 arguments.wx_str(), // arguments
78c743d8 862#else
9cd03a43 863 NULL, // application name (use only cmd line)
f6bcfd97 864 (wxChar *)
c9f78968 865 command.wx_str(), // full command line
78c743d8 866#endif
9cd03a43
WS
867 NULL, // security attributes: defaults for both
868 NULL, // the process and its main thread
869 redirect, // inherit handles if we use pipes
870 dwFlags, // process creation flags
164db92c
VZ
871 envBuffer.data(), // environment (may be NULL which is fine)
872 useCwd // initial working directory
873 ? const_cast<wxChar *>(env->cwd.wx_str())
874 : NULL, // (or use the same)
9cd03a43
WS
875 &si, // startup info (unused here)
876 &pi // process info
f6bcfd97
BP
877 ) != 0;
878
4676948b 879#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97
BP
880 // we can close the pipe ends used by child anyhow
881 if ( redirect )
882 {
79066131
VZ
883 ::CloseHandle(pipeIn.Detach(wxPipe::Read));
884 ::CloseHandle(pipeOut.Detach(wxPipe::Write));
885 ::CloseHandle(pipeErr.Detach(wxPipe::Write));
cb6827a8 886 }
f6bcfd97 887#endif // wxUSE_STREAMS
cb6827a8 888
f6bcfd97 889 if ( !ok )
5e1febfa 890 {
4676948b 891#if wxUSE_STREAMS && !defined(__WXWINCE__)
f6bcfd97
BP
892 // close the other handles too
893 if ( redirect )
5e1febfa 894 {
79066131
VZ
895 ::CloseHandle(pipeOut.Detach(wxPipe::Read));
896 ::CloseHandle(pipeErr.Detach(wxPipe::Read));
5e1febfa 897 }
f6bcfd97 898#endif // wxUSE_STREAMS
5e1febfa 899
f6bcfd97
BP
900 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
901
fbf456aa 902 return flags & wxEXEC_SYNC ? -1 : 0;
f6bcfd97 903 }
8b33ae2d 904
4676948b 905#if wxUSE_STREAMS && !defined(__WXWINCE__)
79066131
VZ
906 // the input buffer bufOut is connected to stdout, this is why it is
907 // called bufOut and not bufIn
908 wxStreamTempInputBuffer bufOut,
909 bufErr;
910
f6bcfd97
BP
911 if ( redirect )
912 {
8b33ae2d 913 // We can now initialize the wxStreams
79066131
VZ
914 wxPipeInputStream *
915 outStream = new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
916 wxPipeInputStream *
917 errStream = new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
918 wxPipeOutputStream *
919 inStream = new wxPipeOutputStream(hpipeStdinWrite);
920
921 handler->SetPipeStreams(outStream, inStream, errStream);
8b33ae2d 922
79066131
VZ
923 bufOut.Init(outStream);
924 bufErr.Init(errStream);
8b33ae2d 925 }
f6bcfd97 926#endif // wxUSE_STREAMS
8b33ae2d 927
cb6827a8
VZ
928 // create a hidden window to receive notification about process
929 // termination
eccd1992
VZ
930 HWND hwnd = wxCreateHiddenWindow
931 (
932 &gs_classForHiddenWindow,
933 wxMSWEXEC_WNDCLASSNAME,
934 (WNDPROC)wxExecuteWindowCbk
935 );
936
223d09f6 937 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
e6045e08 938
cb6827a8
VZ
939 // Alloc data
940 wxExecuteData *data = new wxExecuteData;
941 data->hProcess = pi.hProcess;
942 data->dwProcessId = pi.dwProcessId;
943 data->hWnd = hwnd;
fbf456aa
VZ
944 data->state = (flags & wxEXEC_SYNC) != 0;
945 if ( flags & wxEXEC_SYNC )
e6045e08 946 {
5e1febfa
VZ
947 // handler may be !NULL for capturing program output, but we don't use
948 // it wxExecuteData struct in this case
e6045e08
VZ
949 data->handler = NULL;
950 }
951 else
952 {
953 // may be NULL or not
954 data->handler = handler;
ca5016d4
FM
955
956 if (handler)
957 handler->SetPid(pi.dwProcessId);
e6045e08 958 }
cb6827a8
VZ
959
960 DWORD tid;
961 HANDLE hThread = ::CreateThread(NULL,
962 0,
19193a2c 963 wxExecuteThread,
cb6827a8
VZ
964 (void *)data,
965 0,
966 &tid);
967
0d7ea902
VZ
968 // resume process we created now - whether the thread creation succeeded or
969 // not
970 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
971 {
972 // ignore it - what can we do?
f6bcfd97 973 wxLogLastError(wxT("ResumeThread in wxExecute"));
0d7ea902
VZ
974 }
975
976 // close unneeded handle
977 if ( !::CloseHandle(pi.hThread) )
43b2d5e7 978 {
f6bcfd97 979 wxLogLastError(wxT("CloseHandle(hThread)"));
43b2d5e7 980 }
0d7ea902 981
cb6827a8
VZ
982 if ( !hThread )
983 {
f6bcfd97 984 wxLogLastError(wxT("CreateThread in wxExecute"));
cb6827a8
VZ
985
986 DestroyWindow(hwnd);
987 delete data;
988
989 // the process still started up successfully...
990 return pi.dwProcessId;
991 }
e6045e08 992
5a8561fc 993 gs_asyncThreads.push_back(hThread);
f6bcfd97 994
4676948b 995#if wxUSE_IPC && !defined(__WXWINCE__)
5bd3a2da
VZ
996 // second part of DDE hack: now establish the DDE conversation with the
997 // just launched process
ca289436 998 if ( !ddeServer.empty() )
5bd3a2da 999 {
ca289436
VZ
1000 bool ok;
1001
1002 // give the process the time to init itself
1003 //
1004 // we use a very big timeout hoping that WaitForInputIdle() will return
1005 // much sooner, but not INFINITE just in case the process hangs
1006 // completely - like this we will regain control sooner or later
1007 switch ( ::WaitForInputIdle(pi.hProcess, 10000 /* 10 seconds */) )
6ba63600 1008 {
ca289436 1009 default:
9a83f860 1010 wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") );
ca289436 1011 // fall through
6ba63600 1012
ca289436 1013 case -1:
9a83f860 1014 wxLogLastError(wxT("WaitForInputIdle() in wxExecute"));
6ba63600 1015
ca289436 1016 case WAIT_TIMEOUT:
9a83f860 1017 wxLogDebug(wxT("Timeout too small in WaitForInputIdle"));
ca289436 1018
27d2dbbc 1019 ok = false;
ca289436
VZ
1020 break;
1021
1022 case 0:
1023 // ok, process ready to accept DDE requests
1024 ok = wxExecuteDDE(ddeServer, ddeTopic, ddeCommand);
6ba63600 1025 }
1b47bebc
VZ
1026
1027 if ( !ok )
1028 {
9a83f860 1029 wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."),
1b47bebc
VZ
1030 cmd.c_str());
1031 }
5bd3a2da 1032 }
731dd422 1033#endif // wxUSE_IPC
5bd3a2da 1034
fbf456aa 1035 if ( !(flags & wxEXEC_SYNC) )
cb6827a8
VZ
1036 {
1037 // clean up will be done when the process terminates
e6045e08
VZ
1038
1039 // return the pid
cb6827a8
VZ
1040 return pi.dwProcessId;
1041 }
e6045e08 1042
d60e2332 1043 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
9a83f860 1044 wxCHECK_MSG( traits, -1, wxT("no wxAppTraits in wxExecute()?") );
d60e2332 1045
c3fad64b 1046 void *cookie = NULL;
f38f6899
VZ
1047 if ( !(flags & wxEXEC_NODISABLE) )
1048 {
f38f6899
VZ
1049 // disable all app windows while waiting for the child process to finish
1050 cookie = traits->BeforeChildWaitLoop();
1051 }
e2478fde
VZ
1052
1053 // wait until the child process terminates
1054 while ( data->state )
1055 {
4676948b 1056#if wxUSE_STREAMS && !defined(__WXWINCE__)
4d425dee 1057 if ( !bufOut.Update() && !bufErr.Update() )
79066131 1058#endif // wxUSE_STREAMS
4d425dee
VZ
1059 {
1060 // don't eat 100% of the CPU -- ugly but anything else requires
1061 // real async IO which we don't have for the moment
1062 ::Sleep(50);
1063 }
e6045e08 1064
dbbcfbb6
VZ
1065 // we must always process messages for our hidden window or we'd never
1066 // get wxWM_PROC_TERMINATED and so this loop would never terminate
1067 MSG msg;
1068 ::PeekMessage(&msg, data->hWnd, 0, 0, PM_REMOVE);
1069
1070 // we may also need to process messages for all the other application
1071 // windows
1072 if ( !(flags & wxEXEC_NOEVENTS) )
1073 {
1074 wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
1075 if ( loop )
1076 loop->Yield();
1077 }
cd6ce4a9 1078 }
068a7cfe 1079
d60e2332
VZ
1080 if ( !(flags & wxEXEC_NODISABLE) )
1081 {
1082 // reenable disabled windows back
f38f6899 1083 traits->AfterChildWaitLoop(cookie);
d60e2332 1084 }
0d7ea902 1085
e6045e08 1086 DWORD dwExitCode = data->dwExitCode;
cb6827a8
VZ
1087 delete data;
1088
e6045e08
VZ
1089 // return the exit code
1090 return dwExitCode;
32592631 1091}
c740f496 1092
05718a98 1093template <typename CharType>
164db92c
VZ
1094long wxExecuteImpl(CharType **argv, int flags, wxProcess *handler,
1095 const wxExecuteEnv *env)
c740f496 1096{
cb6827a8 1097 wxString command;
05718a98 1098 command.reserve(1024);
e6045e08 1099
3cdd564f 1100 wxString arg;
0493ba13 1101 for ( ;; )
cb6827a8 1102 {
3cdd564f
VZ
1103 arg = *argv++;
1104
a6eac99d
VZ
1105 bool quote;
1106 if ( arg.empty() )
1107 {
1108 // we need to quote empty arguments, otherwise they'd just
1109 // disappear
1110 quote = true;
1111 }
1112 else // non-empty
1113 {
1114 // escape any quotes present in the string to avoid interfering
1115 // with the command line parsing in the child process
1116 arg.Replace("\"", "\\\"", true /* replace all */);
3cdd564f 1117
a6eac99d
VZ
1118 // and quote any arguments containing the spaces to prevent them from
1119 // being broken down
1120 quote = arg.find_first_of(" \t") != wxString::npos;
1121 }
1122
1123 if ( quote )
3cdd564f 1124 command += '\"' + arg + '\"';
a6eac99d
VZ
1125 else
1126 command += arg;
3cdd564f 1127
0493ba13
VZ
1128 if ( !*argv )
1129 break;
cb6827a8 1130
05718a98 1131 command += ' ';
0493ba13 1132 }
cb6827a8 1133
164db92c 1134 return wxExecute(command, flags, handler, env);
c740f496 1135}
05718a98 1136
164db92c
VZ
1137long wxExecute(char **argv, int flags, wxProcess *handler,
1138 const wxExecuteEnv *env)
05718a98 1139{
164db92c 1140 return wxExecuteImpl(argv, flags, handler, env);
05718a98
VZ
1141}
1142
d7ef641d
VZ
1143#if wxUSE_UNICODE
1144
164db92c
VZ
1145long wxExecute(wchar_t **argv, int flags, wxProcess *handler,
1146 const wxExecuteEnv *env)
05718a98 1147{
164db92c 1148 return wxExecuteImpl(argv, flags, handler, env);
05718a98 1149}
d7ef641d
VZ
1150
1151#endif // wxUSE_UNICODE