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