]> git.saurik.com Git - wxWidgets.git/blob - src/unix/utilsunx.cpp
Fixed wxscintilla compilation for wxDFB.
[wxWidgets.git] / src / unix / utilsunx.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/utilsunx.cpp
3 // Purpose: generic Unix implementation of many wx functions (for wxBase)
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
192 void wxSleep(int nSecs)
193 {
194 sleep(nSecs);
195 }
196
197 void 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, 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
224 void wxMilliSleep(unsigned long milliseconds)
225 {
226 wxMicroSleep(milliseconds*1000);
227 }
228
229 // ----------------------------------------------------------------------------
230 // process management
231 // ----------------------------------------------------------------------------
232
233 int 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(wxT("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
269 bool wxShutdown(int flags)
270 {
271 flags &= ~wxSHUTDOWN_FORCE;
272
273 wxChar level;
274 switch ( flags )
275 {
276 case wxSHUTDOWN_POWEROFF:
277 level = wxT('0');
278 break;
279
280 case wxSHUTDOWN_REBOOT:
281 level = wxT('6');
282 break;
283
284 case wxSHUTDOWN_LOGOFF:
285 // TODO: use dcop to log off?
286 return false;
287
288 default:
289 wxFAIL_MSG( wxT("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
302 bool 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(wxT("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
346 static wxString wxMakeShellCommand(const wxString& command)
347 {
348 wxString cmd;
349 if ( !command )
350 {
351 // just an interactive shell
352 cmd = wxT("xterm");
353 }
354 else
355 {
356 // execute command in a shell
357 cmd << wxT("/bin/sh -c '") << command << wxT('\'');
358 }
359
360 return cmd;
361 }
362
363 bool wxShell(const wxString& command)
364 {
365 return wxExecute(wxMakeShellCommand(command), wxEXEC_SYNC) == 0;
366 }
367
368 bool wxShell(const wxString& command, wxArrayString& output)
369 {
370 wxCHECK_MSG( !command.empty(), false, wxT("can't exec shell non interactively") );
371
372 return wxExecute(wxMakeShellCommand(command), output);
373 }
374
375 namespace
376 {
377
378 // helper class for storing arguments as char** array suitable for passing to
379 // execvp(), whatever form they were passed to us
380 class ArgsArray
381 {
382 public:
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[argc] )
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
421 private:
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 wxDECLARE_NO_COPY_CLASS(ArgsArray);
433 };
434
435 } // anonymous namespace
436
437 // ----------------------------------------------------------------------------
438 // wxExecute implementations
439 // ----------------------------------------------------------------------------
440
441 #if defined(__DARWIN__)
442 bool wxMacLaunch(char **argv);
443 #endif
444
445 long wxExecute(const wxString& command, int flags, wxProcess *process)
446 {
447 ArgsArray argv(wxCmdLineParser::ConvertStringToArgs(command,
448 wxCMD_LINE_SPLIT_UNIX));
449
450 return wxExecute(argv, flags, process);
451 }
452
453 #if wxUSE_UNICODE
454
455 long wxExecute(wchar_t **wargv, int flags, wxProcess *process)
456 {
457 ArgsArray argv(wargv);
458
459 return wxExecute(argv, flags, process);
460 }
461
462 #endif // wxUSE_UNICODE
463
464 // wxExecute: the real worker function
465 long wxExecute(char **argv, int flags, wxProcess *process)
466 {
467 // for the sync execution, we return -1 to indicate failure, but for async
468 // case we return 0 which is never a valid PID
469 //
470 // we define this as a macro, not a variable, to avoid compiler warnings
471 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
472 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
473
474 wxCHECK_MSG( *argv, ERROR_RETURN_CODE, wxT("can't exec empty command") );
475
476 #if wxUSE_THREADS
477 // fork() doesn't mix well with POSIX threads: on many systems the program
478 // deadlocks or crashes for some reason. Probably our code is buggy and
479 // doesn't do something which must be done to allow this to work, but I
480 // don't know what yet, so for now just warn the user (this is the least we
481 // can do) about it
482 wxASSERT_MSG( wxThread::IsMain(),
483 wxT("wxExecute() can be called only from the main thread") );
484 #endif // wxUSE_THREADS
485
486 #if defined(__WXCOCOA__) || ( defined(__WXOSX_MAC__) && wxOSX_USE_COCOA_OR_CARBON )
487 // wxMacLaunch() only executes app bundles and only does it asynchronously.
488 // It returns false if the target is not an app bundle, thus falling
489 // through to the regular code for non app bundles.
490 if ( !(flags & wxEXEC_SYNC) && wxMacLaunch(argv) )
491 {
492 // we don't have any PID to return so just make up something non null
493 return -1;
494 }
495 #endif // __DARWIN__
496
497
498 // this struct contains all information which we use for housekeeping
499 wxExecuteData execData;
500 execData.flags = flags;
501 execData.process = process;
502
503 // create pipes
504 if ( !execData.pipeEndProcDetect.Create() )
505 {
506 wxLogError( _("Failed to execute '%s'\n"), *argv );
507
508 return ERROR_RETURN_CODE;
509 }
510
511 // pipes for inter process communication
512 wxPipe pipeIn, // stdin
513 pipeOut, // stdout
514 pipeErr; // stderr
515
516 if ( process && process->IsRedirected() )
517 {
518 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
519 {
520 wxLogError( _("Failed to execute '%s'\n"), *argv );
521
522 return ERROR_RETURN_CODE;
523 }
524 }
525
526 // fork the process
527 //
528 // NB: do *not* use vfork() here, it completely breaks this code for some
529 // reason under Solaris (and maybe others, although not under Linux)
530 // But on OpenVMS we do not have fork so we have to use vfork and
531 // cross our fingers that it works.
532 #ifdef __VMS
533 pid_t pid = vfork();
534 #else
535 pid_t pid = fork();
536 #endif
537 if ( pid == -1 ) // error?
538 {
539 wxLogSysError( _("Fork failed") );
540
541 return ERROR_RETURN_CODE;
542 }
543 else if ( pid == 0 ) // we're in child
544 {
545 // NB: we used to close all the unused descriptors of the child here
546 // but this broke some programs which relied on e.g. FD 1 being
547 // always opened so don't do it any more, after all there doesn't
548 // seem to be any real problem with keeping them opened
549
550 #if !defined(__VMS) && !defined(__EMX__)
551 if ( flags & wxEXEC_MAKE_GROUP_LEADER )
552 {
553 // Set process group to child process' pid. Then killing -pid
554 // of the parent will kill the process and all of its children.
555 setsid();
556 }
557 #endif // !__VMS
558
559 // reading side can be safely closed but we should keep the write one
560 // opened, it will be only closed when the process terminates resulting
561 // in a read notification to the parent
562 execData.pipeEndProcDetect.Detach(wxPipe::Write);
563 execData.pipeEndProcDetect.Close();
564
565 // redirect stdin, stdout and stderr
566 if ( pipeIn.IsOk() )
567 {
568 if ( dup2(pipeIn[wxPipe::Read], STDIN_FILENO) == -1 ||
569 dup2(pipeOut[wxPipe::Write], STDOUT_FILENO) == -1 ||
570 dup2(pipeErr[wxPipe::Write], STDERR_FILENO) == -1 )
571 {
572 wxLogSysError(_("Failed to redirect child process input/output"));
573 }
574
575 pipeIn.Close();
576 pipeOut.Close();
577 pipeErr.Close();
578 }
579
580 execvp(*argv, argv);
581
582 fprintf(stderr, "execvp(");
583 for ( char **a = argv; *a; a++ )
584 fprintf(stderr, "%s%s", a == argv ? "" : ", ", *a);
585 fprintf(stderr, ") failed with error %d!\n", errno);
586
587 // there is no return after successful exec()
588 _exit(-1);
589
590 // some compilers complain about missing return - of course, they
591 // should know that exit() doesn't return but what else can we do if
592 // they don't?
593 //
594 // and, sure enough, other compilers complain about unreachable code
595 // after exit() call, so we can just always have return here...
596 #if defined(__VMS) || defined(__INTEL_COMPILER)
597 return 0;
598 #endif
599 }
600 else // we're in parent
601 {
602 // save it for WaitForChild() use
603 execData.pid = pid;
604 if (execData.process)
605 execData.process->SetPid(pid); // and also in the wxProcess
606
607 // prepare for IO redirection
608
609 #if HAS_PIPE_INPUT_STREAM
610 // the input buffer bufOut is connected to stdout, this is why it is
611 // called bufOut and not bufIn
612 wxStreamTempInputBuffer bufOut,
613 bufErr;
614
615 if ( process && process->IsRedirected() )
616 {
617 wxOutputStream *inStream =
618 new wxFileOutputStream(pipeIn.Detach(wxPipe::Write));
619
620 const int fdOut = pipeOut.Detach(wxPipe::Read);
621 wxPipeInputStream *outStream = new wxPipeInputStream(fdOut);
622
623 const int fdErr = pipeErr.Detach(wxPipe::Read);
624 wxPipeInputStream *errStream = new wxPipeInputStream(fdErr);
625
626 process->SetPipeStreams(outStream, inStream, errStream);
627
628 bufOut.Init(outStream);
629 bufErr.Init(errStream);
630
631 execData.bufOut = &bufOut;
632 execData.bufErr = &bufErr;
633
634 execData.fdOut = fdOut;
635 execData.fdErr = fdErr;
636 }
637 #endif // HAS_PIPE_INPUT_STREAM
638
639 if ( pipeIn.IsOk() )
640 {
641 pipeIn.Close();
642 pipeOut.Close();
643 pipeErr.Close();
644 }
645
646 // we want this function to work even if there is no wxApp so ensure
647 // that we have a valid traits pointer
648 wxConsoleAppTraits traitsConsole;
649 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
650 if ( !traits )
651 traits = &traitsConsole;
652
653 return traits->WaitForChild(execData);
654 }
655
656 #if !defined(__VMS) && !defined(__INTEL_COMPILER)
657 return ERROR_RETURN_CODE;
658 #endif
659 }
660
661 #undef ERROR_RETURN_CODE
662
663 // ----------------------------------------------------------------------------
664 // file and directory functions
665 // ----------------------------------------------------------------------------
666
667 const wxChar* wxGetHomeDir( wxString *home )
668 {
669 *home = wxGetUserHome();
670 wxString tmp;
671 if ( home->empty() )
672 *home = wxT("/");
673 #ifdef __VMS
674 tmp = *home;
675 if ( tmp.Last() != wxT(']'))
676 if ( tmp.Last() != wxT('/')) *home << wxT('/');
677 #endif
678 return home->c_str();
679 }
680
681 wxString wxGetUserHome( const wxString &user )
682 {
683 struct passwd *who = (struct passwd *) NULL;
684
685 if ( !user )
686 {
687 wxChar *ptr;
688
689 if ((ptr = wxGetenv(wxT("HOME"))) != NULL)
690 {
691 return ptr;
692 }
693
694 if ((ptr = wxGetenv(wxT("USER"))) != NULL ||
695 (ptr = wxGetenv(wxT("LOGNAME"))) != NULL)
696 {
697 who = getpwnam(wxSafeConvertWX2MB(ptr));
698 }
699
700 // make sure the user exists!
701 if ( !who )
702 {
703 who = getpwuid(getuid());
704 }
705 }
706 else
707 {
708 who = getpwnam (user.mb_str());
709 }
710
711 return wxSafeConvertMB2WX(who ? who->pw_dir : 0);
712 }
713
714 // ----------------------------------------------------------------------------
715 // network and user id routines
716 // ----------------------------------------------------------------------------
717
718 // private utility function which returns output of the given command, removing
719 // the trailing newline
720 static wxString wxGetCommandOutput(const wxString &cmd)
721 {
722 FILE *f = popen(cmd.ToAscii(), "r");
723 if ( !f )
724 {
725 wxLogSysError(wxT("Executing \"%s\" failed"), cmd.c_str());
726 return wxEmptyString;
727 }
728
729 wxString s;
730 char buf[256];
731 while ( !feof(f) )
732 {
733 if ( !fgets(buf, sizeof(buf), f) )
734 break;
735
736 s += wxString::FromAscii(buf);
737 }
738
739 pclose(f);
740
741 if ( !s.empty() && s.Last() == wxT('\n') )
742 s.RemoveLast();
743
744 return s;
745 }
746
747 // retrieve either the hostname or FQDN depending on platform (caller must
748 // check whether it's one or the other, this is why this function is for
749 // private use only)
750 static bool wxGetHostNameInternal(wxChar *buf, int sz)
751 {
752 wxCHECK_MSG( buf, false, wxT("NULL pointer in wxGetHostNameInternal") );
753
754 *buf = wxT('\0');
755
756 // we're using uname() which is POSIX instead of less standard sysinfo()
757 #if defined(HAVE_UNAME)
758 struct utsname uts;
759 bool ok = uname(&uts) != -1;
760 if ( ok )
761 {
762 wxStrlcpy(buf, wxSafeConvertMB2WX(uts.nodename), sz);
763 }
764 #elif defined(HAVE_GETHOSTNAME)
765 char cbuf[sz];
766 bool ok = gethostname(cbuf, sz) != -1;
767 if ( ok )
768 {
769 wxStrlcpy(buf, wxSafeConvertMB2WX(cbuf), sz);
770 }
771 #else // no uname, no gethostname
772 wxFAIL_MSG(wxT("don't know host name for this machine"));
773
774 bool ok = false;
775 #endif // uname/gethostname
776
777 if ( !ok )
778 {
779 wxLogSysError(_("Cannot get the hostname"));
780 }
781
782 return ok;
783 }
784
785 bool wxGetHostName(wxChar *buf, int sz)
786 {
787 bool ok = wxGetHostNameInternal(buf, sz);
788
789 if ( ok )
790 {
791 // BSD systems return the FQDN, we only want the hostname, so extract
792 // it (we consider that dots are domain separators)
793 wxChar *dot = wxStrchr(buf, wxT('.'));
794 if ( dot )
795 {
796 // nuke it
797 *dot = wxT('\0');
798 }
799 }
800
801 return ok;
802 }
803
804 bool wxGetFullHostName(wxChar *buf, int sz)
805 {
806 bool ok = wxGetHostNameInternal(buf, sz);
807
808 if ( ok )
809 {
810 if ( !wxStrchr(buf, wxT('.')) )
811 {
812 struct hostent *host = gethostbyname(wxSafeConvertWX2MB(buf));
813 if ( !host )
814 {
815 wxLogSysError(_("Cannot get the official hostname"));
816
817 ok = false;
818 }
819 else
820 {
821 // the canonical name
822 wxStrlcpy(buf, wxSafeConvertMB2WX(host->h_name), sz);
823 }
824 }
825 //else: it's already a FQDN (BSD behaves this way)
826 }
827
828 return ok;
829 }
830
831 bool wxGetUserId(wxChar *buf, int sz)
832 {
833 struct passwd *who;
834
835 *buf = wxT('\0');
836 if ((who = getpwuid(getuid ())) != NULL)
837 {
838 wxStrlcpy (buf, wxSafeConvertMB2WX(who->pw_name), sz);
839 return true;
840 }
841
842 return false;
843 }
844
845 bool wxGetUserName(wxChar *buf, int sz)
846 {
847 #ifdef HAVE_PW_GECOS
848 struct passwd *who;
849
850 *buf = wxT('\0');
851 if ((who = getpwuid (getuid ())) != NULL)
852 {
853 char *comma = strchr(who->pw_gecos, ',');
854 if (comma)
855 *comma = '\0'; // cut off non-name comment fields
856 wxStrlcpy(buf, wxSafeConvertMB2WX(who->pw_gecos), sz);
857 return true;
858 }
859
860 return false;
861 #else // !HAVE_PW_GECOS
862 return wxGetUserId(buf, sz);
863 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
864 }
865
866 bool wxIsPlatform64Bit()
867 {
868 const wxString machine = wxGetCommandOutput(wxT("uname -m"));
869
870 // the test for "64" is obviously not 100% reliable but seems to work fine
871 // in practice
872 return machine.Contains(wxT("64")) ||
873 machine.Contains(wxT("alpha"));
874 }
875
876 #ifdef __LINUX__
877 wxLinuxDistributionInfo wxGetLinuxDistributionInfo()
878 {
879 const wxString id = wxGetCommandOutput(wxT("lsb_release --id"));
880 const wxString desc = wxGetCommandOutput(wxT("lsb_release --description"));
881 const wxString rel = wxGetCommandOutput(wxT("lsb_release --release"));
882 const wxString codename = wxGetCommandOutput(wxT("lsb_release --codename"));
883
884 wxLinuxDistributionInfo ret;
885
886 id.StartsWith("Distributor ID:\t", &ret.Id);
887 desc.StartsWith("Description:\t", &ret.Description);
888 rel.StartsWith("Release:\t", &ret.Release);
889 codename.StartsWith("Codename:\t", &ret.CodeName);
890
891 return ret;
892 }
893 #endif
894
895 // these functions are in src/osx/utilsexc_base.cpp for wxMac
896 #ifndef __WXMAC__
897
898 wxOperatingSystemId wxGetOsVersion(int *verMaj, int *verMin)
899 {
900 // get OS version
901 int major, minor;
902 wxString release = wxGetCommandOutput(wxT("uname -r"));
903 if ( release.empty() ||
904 wxSscanf(release.c_str(), wxT("%d.%d"), &major, &minor) != 2 )
905 {
906 // failed to get version string or unrecognized format
907 major =
908 minor = -1;
909 }
910
911 if ( verMaj )
912 *verMaj = major;
913 if ( verMin )
914 *verMin = minor;
915
916 // try to understand which OS are we running
917 wxString kernel = wxGetCommandOutput(wxT("uname -s"));
918 if ( kernel.empty() )
919 kernel = wxGetCommandOutput(wxT("uname -o"));
920
921 if ( kernel.empty() )
922 return wxOS_UNKNOWN;
923
924 return wxPlatformInfo::GetOperatingSystemId(kernel);
925 }
926
927 wxString wxGetOsDescription()
928 {
929 return wxGetCommandOutput(wxT("uname -s -r -m"));
930 }
931
932 #endif // !__WXMAC__
933
934 unsigned long wxGetProcessId()
935 {
936 return (unsigned long)getpid();
937 }
938
939 wxMemorySize wxGetFreeMemory()
940 {
941 #if defined(__LINUX__)
942 // get it from /proc/meminfo
943 FILE *fp = fopen("/proc/meminfo", "r");
944 if ( fp )
945 {
946 long memFree = -1;
947
948 char buf[1024];
949 if ( fgets(buf, WXSIZEOF(buf), fp) && fgets(buf, WXSIZEOF(buf), fp) )
950 {
951 // /proc/meminfo changed its format in kernel 2.6
952 if ( wxPlatformInfo().CheckOSVersion(2, 6) )
953 {
954 unsigned long cached, buffers;
955 sscanf(buf, "MemFree: %ld", &memFree);
956
957 fgets(buf, WXSIZEOF(buf), fp);
958 sscanf(buf, "Buffers: %lu", &buffers);
959
960 fgets(buf, WXSIZEOF(buf), fp);
961 sscanf(buf, "Cached: %lu", &cached);
962
963 // add to "MemFree" also the "Buffers" and "Cached" values as
964 // free(1) does as otherwise the value never makes sense: for
965 // kernel 2.6 it's always almost 0
966 memFree += buffers + cached;
967
968 // values here are always expressed in kB and we want bytes
969 memFree *= 1024;
970 }
971 else // Linux 2.4 (or < 2.6, anyhow)
972 {
973 long memTotal, memUsed;
974 sscanf(buf, "Mem: %ld %ld %ld", &memTotal, &memUsed, &memFree);
975 }
976 }
977
978 fclose(fp);
979
980 return (wxMemorySize)memFree;
981 }
982 #elif defined(__SGI__)
983 struct rminfo realmem;
984 if ( sysmp(MP_SAGET, MPSA_RMINFO, &realmem, sizeof realmem) == 0 )
985 return ((wxMemorySize)realmem.physmem * sysconf(_SC_PAGESIZE));
986 #elif defined(_SC_AVPHYS_PAGES)
987 return ((wxMemorySize)sysconf(_SC_AVPHYS_PAGES))*sysconf(_SC_PAGESIZE);
988 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
989 #endif
990
991 // can't find it out
992 return -1;
993 }
994
995 bool wxGetDiskSpace(const wxString& path, wxDiskspaceSize_t *pTotal, wxDiskspaceSize_t *pFree)
996 {
997 #if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
998 // the case to "char *" is needed for AIX 4.3
999 wxStatfs_t fs;
1000 if ( wxStatfs((char *)(const char*)path.fn_str(), &fs) != 0 )
1001 {
1002 wxLogSysError( wxT("Failed to get file system statistics") );
1003
1004 return false;
1005 }
1006
1007 // under Solaris we also have to use f_frsize field instead of f_bsize
1008 // which is in general a multiple of f_frsize
1009 #ifdef HAVE_STATVFS
1010 wxDiskspaceSize_t blockSize = fs.f_frsize;
1011 #else // HAVE_STATFS
1012 wxDiskspaceSize_t blockSize = fs.f_bsize;
1013 #endif // HAVE_STATVFS/HAVE_STATFS
1014
1015 if ( pTotal )
1016 {
1017 *pTotal = wxDiskspaceSize_t(fs.f_blocks) * blockSize;
1018 }
1019
1020 if ( pFree )
1021 {
1022 *pFree = wxDiskspaceSize_t(fs.f_bavail) * blockSize;
1023 }
1024
1025 return true;
1026 #else // !HAVE_STATFS && !HAVE_STATVFS
1027 return false;
1028 #endif // HAVE_STATFS
1029 }
1030
1031 // ----------------------------------------------------------------------------
1032 // env vars
1033 // ----------------------------------------------------------------------------
1034
1035 #if USE_PUTENV
1036
1037 WX_DECLARE_STRING_HASH_MAP(char *, wxEnvVars);
1038
1039 static wxEnvVars gs_envVars;
1040
1041 class wxSetEnvModule : public wxModule
1042 {
1043 public:
1044 virtual bool OnInit() { return true; }
1045 virtual void OnExit()
1046 {
1047 for ( wxEnvVars::const_iterator i = gs_envVars.begin();
1048 i != gs_envVars.end();
1049 ++i )
1050 {
1051 free(i->second);
1052 }
1053
1054 gs_envVars.clear();
1055 }
1056
1057 DECLARE_DYNAMIC_CLASS(wxSetEnvModule)
1058 };
1059
1060 IMPLEMENT_DYNAMIC_CLASS(wxSetEnvModule, wxModule)
1061
1062 #endif // USE_PUTENV
1063
1064 bool wxGetEnv(const wxString& var, wxString *value)
1065 {
1066 // wxGetenv is defined as getenv()
1067 char *p = wxGetenv(var);
1068 if ( !p )
1069 return false;
1070
1071 if ( value )
1072 {
1073 *value = p;
1074 }
1075
1076 return true;
1077 }
1078
1079 static bool wxDoSetEnv(const wxString& variable, const char *value)
1080 {
1081 #if defined(HAVE_SETENV)
1082 if ( !value )
1083 {
1084 #ifdef HAVE_UNSETENV
1085 // don't test unsetenv() return value: it's void on some systems (at
1086 // least Darwin)
1087 unsetenv(variable.mb_str());
1088 return true;
1089 #else
1090 value = ""; // we can't pass NULL to setenv()
1091 #endif
1092 }
1093
1094 return setenv(variable.mb_str(), value, 1 /* overwrite */) == 0;
1095 #elif defined(HAVE_PUTENV)
1096 wxString s = variable;
1097 if ( value )
1098 s << wxT('=') << value;
1099
1100 // transform to ANSI
1101 const wxWX2MBbuf p = s.mb_str();
1102
1103 char *buf = (char *)malloc(strlen(p) + 1);
1104 strcpy(buf, p);
1105
1106 // store the string to free() it later
1107 wxEnvVars::iterator i = gs_envVars.find(variable);
1108 if ( i != gs_envVars.end() )
1109 {
1110 free(i->second);
1111 i->second = buf;
1112 }
1113 else // this variable hadn't been set before
1114 {
1115 gs_envVars[variable] = buf;
1116 }
1117
1118 return putenv(buf) == 0;
1119 #else // no way to set an env var
1120 return false;
1121 #endif
1122 }
1123
1124 bool wxSetEnv(const wxString& variable, const wxString& value)
1125 {
1126 return wxDoSetEnv(variable, value.mb_str());
1127 }
1128
1129 bool wxUnsetEnv(const wxString& variable)
1130 {
1131 return wxDoSetEnv(variable, NULL);
1132 }
1133
1134 // ----------------------------------------------------------------------------
1135 // signal handling
1136 // ----------------------------------------------------------------------------
1137
1138 #if wxUSE_ON_FATAL_EXCEPTION
1139
1140 #include <signal.h>
1141
1142 extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER)
1143 {
1144 if ( wxTheApp )
1145 {
1146 // give the user a chance to do something special about this
1147 wxTheApp->OnFatalException();
1148 }
1149
1150 abort();
1151 }
1152
1153 bool wxHandleFatalExceptions(bool doit)
1154 {
1155 // old sig handlers
1156 static bool s_savedHandlers = false;
1157 static struct sigaction s_handlerFPE,
1158 s_handlerILL,
1159 s_handlerBUS,
1160 s_handlerSEGV;
1161
1162 bool ok = true;
1163 if ( doit && !s_savedHandlers )
1164 {
1165 // install the signal handler
1166 struct sigaction act;
1167
1168 // some systems extend it with non std fields, so zero everything
1169 memset(&act, 0, sizeof(act));
1170
1171 act.sa_handler = wxFatalSignalHandler;
1172 sigemptyset(&act.sa_mask);
1173 act.sa_flags = 0;
1174
1175 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
1176 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
1177 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
1178 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
1179 if ( !ok )
1180 {
1181 wxLogDebug(wxT("Failed to install our signal handler."));
1182 }
1183
1184 s_savedHandlers = true;
1185 }
1186 else if ( s_savedHandlers )
1187 {
1188 // uninstall the signal handler
1189 ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
1190 ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
1191 ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
1192 ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
1193 if ( !ok )
1194 {
1195 wxLogDebug(wxT("Failed to uninstall our signal handler."));
1196 }
1197
1198 s_savedHandlers = false;
1199 }
1200 //else: nothing to do
1201
1202 return ok;
1203 }
1204
1205 #endif // wxUSE_ON_FATAL_EXCEPTION
1206
1207 // ----------------------------------------------------------------------------
1208 // wxExecute support
1209 // ----------------------------------------------------------------------------
1210
1211 int wxAppTraits::AddProcessCallback(wxEndProcessData *data, int fd)
1212 {
1213 // define a custom handler processing only the closure of the descriptor
1214 struct wxEndProcessFDIOHandler : public wxFDIOHandler
1215 {
1216 wxEndProcessFDIOHandler(wxEndProcessData *data, int fd)
1217 : m_data(data), m_fd(fd)
1218 {
1219 }
1220
1221 virtual void OnReadWaiting()
1222 {
1223 wxFDIODispatcher::Get()->UnregisterFD(m_fd);
1224 close(m_fd);
1225
1226 wxHandleProcessTermination(m_data);
1227
1228 delete this;
1229 }
1230
1231 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1232 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1233
1234 wxEndProcessData * const m_data;
1235 const int m_fd;
1236 };
1237
1238 wxFDIODispatcher::Get()->RegisterFD
1239 (
1240 fd,
1241 new wxEndProcessFDIOHandler(data, fd),
1242 wxFDIO_INPUT
1243 );
1244 return fd; // unused, but return something unique for the tag
1245 }
1246
1247 bool wxAppTraits::CheckForRedirectedIO(wxExecuteData& execData)
1248 {
1249 #if HAS_PIPE_INPUT_STREAM
1250 bool hasIO = false;
1251
1252 if ( execData.bufOut && execData.bufOut->Update() )
1253 hasIO = true;
1254
1255 if ( execData.bufErr && execData.bufErr->Update() )
1256 hasIO = true;
1257
1258 return hasIO;
1259 #else // !HAS_PIPE_INPUT_STREAM
1260 return false;
1261 #endif // HAS_PIPE_INPUT_STREAM/!HAS_PIPE_INPUT_STREAM
1262 }
1263
1264 // helper classes/functions used by WaitForChild()
1265 namespace
1266 {
1267
1268 // convenient base class for IO handlers which are registered for read
1269 // notifications only and which also stores the FD we're reading from
1270 //
1271 // the derived classes still have to implement OnReadWaiting()
1272 class wxReadFDIOHandler : public wxFDIOHandler
1273 {
1274 public:
1275 wxReadFDIOHandler(wxFDIODispatcher& disp, int fd) : m_fd(fd)
1276 {
1277 if ( fd )
1278 disp.RegisterFD(fd, this, wxFDIO_INPUT);
1279 }
1280
1281 virtual void OnWriteWaiting() { wxFAIL_MSG("unreachable"); }
1282 virtual void OnExceptionWaiting() { wxFAIL_MSG("unreachable"); }
1283
1284 protected:
1285 const int m_fd;
1286
1287 wxDECLARE_NO_COPY_CLASS(wxReadFDIOHandler);
1288 };
1289
1290 // class for monitoring our end of the process detection pipe, simply sets a
1291 // flag when input on the pipe (which must be due to EOF) is detected
1292 class wxEndHandler : public wxReadFDIOHandler
1293 {
1294 public:
1295 wxEndHandler(wxFDIODispatcher& disp, int fd)
1296 : wxReadFDIOHandler(disp, fd)
1297 {
1298 m_terminated = false;
1299 }
1300
1301 bool Terminated() const { return m_terminated; }
1302
1303 virtual void OnReadWaiting() { m_terminated = true; }
1304
1305 private:
1306 bool m_terminated;
1307
1308 wxDECLARE_NO_COPY_CLASS(wxEndHandler);
1309 };
1310
1311 #if HAS_PIPE_INPUT_STREAM
1312
1313 // class for monitoring our ends of child stdout/err, should be constructed
1314 // with the FD and stream from wxExecuteData and will do nothing if they're
1315 // invalid
1316 //
1317 // unlike wxEndHandler this class registers itself with the provided dispatcher
1318 class wxRedirectedIOHandler : public wxReadFDIOHandler
1319 {
1320 public:
1321 wxRedirectedIOHandler(wxFDIODispatcher& disp,
1322 int fd,
1323 wxStreamTempInputBuffer *buf)
1324 : wxReadFDIOHandler(disp, fd),
1325 m_buf(buf)
1326 {
1327 }
1328
1329 virtual void OnReadWaiting()
1330 {
1331 m_buf->Update();
1332 }
1333
1334 private:
1335 wxStreamTempInputBuffer * const m_buf;
1336
1337 wxDECLARE_NO_COPY_CLASS(wxRedirectedIOHandler);
1338 };
1339
1340 #endif // HAS_PIPE_INPUT_STREAM
1341
1342 // helper function which calls waitpid() and analyzes the result
1343 int DoWaitForChild(int pid, int flags = 0)
1344 {
1345 wxASSERT_MSG( pid > 0, "invalid PID" );
1346
1347 int status, rc;
1348
1349 // loop while we're getting EINTR
1350 for ( ;; )
1351 {
1352 rc = waitpid(pid, &status, flags);
1353
1354 if ( rc != -1 || errno != EINTR )
1355 break;
1356 }
1357
1358 if ( rc == 0 )
1359 {
1360 // This can only happen if the child application closes our dummy pipe
1361 // that is used to monitor its lifetime; in that case, our best bet is
1362 // to pretend the process did terminate, because otherwise wxExecute()
1363 // would hang indefinitely (OnReadWaiting() won't be called again, the
1364 // descriptor is closed now).
1365 wxLogDebug("Child process (PID %d) still alive but pipe closed so "
1366 "generating a close notification", pid);
1367 }
1368 else if ( rc == -1 )
1369 {
1370 wxLogLastError(wxString::Format("waitpid(%d)", pid));
1371 }
1372 else // child did terminate
1373 {
1374 wxASSERT_MSG( rc == pid, "unexpected waitpid() return value" );
1375
1376 // notice that the caller expects the exit code to be signed, e.g. -1
1377 // instead of 255 so don't assign WEXITSTATUS() to an int
1378 signed char exitcode;
1379 if ( WIFEXITED(status) )
1380 exitcode = WEXITSTATUS(status);
1381 else if ( WIFSIGNALED(status) )
1382 exitcode = -WTERMSIG(status);
1383 else
1384 {
1385 wxLogError("Child process (PID %d) exited for unknown reason, "
1386 "status = %d", pid, status);
1387 exitcode = -1;
1388 }
1389
1390 return exitcode;
1391 }
1392
1393 return -1;
1394 }
1395
1396 } // anonymous namespace
1397
1398 int wxAppTraits::WaitForChild(wxExecuteData& execData)
1399 {
1400 if ( !(execData.flags & wxEXEC_SYNC) )
1401 {
1402 // asynchronous execution: just launch the process and return,
1403 // endProcData will be destroyed when it terminates (currently we leak
1404 // it if the process doesn't terminate before we do and this should be
1405 // fixed but it's not a real leak so it's not really very high
1406 // priority)
1407 wxEndProcessData *endProcData = new wxEndProcessData;
1408 endProcData->process = execData.process;
1409 endProcData->pid = execData.pid;
1410 endProcData->tag = AddProcessCallback
1411 (
1412 endProcData,
1413 execData.GetEndProcReadFD()
1414 );
1415 endProcData->async = true;
1416
1417 return execData.pid;
1418 }
1419 //else: synchronous execution case
1420
1421 #if HAS_PIPE_INPUT_STREAM && wxUSE_SOCKETS
1422 wxProcess * const process = execData.process;
1423 if ( process && process->IsRedirected() )
1424 {
1425 // we can't simply block waiting for the child to terminate as we would
1426 // dead lock if it writes more than the pipe buffer size (typically
1427 // 4KB) bytes of output -- it would then block waiting for us to read
1428 // the data while we'd block waiting for it to terminate
1429 //
1430 // so multiplex here waiting for any input from the child or closure of
1431 // the pipe used to indicate its termination
1432 wxSelectDispatcher disp;
1433
1434 wxEndHandler endHandler(disp, execData.GetEndProcReadFD());
1435
1436 wxRedirectedIOHandler outHandler(disp, execData.fdOut, execData.bufOut),
1437 errHandler(disp, execData.fdErr, execData.bufErr);
1438
1439 while ( !endHandler.Terminated() )
1440 {
1441 disp.Dispatch();
1442 }
1443 }
1444 //else: no IO redirection, just block waiting for the child to exit
1445 #endif // HAS_PIPE_INPUT_STREAM
1446
1447 return DoWaitForChild(execData.pid);
1448 }
1449
1450 void wxHandleProcessTermination(wxEndProcessData *data)
1451 {
1452 data->exitcode = DoWaitForChild(data->pid, WNOHANG);
1453
1454 // notify user about termination if required
1455 if ( data->process )
1456 {
1457 data->process->OnTerminate(data->pid, data->exitcode);
1458 }
1459
1460 if ( data->async )
1461 {
1462 // in case of asynchronous execution we don't need this data any more
1463 // after the child terminates
1464 delete data;
1465 }
1466 else // sync execution
1467 {
1468 // let wxExecute() know that the process has terminated
1469 data->pid = 0;
1470 }
1471 }
1472