]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/unix/utilsunx.cpp
blind fix for buildbot
[wxWidgets.git] / src / unix / utilsunx.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: src/unix/utilsunx.cpp
3// Purpose: generic Unix implementation of many wx functions
4// Author: Vadim Zeitlin
5// Id: $Id$
6// Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin
7// Licence: wxWindows licence
8/////////////////////////////////////////////////////////////////////////////
9
10// ============================================================================
11// declarations
12// ============================================================================
13
14// ----------------------------------------------------------------------------
15// headers
16// ----------------------------------------------------------------------------
17
18// for compilers that support precompilation, includes "wx.h".
19#include "wx/wxprec.h"
20
21#include "wx/utils.h"
22
23#define USE_PUTENV (!defined(HAVE_SETENV) && defined(HAVE_PUTENV))
24
25#ifndef WX_PRECOMP
26 #include "wx/string.h"
27 #include "wx/intl.h"
28 #include "wx/log.h"
29 #include "wx/app.h"
30 #include "wx/wxcrtvararg.h"
31 #if USE_PUTENV
32 #include "wx/module.h"
33 #include "wx/hashmap.h"
34 #endif
35#endif
36
37#include "wx/apptrait.h"
38
39#include "wx/process.h"
40#include "wx/thread.h"
41
42#include "wx/cmdline.h"
43
44#include "wx/wfstream.h"
45
46#include "wx/private/selectdispatcher.h"
47#include "wx/private/fdiodispatcher.h"
48#include "wx/unix/execute.h"
49#include "wx/unix/private.h"
50
51#ifdef wxHAS_GENERIC_PROCESS_CALLBACK
52#include "wx/private/fdiodispatcher.h"
53#endif
54
55#include <pwd.h>
56#include <sys/wait.h> // waitpid()
57
58#ifdef HAVE_SYS_SELECT_H
59# include <sys/select.h>
60#endif
61
62#define HAS_PIPE_INPUT_STREAM (wxUSE_STREAMS && wxUSE_FILE)
63
64#if HAS_PIPE_INPUT_STREAM
65
66// define this to let wxexec.cpp know that we know what we're doing
67#define _WX_USED_BY_WXEXECUTE_
68#include "../common/execcmn.cpp"
69
70#endif // HAS_PIPE_INPUT_STREAM
71
72#if defined(__MWERKS__) && defined(__MACH__)
73 #ifndef WXWIN_OS_DESCRIPTION
74 #define WXWIN_OS_DESCRIPTION "MacOS X"
75 #endif
76 #ifndef HAVE_NANOSLEEP
77 #define HAVE_NANOSLEEP
78 #endif
79 #ifndef HAVE_UNAME
80 #define HAVE_UNAME
81 #endif
82
83 // our configure test believes we can use sigaction() if the function is
84 // available but Metrowekrs with MSL run-time does have the function but
85 // doesn't have sigaction struct so finally we can't use it...
86 #ifdef __MSL__
87 #undef wxUSE_ON_FATAL_EXCEPTION
88 #define wxUSE_ON_FATAL_EXCEPTION 0
89 #endif
90#endif
91
92// not only the statfs syscall is called differently depending on platform, but
93// one of its incarnations, statvfs(), takes different arguments under
94// different platforms and even different versions of the same system (Solaris
95// 7 and 8): if you want to test for this, don't forget that the problems only
96// appear if the large files support is enabled
97#ifdef HAVE_STATFS
98 #ifdef __BSD__
99 #include <sys/param.h>
100 #include <sys/mount.h>
101 #else // !__BSD__
102 #include <sys/vfs.h>
103 #endif // __BSD__/!__BSD__
104
105 #define wxStatfs statfs
106
107 #ifndef HAVE_STATFS_DECL
108 // some systems lack statfs() prototype in the system headers (AIX 4)
109 extern "C" int statfs(const char *path, struct statfs *buf);
110 #endif
111#endif // HAVE_STATFS
112
113#ifdef HAVE_STATVFS
114 #include <sys/statvfs.h>
115
116 #define wxStatfs statvfs
117#endif // HAVE_STATVFS
118
119#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
120 // WX_STATFS_T is detected by configure
121 #define wxStatfs_t WX_STATFS_T
122#endif
123
124// SGI signal.h defines signal handler arguments differently depending on
125// whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
126#if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
127 #define _LANGUAGE_C_PLUS_PLUS 1
128#endif // SGI hack
129
130#include <stdarg.h>
131#include <dirent.h>
132#include <string.h>
133#include <sys/stat.h>
134#include <sys/types.h>
135#include <sys/wait.h>
136#include <unistd.h>
137#include <errno.h>
138#include <netdb.h>
139#include <signal.h>
140#include <fcntl.h> // for O_WRONLY and friends
141#include <time.h> // nanosleep() and/or usleep()
142#include <ctype.h> // isspace()
143#include <sys/time.h> // needed for FD_SETSIZE
144
145#ifdef HAVE_UNAME
146 #include <sys/utsname.h> // for uname()
147#endif // HAVE_UNAME
148
149// Used by wxGetFreeMemory().
150#ifdef __SGI__
151 #include <sys/sysmp.h>
152 #include <sys/sysinfo.h> // for SAGET and MINFO structures
153#endif
154
155// ----------------------------------------------------------------------------
156// conditional compilation
157// ----------------------------------------------------------------------------
158
159// many versions of Unices have this function, but it is not defined in system
160// headers - please add your system here if it is the case for your OS.
161// SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
162#if !defined(HAVE_USLEEP) && \
163 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
164 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
165 defined(__osf__) || defined(__EMX__))
166 extern "C"
167 {
168 #ifdef __EMX__
169 /* I copied this from the XFree86 diffs. AV. */
170 #define INCL_DOSPROCESS
171 #include <os2.h>
172 inline void usleep(unsigned long delay)
173 {
174 DosSleep(delay ? (delay/1000l) : 1l);
175 }
176 #else // Unix
177 int usleep(unsigned int usec);
178 #endif // __EMX__/Unix
179 };
180
181 #define HAVE_USLEEP 1
182#endif // Unices without usleep()
183
184// ============================================================================
185// implementation
186// ============================================================================
187
188// ----------------------------------------------------------------------------
189// sleeping
190// ----------------------------------------------------------------------------
191
192void wxSleep(int nSecs)
193{
194 sleep(nSecs);
195}
196
197void wxMicroSleep(unsigned long microseconds)
198{
199#if defined(HAVE_NANOSLEEP)
200 timespec tmReq;
201 tmReq.tv_sec = (time_t)(microseconds / 1000000);
202 tmReq.tv_nsec = (microseconds % 1000000) * 1000;
203
204 // we're not interested in remaining time nor in return value
205 (void)nanosleep(&tmReq, (timespec *)NULL);
206#elif defined(HAVE_USLEEP)
207 // uncomment this if you feel brave or if you are sure that your version
208 // of Solaris has a safe usleep() function but please notice that usleep()
209 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
210 // documented as MT-Safe
211 #if defined(__SUN__) && wxUSE_THREADS
212 #error "usleep() cannot be used in MT programs under Solaris."
213 #endif // Sun
214
215 usleep(microseconds);
216#elif defined(HAVE_SLEEP)
217 // under BeOS sleep() takes seconds (what about other platforms, if any?)
218 sleep(microseconds * 1000000);
219#else // !sleep function
220 #error "usleep() or nanosleep() function required for wxMicroSleep"
221#endif // sleep function
222}
223
224void wxMilliSleep(unsigned long milliseconds)
225{
226 wxMicroSleep(milliseconds*1000);
227}
228
229// ----------------------------------------------------------------------------
230// process management
231// ----------------------------------------------------------------------------
232
233int wxKill(long pid, wxSignal sig, wxKillError *rc, int flags)
234{
235 int err = kill((pid_t) (flags & wxKILL_CHILDREN) ? -pid : pid, (int)sig);
236 if ( rc )
237 {
238 switch ( err ? errno : 0 )
239 {
240 case 0:
241 *rc = wxKILL_OK;
242 break;
243
244 case EINVAL:
245 *rc = wxKILL_BAD_SIGNAL;
246 break;
247
248 case EPERM:
249 *rc = wxKILL_ACCESS_DENIED;
250 break;
251
252 case ESRCH:
253 *rc = wxKILL_NO_PROCESS;
254 break;
255
256 default:
257 // this goes against Unix98 docs so log it
258 wxLogDebug(_T("unexpected kill(2) return value %d"), err);
259
260 // something else...
261 *rc = wxKILL_ERROR;
262 }
263 }
264
265 return err;
266}
267
268// Shutdown or reboot the PC
269bool wxShutdown(int flags)
270{
271 flags &= ~wxSHUTDOWN_FORCE;
272
273 wxChar level;
274 switch ( flags )
275 {
276 case wxSHUTDOWN_POWEROFF:
277 level = _T('0');
278 break;
279
280 case wxSHUTDOWN_REBOOT:
281 level = _T('6');
282 break;
283
284 case wxSHUTDOWN_LOGOFF:
285 // TODO: use dcop to log off?
286 return false;
287
288 default:
289 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
290 return false;
291 }
292
293 return system(wxString::Format("init %c", level).mb_str()) == 0;
294}
295
296// ----------------------------------------------------------------------------
297// wxStream classes to support IO redirection in wxExecute
298// ----------------------------------------------------------------------------
299
300#if HAS_PIPE_INPUT_STREAM
301
302bool wxPipeInputStream::CanRead() const
303{
304 if ( m_lasterror == wxSTREAM_EOF )
305 return false;
306
307 // check if there is any input available
308 struct timeval tv;
309 tv.tv_sec = 0;
310 tv.tv_usec = 0;
311
312 const int fd = m_file->fd();
313
314 fd_set readfds;
315
316 wxFD_ZERO(&readfds);
317 wxFD_SET(fd, &readfds);
318
319 switch ( select(fd + 1, &readfds, NULL, NULL, &tv) )
320 {
321 case -1:
322 wxLogSysError(_("Impossible to get child process input"));
323 // fall through
324
325 case 0:
326 return false;
327
328 default:
329 wxFAIL_MSG(_T("unexpected select() return value"));
330 // still fall through
331
332 case 1:
333 // input available -- or maybe not, as select() returns 1 when a
334 // read() will complete without delay, but it could still not read
335 // anything
336 return !Eof();
337 }
338}
339
340#endif // HAS_PIPE_INPUT_STREAM
341
342// ----------------------------------------------------------------------------
343// wxShell
344// ----------------------------------------------------------------------------
345
346static wxString wxMakeShellCommand(const wxString& command)
347{
348 wxString cmd;
349 if ( !command )
350 {
351 // just an interactive shell
352 cmd = _T("xterm");
353 }
354 else
355 {
356 // execute command in a shell
357 cmd << _T("/bin/sh -c '") << command << _T('\'');
358 }
359
360 return cmd;
361}
362
363bool wxShell(const wxString& command)
364{
365 return wxExecute(wxMakeShellCommand(command), wxEXEC_SYNC) == 0;
366}
367
368bool wxShell(const wxString& command, wxArrayString& output)
369{
370 wxCHECK_MSG( !command.empty(), false, _T("can't exec shell non interactively") );
371
372 return wxExecute(wxMakeShellCommand(command), output);
373}
374
375namespace
376{
377
378// helper class for storing arguments as char** array suitable for passing to
379// execvp(), whatever form they were passed to us
380class ArgsArray
381{
382public:
383 ArgsArray(const wxArrayString& args)
384 {
385 Init(args.size());
386
387 for ( int i = 0; i < m_argc; i++ )
388 {
389 m_argv[i] = wxStrdup(args[i]);
390 }
391 }
392
393#if wxUSE_UNICODE
394 ArgsArray(wchar_t **wargv)
395 {
396 int argc = 0;
397 while ( *wargv++ )
398 argc++;
399
400 Init(argc);
401
402 for ( int i = 0; i < m_argc; i++ )
403 {
404 m_argv[i] = wxSafeConvertWX2MB(wargv[i]).release();
405 }
406 }
407#endif // wxUSE_UNICODE
408
409 ~ArgsArray()
410 {
411 for ( int i = 0; i < m_argc; i++ )
412 {
413 free(m_argv[i]);
414 }
415
416 delete [] m_argv;
417 }
418
419 operator char**() const { return m_argv; }
420
421private:
422 void Init(int argc)
423 {
424 m_argc = argc;
425 m_argv = new char *[m_argc + 1];
426 m_argv[m_argc] = NULL;
427 }
428
429 int m_argc;
430 char **m_argv;
431
432 DECLARE_NO_COPY_CLASS(ArgsArray)
433};
434
435} // anonymous namespace
436
437// these functions are in src/osx/carbon/utils.cpp for wxMac
438#ifndef __WXMAC__
439
440// ----------------------------------------------------------------------------
441// Launch document with default app
442// ----------------------------------------------------------------------------
443
444bool wxLaunchDefaultApplication(const wxString& document, int flags)
445{
446 wxUnusedVar(flags);
447
448 // Our best best is to use xdg-open from freedesktop.org cross-desktop
449 // compatibility suite xdg-utils
450 // (see http://portland.freedesktop.org/wiki/) -- this is installed on
451 // most modern distributions and may be tweaked by them to handle
452 // distribution specifics.
453 wxString path, xdg_open;
454 if ( wxGetEnv("PATH", &path) &&
455 wxFindFileInPath(&xdg_open, path, "xdg-open") )
456 {
457 if ( wxExecute(xdg_open + " " + document) )
458 return true;
459 }
460
461 return false;
462}
463
464// ----------------------------------------------------------------------------
465// Launch default browser
466// ----------------------------------------------------------------------------
467
468bool wxDoLaunchDefaultBrowser(const wxString& url, int flags)
469{
470 wxUnusedVar(flags);
471
472 // Our best best is to use xdg-open from freedesktop.org cross-desktop
473 // compatibility suite xdg-utils
474 // (see http://portland.freedesktop.org/wiki/) -- this is installed on
475 // most modern distributions and may be tweaked by them to handle
476 // distribution specifics. Only if that fails, try to find the right
477 // browser ourselves.
478 wxString path, xdg_open;
479 if ( wxGetEnv("PATH", &path) &&
480 wxFindFileInPath(&xdg_open, path, "xdg-open") )
481 {
482 if ( wxExecute(xdg_open + " " + url) )
483 return true;
484 }
485
486 wxString desktop = wxTheApp->GetTraits()->GetDesktopEnvironment();
487
488 // GNOME and KDE desktops have some applications which should be always installed
489 // together with their main parts, which give us the
490 if (desktop == wxT("GNOME"))
491 {
492 wxArrayString errors;
493 wxArrayString output;
494
495 // gconf will tell us the path of the application to use as browser
496 long res = wxExecute( wxT("gconftool-2 --get /desktop/gnome/applications/browser/exec"),
497 output, errors, wxEXEC_NODISABLE );
498 if (res >= 0 && errors.GetCount() == 0)
499 {
500 wxString cmd = output[0];
501 cmd << _T(' ') << url;
502 if (wxExecute(cmd))
503 return true;
504 }
505 }
506 else if (desktop == wxT("KDE"))
507 {
508 // kfmclient directly opens the given URL
509 if (wxExecute(wxT("kfmclient openURL ") + url))
510 return true;
511 }
512
513 return false;
514}
515
516#endif // __WXMAC__
517
518// ----------------------------------------------------------------------------
519// wxExecute implementations
520// ----------------------------------------------------------------------------
521
522#if defined(__DARWIN__)
523bool wxMacLaunch(char **argv);
524#endif
525
526long wxExecute(const wxString& command, int flags, wxProcess *process)
527{
528 ArgsArray argv(wxCmdLineParser::ConvertStringToArgs(command,
529 wxCMD_LINE_SPLIT_UNIX));
530
531 return wxExecute(argv, flags, process);
532}
533
534#if wxUSE_UNICODE
535
536long wxExecute(wchar_t **wargv, int flags, wxProcess *process)
537{
538 ArgsArray argv(wargv);
539
540 return wxExecute(argv, flags, process);
541}
542
543#endif // wxUSE_UNICODE
544
545// wxExecute: the real worker function
546long wxExecute(char **argv, int flags, wxProcess *process)
547{
548 // for the sync execution, we return -1 to indicate failure, but for async
549 // case we return 0 which is never a valid PID
550 //
551 // we define this as a macro, not a variable, to avoid compiler warnings
552 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
553 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
554
555 wxCHECK_MSG( *argv, ERROR_RETURN_CODE, wxT("can't exec empty command") );
556
557#if wxUSE_THREADS
558 // fork() doesn't mix well with POSIX threads: on many systems the program
559 // deadlocks or crashes for some reason. Probably our code is buggy and
560 // doesn't do something which must be done to allow this to work, but I
561 // don't know what yet, so for now just warn the user (this is the least we
562 // can do) about it
563 wxASSERT_MSG( wxThread::IsMain(),
564 _T("wxExecute() can be called only from the main thread") );
565#endif // wxUSE_THREADS
566
567#if defined(__WXCOCOA__) || ( defined(__WXOSX_MAC__) && wxOSX_USE_COCOA_OR_CARBON )
568 // wxMacLaunch() only executes app bundles and only does it asynchronously.
569 // It returns false if the target is not an app bundle, thus falling
570 // through to the regular code for non app bundles.
571 if ( !(flags & wxEXEC_SYNC) && wxMacLaunch(argv) )
572 {
573 // we don't have any PID to return so just make up something non null
574 return -1;
575 }
576#endif // __DARWIN__
577
578
579 // this struct contains all information which we use for housekeeping
580 wxExecuteData execData;
581 execData.flags = flags;
582 execData.process = process;
583
584 // create pipes
585 if ( !execData.pipeEndProcDetect.Create() )
586 {
587 wxLogError( _("Failed to execute '%s'\n"), *argv );
588
589 return ERROR_RETURN_CODE;
590 }
591
592 // pipes for inter process communication
593 wxPipe pipeIn, // stdin
594 pipeOut, // stdout
595 pipeErr; // stderr
596
597 if ( process && process->IsRedirected() )
598 {
599 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
600 {
601 wxLogError( _("Failed to execute '%s'\n"), *argv );
602
603 return ERROR_RETURN_CODE;
604 }
605 }
606
607 // fork the process
608 //
609 // NB: do *not* use vfork() here, it completely breaks this code for some
610 // reason under Solaris (and maybe others, although not under Linux)
611 // But on OpenVMS we do not have fork so we have to use vfork and
612 // cross our fingers that it works.
613#ifdef __VMS
614 pid_t pid = vfork();
615#else
616 pid_t pid = fork();
617#endif
618 if ( pid == -1 ) // error?
619 {
620 wxLogSysError( _("Fork failed") );
621
622 return ERROR_RETURN_CODE;
623 }
624 else if ( pid == 0 ) // we're in child
625 {
626 // NB: we used to close all the unused descriptors of the child here
627 // but this broke some programs which relied on e.g. FD 1 being
628 // always opened so don't do it any more, after all there doesn't
629 // seem to be any real problem with keeping them opened
630
631#if !defined(__VMS) && !defined(__EMX__)
632 if ( flags & wxEXEC_MAKE_GROUP_LEADER )
633 {
634 // Set process group to child process' pid. Then killing -pid
635 // of the parent will kill the process and all of its children.
636 setsid();
637 }
638#endif // !__VMS
639
640 // reading side can be safely closed but we should keep the write one
641 // opened, it will be only closed when the process terminates resulting
642 // in a read notification to the parent
643 execData.pipeEndProcDetect.Detach(wxPipe::Write);
644 execData.pipeEndProcDetect.Close();
645
646 // redirect stdin, stdout and stderr
647 if ( pipeIn.IsOk() )
648 {
649 if ( dup2(pipeIn[wxPipe::Read], STDIN_FILENO) == -1 ||
650 dup2(pipeOut[wxPipe::Write], STDOUT_FILENO) == -1 ||
651 dup2(pipeErr[wxPipe::Write], STDERR_FILENO) == -1 )
652 {
653 wxLogSysError(_("Failed to redirect child process input/output"));
654 }
655
656 pipeIn.Close();
657 pipeOut.Close();
658 pipeErr.Close();
659 }
660
661 execvp(*argv, argv);
662
663 fprintf(stderr, "execvp(");
664 for ( char **a = argv; *a; a++ )
665 fprintf(stderr, "%s%s", a == argv ? "" : ", ", *a);
666 fprintf(stderr, ") failed with error %d!\n", errno);
667
668 // there is no return after successful exec()
669 _exit(-1);
670
671 // some compilers complain about missing return - of course, they
672 // should know that exit() doesn't return but what else can we do if
673 // they don't?
674 //
675 // and, sure enough, other compilers complain about unreachable code
676 // after exit() call, so we can just always have return here...
677#if defined(__VMS) || defined(__INTEL_COMPILER)
678 return 0;
679#endif
680 }
681 else // we're in parent
682 {
683 // save it for WaitForChild() use
684 execData.pid = pid;
685
686 // prepare for IO redirection
687
688#if HAS_PIPE_INPUT_STREAM
689 // the input buffer bufOut is connected to stdout, this is why it is
690 // called bufOut and not bufIn
691 wxStreamTempInputBuffer bufOut,
692 bufErr;
693
694 if ( process && process->IsRedirected() )
695 {
696 wxOutputStream *inStream =
697 new wxFileOutputStream(pipeIn.Detach(wxPipe::Write));
698
699 const int fdOut = pipeOut.Detach(wxPipe::Read);
700 wxPipeInputStream *outStream = new wxPipeInputStream(fdOut);
701
702 const int fdErr = pipeErr.Detach(wxPipe::Read);
703 wxPipeInputStream *errStream = new wxPipeInputStream(fdErr);
704
705 process->SetPipeStreams(outStream, inStream, errStream);
706
707 bufOut.Init(outStream);
708 bufErr.Init(errStream);
709
710 execData.bufOut = &bufOut;
711 execData.bufErr = &bufErr;
712
713 execData.fdOut = fdOut;
714 execData.fdErr = fdErr;
715 }
716#endif // HAS_PIPE_INPUT_STREAM
717
718 if ( pipeIn.IsOk() )
719 {
720 pipeIn.Close();
721 pipeOut.Close();
722 pipeErr.Close();
723 }
724
725 // we want this function to work even if there is no wxApp so ensure
726 // that we have a valid traits pointer
727 wxConsoleAppTraits traitsConsole;
728 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
729 if ( !traits )
730 traits = &traitsConsole;
731
732 return traits->WaitForChild(execData);
733 }
734
735#if !defined(__VMS) && !defined(__INTEL_COMPILER)
736 return ERROR_RETURN_CODE;
737#endif
738}
739
740#undef ERROR_RETURN_CODE
741
742// ----------------------------------------------------------------------------
743// file and directory functions
744// ----------------------------------------------------------------------------
745
746const wxChar* wxGetHomeDir( wxString *home )
747{
748 *home = wxGetUserHome();
749 wxString tmp;
750 if ( home->empty() )
751 *home = wxT("/");
752#ifdef __VMS
753 tmp = *home;
754 if ( tmp.Last() != wxT(']'))
755 if ( tmp.Last() != wxT('/')) *home << wxT('/');
756#endif
757 return home->c_str();
758}
759
760wxString wxGetUserHome( const wxString &user )
761{
762 struct passwd *who = (struct passwd *) NULL;
763
764 if ( !user )
765 {
766 wxChar *ptr;
767
768 if ((ptr = wxGetenv(wxT("HOME"))) != NULL)
769 {
770 return ptr;
771 }
772
773 if ((ptr = wxGetenv(wxT("USER"))) != NULL ||
774 (ptr = wxGetenv(wxT("LOGNAME"))) != NULL)
775 {
776 who = getpwnam(wxSafeConvertWX2MB(ptr));
777 }
778
779 // make sure the user exists!
780 if ( !who )
781 {
782 who = getpwuid(getuid());
783 }
784 }
785 else
786 {
787 who = getpwnam (user.mb_str());
788 }
789
790 return wxSafeConvertMB2WX(who ? who->pw_dir : 0);
791}
792
793// ----------------------------------------------------------------------------
794// network and user id routines
795// ----------------------------------------------------------------------------
796
797// private utility function which returns output of the given command, removing
798// the trailing newline
799static wxString wxGetCommandOutput(const wxString &cmd)
800{
801 FILE *f = popen(cmd.ToAscii(), "r");
802 if ( !f )
803 {
804 wxLogSysError(_T("Executing \"%s\" failed"), cmd.c_str());
805 return wxEmptyString;
806 }
807
808 wxString s;
809 char buf[256];
810 while ( !feof(f) )
811 {
812 if ( !fgets(buf, sizeof(buf), f) )
813 break;
814
815 s += wxString::FromAscii(buf);
816 }
817
818 pclose(f);
819
820 if ( !s.empty() && s.Last() == _T('\n') )
821 s.RemoveLast();
822
823 return s;
824}
825
826// retrieve either the hostname or FQDN depending on platform (caller must
827// check whether it's one or the other, this is why this function is for
828// private use only)
829static bool wxGetHostNameInternal(wxChar *buf, int sz)
830{
831 wxCHECK_MSG( buf, false, wxT("NULL pointer in wxGetHostNameInternal") );
832
833 *buf = wxT('\0');
834
835 // we're using uname() which is POSIX instead of less standard sysinfo()
836#if defined(HAVE_UNAME)
837 struct utsname uts;
838 bool ok = uname(&uts) != -1;
839 if ( ok )
840 {
841 wxStrlcpy(buf, wxSafeConvertMB2WX(uts.nodename), sz);
842 }
843#elif defined(HAVE_GETHOSTNAME)
844 char cbuf[sz];
845 bool ok = gethostname(cbuf, sz) != -1;
846 if ( ok )
847 {
848 wxStrlcpy(buf, wxSafeConvertMB2WX(cbuf), sz);
849 }
850#else // no uname, no gethostname
851 wxFAIL_MSG(wxT("don't know host name for this machine"));
852
853 bool ok = false;
854#endif // uname/gethostname
855
856 if ( !ok )
857 {
858 wxLogSysError(_("Cannot get the hostname"));
859 }
860
861 return ok;
862}
863
864bool wxGetHostName(wxChar *buf, int sz)
865{
866 bool ok = wxGetHostNameInternal(buf, sz);
867
868 if ( ok )
869 {
870 // BSD systems return the FQDN, we only want the hostname, so extract
871 // it (we consider that dots are domain separators)
872 wxChar *dot = wxStrchr(buf, wxT('.'));
873 if ( dot )
874 {
875 // nuke it
876 *dot = wxT('\0');
877 }
878 }
879
880 return ok;
881}
882
883bool wxGetFullHostName(wxChar *buf, int sz)
884{
885 bool ok = wxGetHostNameInternal(buf, sz);
886
887 if ( ok )
888 {
889 if ( !wxStrchr(buf, wxT('.')) )
890 {
891 struct hostent *host = gethostbyname(wxSafeConvertWX2MB(buf));
892 if ( !host )
893 {
894 wxLogSysError(_("Cannot get the official hostname"));
895
896 ok = false;
897 }
898 else
899 {
900 // the canonical name
901 wxStrlcpy(buf, wxSafeConvertMB2WX(host->h_name), sz);
902 }
903 }
904 //else: it's already a FQDN (BSD behaves this way)
905 }
906
907 return ok;
908}
909
910bool wxGetUserId(wxChar *buf, int sz)
911{
912 struct passwd *who;
913
914 *buf = wxT('\0');
915 if ((who = getpwuid(getuid ())) != NULL)
916 {
917 wxStrlcpy (buf, wxSafeConvertMB2WX(who->pw_name), sz);
918 return true;
919 }
920
921 return false;
922}
923
924bool wxGetUserName(wxChar *buf, int sz)
925{
926#ifdef HAVE_PW_GECOS
927 struct passwd *who;
928
929 *buf = wxT('\0');
930 if ((who = getpwuid (getuid ())) != NULL)
931 {
932 char *comma = strchr(who->pw_gecos, ',');
933 if (comma)
934 *comma = '\0'; // cut off non-name comment fields
935 wxStrlcpy(buf, wxSafeConvertMB2WX(who->pw_gecos), sz);
936 return true;
937 }
938
939 return false;
940#else // !HAVE_PW_GECOS
941 return wxGetUserId(buf, sz);
942#endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
943}
944
945bool wxIsPlatform64Bit()
946{
947 const wxString machine = wxGetCommandOutput(wxT("uname -m"));
948
949 // the test for "64" is obviously not 100% reliable but seems to work fine
950 // in practice
951 return machine.Contains(wxT("64")) ||
952 machine.Contains(wxT("alpha"));
953}
954
955// these functions are in src/osx/utilsexc_base.cpp for wxMac
956#ifndef __WXMAC__
957
958wxOperatingSystemId wxGetOsVersion(int *verMaj, int *verMin)
959{
960 // get OS version
961 int major, minor;
962 wxString release = wxGetCommandOutput(wxT("uname -r"));
963 if ( release.empty() ||
964 wxSscanf(release.c_str(), wxT("%d.%d"), &major, &minor) != 2 )
965 {
966 // failed to get version string or unrecognized format
967 major =
968 minor = -1;
969 }
970
971 if ( verMaj )
972 *verMaj = major;
973 if ( verMin )
974 *verMin = minor;
975
976 // try to understand which OS are we running
977 wxString kernel = wxGetCommandOutput(wxT("uname -s"));
978 if ( kernel.empty() )
979 kernel = wxGetCommandOutput(wxT("uname -o"));
980
981 if ( kernel.empty() )
982 return wxOS_UNKNOWN;
983
984 return wxPlatformInfo::GetOperatingSystemId(kernel);
985}
986
987wxString wxGetOsDescription()
988{
989 return wxGetCommandOutput(wxT("uname -s -r -m"));
990}
991
992#endif // !__WXMAC__
993
994unsigned long wxGetProcessId()
995{
996 return (unsigned long)getpid();
997}
998
999wxMemorySize wxGetFreeMemory()
1000{
1001#if defined(__LINUX__)
1002 // get it from /proc/meminfo
1003 FILE *fp = fopen("/proc/meminfo", "r");
1004 if ( fp )
1005 {
1006 long memFree = -1;
1007
1008 char buf[1024];
1009 if ( fgets(buf, WXSIZEOF(buf), fp) && fgets(buf, WXSIZEOF(buf), fp) )
1010 {
1011 // /proc/meminfo changed its format in kernel 2.6
1012 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
1013 {
1014 unsigned long cached, buffers;
1015 sscanf(buf, "MemFree: %ld", &memFree);
1016
1017 fgets(buf, WXSIZEOF(buf), fp);
1018 sscanf(buf, "Buffers: %lu", &buffers);
1019
1020 fgets(buf, WXSIZEOF(buf), fp);
1021 sscanf(buf, "Cached: %lu", &cached);
1022
1023 // add to "MemFree" also the "Buffers" and "Cached" values as
1024 // free(1) does as otherwise the value never makes sense: for
1025 // kernel 2.6 it's always almost 0
1026 memFree += buffers + cached;
1027
1028 // values here are always expressed in kB and we want bytes
1029 memFree *= 1024;
1030 }
1031 else // Linux 2.4 (or < 2.6, anyhow)
1032 {
1033 long memTotal, memUsed;
1034 sscanf(buf, "Mem: %ld %ld %ld", &memTotal, &memUsed, &memFree);
1035 }
1036 }
1037
1038 fclose(fp);
1039
1040 return (wxMemorySize)memFree;
1041 }
1042#elif defined(__SGI__)
1043 struct rminfo realmem;
1044 if ( sysmp(MP_SAGET, MPSA_RMINFO, &realmem, sizeof realmem) == 0 )
1045 return ((wxMemorySize)realmem.physmem * sysconf(_SC_PAGESIZE));
1046#elif defined(_SC_AVPHYS_PAGES)
1047 return ((wxMemorySize)sysconf(_SC_AVPHYS_PAGES))*sysconf(_SC_PAGESIZE);
1048//#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1049#endif
1050
1051 // can't find it out
1052 return -1;
1053}
1054
1055bool wxGetDiskSpace(const wxString& path, wxDiskspaceSize_t *pTotal, wxDiskspaceSize_t *pFree)
1056{
1057#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
1058 // the case to "char *" is needed for AIX 4.3
1059 wxStatfs_t fs;
1060 if ( wxStatfs((char *)(const char*)path.fn_str(), &fs) != 0 )
1061 {
1062 wxLogSysError( wxT("Failed to get file system statistics") );
1063
1064 return false;
1065 }
1066
1067 // under Solaris we also have to use f_frsize field instead of f_bsize
1068 // which is in general a multiple of f_frsize
1069#ifdef HAVE_STATVFS
1070 wxDiskspaceSize_t blockSize = fs.f_frsize;
1071#else // HAVE_STATFS
1072 wxDiskspaceSize_t blockSize = fs.f_bsize;
1073#endif // HAVE_STATVFS/HAVE_STATFS
1074
1075 if ( pTotal )
1076 {
1077 *pTotal = wxDiskspaceSize_t(fs.f_blocks) * blockSize;
1078 }
1079
1080 if ( pFree )
1081 {
1082 *pFree = wxDiskspaceSize_t(fs.f_bavail) * blockSize;
1083 }
1084
1085 return true;
1086#else // !HAVE_STATFS && !HAVE_STATVFS
1087 return false;
1088#endif // HAVE_STATFS
1089}
1090
1091// ----------------------------------------------------------------------------
1092// env vars
1093// ----------------------------------------------------------------------------
1094
1095#if USE_PUTENV
1096
1097WX_DECLARE_STRING_HASH_MAP(char *, wxEnvVars);
1098
1099static wxEnvVars gs_envVars;
1100
1101class wxSetEnvModule : public wxModule
1102{
1103public:
1104 virtual bool OnInit() { return true; }
1105 virtual void OnExit()
1106 {
1107 for ( wxEnvVars::const_iterator i = gs_envVars.begin();
1108 i != gs_envVars.end();
1109 ++i )
1110 {
1111 free(i->second);
1112 }
1113
1114 gs_envVars.clear();
1115 }
1116
1117 DECLARE_DYNAMIC_CLASS(wxSetEnvModule)
1118};
1119
1120IMPLEMENT_DYNAMIC_CLASS(wxSetEnvModule, wxModule)
1121
1122#endif // USE_PUTENV
1123
1124bool wxGetEnv(const wxString& var, wxString *value)
1125{
1126 // wxGetenv is defined as getenv()
1127 char *p = wxGetenv(var);
1128 if ( !p )
1129 return false;
1130
1131 if ( value )
1132 {
1133 *value = p;
1134 }
1135
1136 return true;
1137}
1138
1139static bool wxDoSetEnv(const wxString& variable, const char *value)
1140{
1141#if defined(HAVE_SETENV)
1142 if ( !value )
1143 {
1144#ifdef HAVE_UNSETENV
1145 // don't test unsetenv() return value: it's void on some systems (at
1146 // least Darwin)
1147 unsetenv(variable.mb_str());
1148 return true;
1149#else
1150 value = ""; // we can't pass NULL to setenv()
1151#endif
1152 }
1153
1154 return setenv(variable.mb_str(), value, 1 /* overwrite */) == 0;
1155#elif defined(HAVE_PUTENV)
1156 wxString s = variable;
1157 if ( value )
1158 s << _T('=') << value;
1159
1160 // transform to ANSI
1161 const wxWX2MBbuf p = s.mb_str();
1162
1163 char *buf = (char *)malloc(strlen(p) + 1);
1164 strcpy(buf, p);
1165
1166 // store the string to free() it later
1167 wxEnvVars::iterator i = gs_envVars.find(variable);
1168 if ( i != gs_envVars.end() )
1169 {
1170 free(i->second);
1171 i->second = buf;
1172 }
1173 else // this variable hadn't been set before
1174 {
1175 gs_envVars[variable] = buf;
1176 }
1177
1178 return putenv(buf) == 0;
1179#else // no way to set an env var
1180 return false;
1181#endif
1182}
1183
1184bool wxSetEnv(const wxString& variable, const wxString& value)
1185{
1186 return wxDoSetEnv(variable, value.mb_str());
1187}
1188
1189bool wxUnsetEnv(const wxString& variable)
1190{
1191 return wxDoSetEnv(variable, NULL);
1192}
1193
1194// ----------------------------------------------------------------------------
1195// signal handling
1196// ----------------------------------------------------------------------------
1197
1198#if wxUSE_ON_FATAL_EXCEPTION
1199
1200#include <signal.h>
1201
1202extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER)
1203{
1204 if ( wxTheApp )
1205 {
1206 // give the user a chance to do something special about this
1207 wxTheApp->OnFatalException();
1208 }
1209
1210 abort();
1211}
1212
1213bool wxHandleFatalExceptions(bool doit)
1214{
1215 // old sig handlers
1216 static bool s_savedHandlers = false;
1217 static struct sigaction s_handlerFPE,
1218 s_handlerILL,
1219 s_handlerBUS,
1220 s_handlerSEGV;
1221
1222 bool ok = true;
1223 if ( doit && !s_savedHandlers )
1224 {
1225 // install the signal handler
1226 struct sigaction act;
1227
1228 // some systems extend it with non std fields, so zero everything
1229 memset(&act, 0, sizeof(act));
1230
1231 act.sa_handler = wxFatalSignalHandler;
1232 sigemptyset(&act.sa_mask);
1233 act.sa_flags = 0;
1234
1235 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
1236 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
1237 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
1238 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
1239 if ( !ok )
1240 {
1241 wxLogDebug(_T("Failed to install our signal handler."));
1242 }
1243
1244 s_savedHandlers = true;
1245 }
1246 else if ( s_savedHandlers )
1247 {
1248 // uninstall the signal handler
1249 ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
1250 ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
1251 ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
1252 ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
1253 if ( !ok )
1254 {
1255 wxLogDebug(_T("Failed to uninstall our signal handler."));
1256 }
1257
1258 s_savedHandlers = false;
1259 }
1260 //else: nothing to do
1261
1262 return ok;
1263}
1264
1265#endif // wxUSE_ON_FATAL_EXCEPTION
1266
1267// ----------------------------------------------------------------------------
1268// wxExecute support
1269// ----------------------------------------------------------------------------
1270
1271int wxAppTraits::AddProcessCallback(wxEndProcessData *data, int fd)
1272{
1273 // define a custom handler processing only the closure of the descriptor
1274 struct wxEndProcessFDIOHandler : public wxFDIOHandler
1275 {
1276 wxEndProcessFDIOHandler(wxEndProcessData *data, int fd)
1277 : m_data(data), m_fd(fd)
1278 {
1279 }
1280
1281 virtual void OnReadWaiting()
1282 {
1283 wxFDIODispatcher::Get()->UnregisterFD(m_fd);
1284 close(m_fd);
1285
1286 wxHandleProcessTermination(m_data);
1287
1288 delete this;
1289 }
1290
1291 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1292 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1293
1294 wxEndProcessData * const m_data;
1295 const int m_fd;
1296 };
1297
1298 wxFDIODispatcher::Get()->RegisterFD
1299 (
1300 fd,
1301 new wxEndProcessFDIOHandler(data, fd),
1302 wxFDIO_INPUT
1303 );
1304 return fd; // unused, but return something unique for the tag
1305}
1306
1307bool wxAppTraits::CheckForRedirectedIO(wxExecuteData& execData)
1308{
1309#if HAS_PIPE_INPUT_STREAM
1310 bool hasIO = false;
1311
1312 if ( execData.bufOut && execData.bufOut->Update() )
1313 hasIO = true;
1314
1315 if ( execData.bufErr && execData.bufErr->Update() )
1316 hasIO = true;
1317
1318 return hasIO;
1319#else // !HAS_PIPE_INPUT_STREAM
1320 return false;
1321#endif // HAS_PIPE_INPUT_STREAM/!HAS_PIPE_INPUT_STREAM
1322}
1323
1324// helper classes/functions used by WaitForChild()
1325namespace
1326{
1327
1328// convenient base class for IO handlers which are registered for read
1329// notifications only and which also stores the FD we're reading from
1330//
1331// the derived classes still have to implement OnReadWaiting()
1332class wxReadFDIOHandler : public wxFDIOHandler
1333{
1334public:
1335 wxReadFDIOHandler(wxFDIODispatcher& disp, int fd) : m_fd(fd)
1336 {
1337 if ( fd )
1338 disp.RegisterFD(fd, this, wxFDIO_INPUT);
1339 }
1340
1341 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1342 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1343
1344protected:
1345 const int m_fd;
1346
1347 DECLARE_NO_COPY_CLASS(wxReadFDIOHandler)
1348};
1349
1350// class for monitoring our end of the process detection pipe, simply sets a
1351// flag when input on the pipe (which must be due to EOF) is detected
1352class wxEndHandler : public wxReadFDIOHandler
1353{
1354public:
1355 wxEndHandler(wxFDIODispatcher& disp, int fd)
1356 : wxReadFDIOHandler(disp, fd)
1357 {
1358 m_terminated = false;
1359 }
1360
1361 bool Terminated() const { return m_terminated; }
1362
1363 virtual void OnReadWaiting() { m_terminated = true; }
1364
1365private:
1366 bool m_terminated;
1367
1368 DECLARE_NO_COPY_CLASS(wxEndHandler)
1369};
1370
1371#if HAS_PIPE_INPUT_STREAM
1372
1373// class for monitoring our ends of child stdout/err, should be constructed
1374// with the FD and stream from wxExecuteData and will do nothing if they're
1375// invalid
1376//
1377// unlike wxEndHandler this class registers itself with the provided dispatcher
1378class wxRedirectedIOHandler : public wxReadFDIOHandler
1379{
1380public:
1381 wxRedirectedIOHandler(wxFDIODispatcher& disp,
1382 int fd,
1383 wxStreamTempInputBuffer *buf)
1384 : wxReadFDIOHandler(disp, fd),
1385 m_buf(buf)
1386 {
1387 }
1388
1389 virtual void OnReadWaiting()
1390 {
1391 m_buf->Update();
1392 }
1393
1394private:
1395 wxStreamTempInputBuffer * const m_buf;
1396
1397 DECLARE_NO_COPY_CLASS(wxRedirectedIOHandler)
1398};
1399
1400#endif // HAS_PIPE_INPUT_STREAM
1401
1402// helper function which calls waitpid() and analyzes the result
1403int DoWaitForChild(int pid, int flags = 0)
1404{
1405 wxASSERT_MSG( pid > 0, "invalid PID" );
1406
1407 int status, rc;
1408
1409 // loop while we're getting EINTR
1410 for ( ;; )
1411 {
1412 rc = waitpid(pid, &status, flags);
1413
1414 if ( rc != -1 || errno != EINTR )
1415 break;
1416 }
1417
1418 if ( rc == 0 )
1419 {
1420 // This can only happen if the child application closes our dummy pipe
1421 // that is used to monitor its lifetime; in that case, our best bet is
1422 // to pretend the process did terminate, because otherwise wxExecute()
1423 // would hang indefinitely (OnReadWaiting() won't be called again, the
1424 // descriptor is closed now).
1425 wxLogDebug("Child process (PID %d) still alive but pipe closed so "
1426 "generating a close notification", pid);
1427 }
1428 else if ( rc == -1 )
1429 {
1430 wxLogLastError(wxString::Format("waitpid(%d)", pid));
1431 }
1432 else // child did terminate
1433 {
1434 wxASSERT_MSG( rc == pid, "unexpected waitpid() return value" );
1435
1436 if ( WIFEXITED(status) )
1437 return WEXITSTATUS(status);
1438 else if ( WIFSIGNALED(status) )
1439 return -WTERMSIG(status);
1440 else
1441 {
1442 wxLogError("Child process (PID %d) exited for unknown reason, "
1443 "status = %d", pid, status);
1444 }
1445 }
1446
1447 return -1;
1448}
1449
1450} // anonymous namespace
1451
1452int wxAppTraits::WaitForChild(wxExecuteData& execData)
1453{
1454 if ( !(execData.flags & wxEXEC_SYNC) )
1455 {
1456 // asynchronous execution: just launch the process and return,
1457 // endProcData will be destroyed when it terminates (currently we leak
1458 // it if the process doesn't terminate before we do and this should be
1459 // fixed but it's not a real leak so it's not really very high
1460 // priority)
1461 wxEndProcessData *endProcData = new wxEndProcessData;
1462 endProcData->process = execData.process;
1463 endProcData->pid = execData.pid;
1464 endProcData->tag = AddProcessCallback
1465 (
1466 endProcData,
1467 execData.GetEndProcReadFD()
1468 );
1469 endProcData->async = true;
1470
1471 return execData.pid;
1472 }
1473 //else: synchronous execution case
1474
1475#if HAS_PIPE_INPUT_STREAM
1476 wxProcess * const process = execData.process;
1477 if ( process && process->IsRedirected() )
1478 {
1479 // we can't simply block waiting for the child to terminate as we would
1480 // dead lock if it writes more than the pipe buffer size (typically
1481 // 4KB) bytes of output -- it would then block waiting for us to read
1482 // the data while we'd block waiting for it to terminate
1483 //
1484 // so multiplex here waiting for any input from the child or closure of
1485 // the pipe used to indicate its termination
1486 wxSelectDispatcher disp;
1487
1488 wxEndHandler endHandler(disp, execData.GetEndProcReadFD());
1489
1490 wxRedirectedIOHandler outHandler(disp, execData.fdOut, execData.bufOut),
1491 errHandler(disp, execData.fdErr, execData.bufErr);
1492
1493 while ( !endHandler.Terminated() )
1494 {
1495 disp.Dispatch();
1496 }
1497 }
1498 //else: no IO redirection, just block waiting for the child to exit
1499#endif // HAS_PIPE_INPUT_STREAM
1500
1501 return DoWaitForChild(execData.pid);
1502}
1503
1504void wxHandleProcessTermination(wxEndProcessData *data)
1505{
1506 data->exitcode = DoWaitForChild(data->pid, WNOHANG);
1507
1508 // notify user about termination if required
1509 if ( data->process )
1510 {
1511 data->process->OnTerminate(data->pid, data->exitcode);
1512 }
1513
1514 if ( data->async )
1515 {
1516 // in case of asynchronous execution we don't need this data any more
1517 // after the child terminates
1518 delete data;
1519 }
1520 else // sync execution
1521 {
1522 // let wxExecute() know that the process has terminated
1523 data->pid = 0;
1524 }
1525}
1526