]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/unix/utilsunx.cpp
fix for potention crash when conversion fails
[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#ifndef WX_PRECOMP
24 #include "wx/string.h"
25 #include "wx/intl.h"
26 #include "wx/log.h"
27 #include "wx/app.h"
28#endif
29
30#include "wx/apptrait.h"
31
32#include "wx/process.h"
33#include "wx/thread.h"
34
35#include "wx/wfstream.h"
36
37#include "wx/unix/execute.h"
38#include "wx/unix/private.h"
39
40#include <pwd.h>
41
42#if wxUSE_STREAMS
43
44// define this to let wxexec.cpp know that we know what we're doing
45#define _WX_USED_BY_WXEXECUTE_
46#include "../common/execcmn.cpp"
47
48#endif // wxUSE_STREAMS
49
50#if wxUSE_BASE
51
52#if defined(__MWERKS__) && defined(__MACH__)
53 #ifndef WXWIN_OS_DESCRIPTION
54 #define WXWIN_OS_DESCRIPTION "MacOS X"
55 #endif
56 #ifndef HAVE_NANOSLEEP
57 #define HAVE_NANOSLEEP
58 #endif
59 #ifndef HAVE_UNAME
60 #define HAVE_UNAME
61 #endif
62
63 // our configure test believes we can use sigaction() if the function is
64 // available but Metrowekrs with MSL run-time does have the function but
65 // doesn't have sigaction struct so finally we can't use it...
66 #ifdef __MSL__
67 #undef wxUSE_ON_FATAL_EXCEPTION
68 #define wxUSE_ON_FATAL_EXCEPTION 0
69 #endif
70#endif
71
72// not only the statfs syscall is called differently depending on platform, but
73// one of its incarnations, statvfs(), takes different arguments under
74// different platforms and even different versions of the same system (Solaris
75// 7 and 8): if you want to test for this, don't forget that the problems only
76// appear if the large files support is enabled
77#ifdef HAVE_STATFS
78 #ifdef __BSD__
79 #include <sys/param.h>
80 #include <sys/mount.h>
81 #else // !__BSD__
82 #include <sys/vfs.h>
83 #endif // __BSD__/!__BSD__
84
85 #define wxStatfs statfs
86
87 #ifndef HAVE_STATFS_DECL
88 // some systems lack statfs() prototype in the system headers (AIX 4)
89 extern "C" int statfs(const char *path, struct statfs *buf);
90 #endif
91#endif // HAVE_STATFS
92
93#ifdef HAVE_STATVFS
94 #include <sys/statvfs.h>
95
96 #define wxStatfs statvfs
97#endif // HAVE_STATVFS
98
99#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
100 // WX_STATFS_T is detected by configure
101 #define wxStatfs_t WX_STATFS_T
102#endif
103
104// SGI signal.h defines signal handler arguments differently depending on
105// whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
106#if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
107 #define _LANGUAGE_C_PLUS_PLUS 1
108#endif // SGI hack
109
110#include <stdarg.h>
111#include <dirent.h>
112#include <string.h>
113#include <sys/stat.h>
114#include <sys/types.h>
115#include <sys/wait.h>
116#include <unistd.h>
117#include <errno.h>
118#include <netdb.h>
119#include <signal.h>
120#include <fcntl.h> // for O_WRONLY and friends
121#include <time.h> // nanosleep() and/or usleep()
122#include <ctype.h> // isspace()
123#include <sys/time.h> // needed for FD_SETSIZE
124
125#ifdef HAVE_UNAME
126 #include <sys/utsname.h> // for uname()
127#endif // HAVE_UNAME
128
129// Used by wxGetFreeMemory().
130#ifdef __SGI__
131 #include <sys/sysmp.h>
132 #include <sys/sysinfo.h> // for SAGET and MINFO structures
133#endif
134
135// ----------------------------------------------------------------------------
136// conditional compilation
137// ----------------------------------------------------------------------------
138
139// many versions of Unices have this function, but it is not defined in system
140// headers - please add your system here if it is the case for your OS.
141// SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
142#if !defined(HAVE_USLEEP) && \
143 ((defined(__SUN__) && !defined(__SunOs_5_6) && \
144 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
145 defined(__osf__) || defined(__EMX__))
146 extern "C"
147 {
148 #ifdef __SUN__
149 int usleep(unsigned int usec);
150 #else // !Sun
151 #ifdef __EMX__
152 /* I copied this from the XFree86 diffs. AV. */
153 #define INCL_DOSPROCESS
154 #include <os2.h>
155 inline void usleep(unsigned long delay)
156 {
157 DosSleep(delay ? (delay/1000l) : 1l);
158 }
159 #else // !Sun && !EMX
160 void usleep(unsigned long usec);
161 #endif
162 #endif // Sun/EMX/Something else
163 };
164
165 #define HAVE_USLEEP 1
166#endif // Unices without usleep()
167
168// ============================================================================
169// implementation
170// ============================================================================
171
172// ----------------------------------------------------------------------------
173// sleeping
174// ----------------------------------------------------------------------------
175
176void wxSleep(int nSecs)
177{
178 sleep(nSecs);
179}
180
181void wxMicroSleep(unsigned long microseconds)
182{
183#if defined(HAVE_NANOSLEEP)
184 timespec tmReq;
185 tmReq.tv_sec = (time_t)(microseconds / 1000000);
186 tmReq.tv_nsec = (microseconds % 1000000) * 1000;
187
188 // we're not interested in remaining time nor in return value
189 (void)nanosleep(&tmReq, (timespec *)NULL);
190#elif defined(HAVE_USLEEP)
191 // uncomment this if you feel brave or if you are sure that your version
192 // of Solaris has a safe usleep() function but please notice that usleep()
193 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
194 // documented as MT-Safe
195 #if defined(__SUN__) && wxUSE_THREADS
196 #error "usleep() cannot be used in MT programs under Solaris."
197 #endif // Sun
198
199 usleep(microseconds);
200#elif defined(HAVE_SLEEP)
201 // under BeOS sleep() takes seconds (what about other platforms, if any?)
202 sleep(microseconds * 1000000);
203#else // !sleep function
204 #error "usleep() or nanosleep() function required for wxMicroSleep"
205#endif // sleep function
206}
207
208void wxMilliSleep(unsigned long milliseconds)
209{
210 wxMicroSleep(milliseconds*1000);
211}
212
213// ----------------------------------------------------------------------------
214// process management
215// ----------------------------------------------------------------------------
216
217int wxKill(long pid, wxSignal sig, wxKillError *rc, int flags)
218{
219 int err = kill((pid_t) (flags & wxKILL_CHILDREN) ? -pid : pid, (int)sig);
220 if ( rc )
221 {
222 switch ( err ? errno : 0 )
223 {
224 case 0:
225 *rc = wxKILL_OK;
226 break;
227
228 case EINVAL:
229 *rc = wxKILL_BAD_SIGNAL;
230 break;
231
232 case EPERM:
233 *rc = wxKILL_ACCESS_DENIED;
234 break;
235
236 case ESRCH:
237 *rc = wxKILL_NO_PROCESS;
238 break;
239
240 default:
241 // this goes against Unix98 docs so log it
242 wxLogDebug(_T("unexpected kill(2) return value %d"), err);
243
244 // something else...
245 *rc = wxKILL_ERROR;
246 }
247 }
248
249 return err;
250}
251
252#define WXEXECUTE_NARGS 127
253
254#if defined(__DARWIN__)
255long wxMacExecute(wxChar **argv,
256 int flags,
257 wxProcess *process);
258#endif
259
260long wxExecute( const wxString& command, int flags, wxProcess *process )
261{
262 wxCHECK_MSG( !command.empty(), 0, wxT("can't exec empty command") );
263 wxLogDebug(wxString(wxT("Launching: ")) + command);
264
265#if wxUSE_THREADS
266 // fork() doesn't mix well with POSIX threads: on many systems the program
267 // deadlocks or crashes for some reason. Probably our code is buggy and
268 // doesn't do something which must be done to allow this to work, but I
269 // don't know what yet, so for now just warn the user (this is the least we
270 // can do) about it
271 wxASSERT_MSG( wxThread::IsMain(),
272 _T("wxExecute() can be called only from the main thread") );
273#endif // wxUSE_THREADS
274
275 int argc = 0;
276 wxChar *argv[WXEXECUTE_NARGS];
277 wxString argument;
278 const wxChar *cptr = command.c_str();
279 wxChar quotechar = wxT('\0'); // is arg quoted?
280 bool escaped = false;
281
282 // split the command line in arguments
283 do
284 {
285 argument = wxEmptyString;
286 quotechar = wxT('\0');
287
288 // eat leading whitespace:
289 while ( wxIsspace(*cptr) )
290 cptr++;
291
292 if ( *cptr == wxT('\'') || *cptr == wxT('"') )
293 quotechar = *cptr++;
294
295 do
296 {
297 if ( *cptr == wxT('\\') && ! escaped )
298 {
299 escaped = true;
300 cptr++;
301 continue;
302 }
303
304 // all other characters:
305 argument += *cptr++;
306 escaped = false;
307
308 // have we reached the end of the argument?
309 if ( (*cptr == quotechar && ! escaped)
310 || (quotechar == wxT('\0') && wxIsspace(*cptr))
311 || *cptr == wxT('\0') )
312 {
313 wxASSERT_MSG( argc < WXEXECUTE_NARGS,
314 wxT("too many arguments in wxExecute") );
315
316 argv[argc] = new wxChar[argument.length() + 1];
317 wxStrcpy(argv[argc], argument.c_str());
318 argc++;
319
320 // if not at end of buffer, swallow last character:
321 if(*cptr)
322 cptr++;
323
324 break; // done with this one, start over
325 }
326 } while(*cptr);
327 } while(*cptr);
328 argv[argc] = NULL;
329
330 long lRc;
331#if defined(__DARWIN__)
332 // wxMacExecute only executes app bundles.
333 // It returns an error code if the target is not an app bundle, thus falling
334 // through to the regular wxExecute for non app bundles.
335 lRc = wxMacExecute(argv, flags, process);
336 if( lRc != ((flags & wxEXEC_SYNC) ? -1 : 0))
337 return lRc;
338#endif
339
340 // do execute the command
341 lRc = wxExecute(argv, flags, process);
342
343 // clean up
344 argc = 0;
345 while( argv[argc] )
346 delete [] argv[argc++];
347
348 return lRc;
349}
350
351// ----------------------------------------------------------------------------
352// wxShell
353// ----------------------------------------------------------------------------
354
355static wxString wxMakeShellCommand(const wxString& command)
356{
357 wxString cmd;
358 if ( !command )
359 {
360 // just an interactive shell
361 cmd = _T("xterm");
362 }
363 else
364 {
365 // execute command in a shell
366 cmd << _T("/bin/sh -c '") << command << _T('\'');
367 }
368
369 return cmd;
370}
371
372bool wxShell(const wxString& command)
373{
374 return wxExecute(wxMakeShellCommand(command), wxEXEC_SYNC) == 0;
375}
376
377bool wxShell(const wxString& command, wxArrayString& output)
378{
379 wxCHECK_MSG( !command.empty(), false, _T("can't exec shell non interactively") );
380
381 return wxExecute(wxMakeShellCommand(command), output);
382}
383
384// Shutdown or reboot the PC
385bool wxShutdown(wxShutdownFlags wFlags)
386{
387 wxChar level;
388 switch ( wFlags )
389 {
390 case wxSHUTDOWN_POWEROFF:
391 level = _T('0');
392 break;
393
394 case wxSHUTDOWN_REBOOT:
395 level = _T('6');
396 break;
397
398 default:
399 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
400 return false;
401 }
402
403 return system(wxString::Format(_T("init %c"), level).mb_str()) == 0;
404}
405
406// ----------------------------------------------------------------------------
407// wxStream classes to support IO redirection in wxExecute
408// ----------------------------------------------------------------------------
409
410#if wxUSE_STREAMS
411
412bool wxPipeInputStream::CanRead() const
413{
414 if ( m_lasterror == wxSTREAM_EOF )
415 return false;
416
417 // check if there is any input available
418 struct timeval tv;
419 tv.tv_sec = 0;
420 tv.tv_usec = 0;
421
422 const int fd = m_file->fd();
423
424 fd_set readfds;
425
426 wxFD_ZERO(&readfds);
427 wxFD_SET(fd, &readfds);
428
429 switch ( select(fd + 1, &readfds, NULL, NULL, &tv) )
430 {
431 case -1:
432 wxLogSysError(_("Impossible to get child process input"));
433 // fall through
434
435 case 0:
436 return false;
437
438 default:
439 wxFAIL_MSG(_T("unexpected select() return value"));
440 // still fall through
441
442 case 1:
443 // input available -- or maybe not, as select() returns 1 when a
444 // read() will complete without delay, but it could still not read
445 // anything
446 return !Eof();
447 }
448}
449
450#endif // wxUSE_STREAMS
451
452// ----------------------------------------------------------------------------
453// wxExecute: the real worker function
454// ----------------------------------------------------------------------------
455
456long wxExecute(wxChar **argv, int flags, wxProcess *process)
457{
458 // for the sync execution, we return -1 to indicate failure, but for async
459 // case we return 0 which is never a valid PID
460 //
461 // we define this as a macro, not a variable, to avoid compiler warnings
462 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
463 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
464
465 wxCHECK_MSG( *argv, ERROR_RETURN_CODE, wxT("can't exec empty command") );
466
467#if wxUSE_UNICODE
468 int mb_argc = 0;
469 char *mb_argv[WXEXECUTE_NARGS];
470
471 while (argv[mb_argc])
472 {
473 wxWX2MBbuf mb_arg = wxConvertWX2MB(argv[mb_argc]);
474 mb_argv[mb_argc] = strdup(mb_arg);
475 mb_argc++;
476 }
477 mb_argv[mb_argc] = (char *) NULL;
478
479 // this macro will free memory we used above
480 #define ARGS_CLEANUP \
481 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
482 free(mb_argv[mb_argc])
483#else // ANSI
484 // no need for cleanup
485 #define ARGS_CLEANUP
486
487 wxChar **mb_argv = argv;
488#endif // Unicode/ANSI
489
490 // we want this function to work even if there is no wxApp so ensure that
491 // we have a valid traits pointer
492 wxConsoleAppTraits traitsConsole;
493 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
494 if ( !traits )
495 traits = &traitsConsole;
496
497 // this struct contains all information which we pass to and from
498 // wxAppTraits methods
499 wxExecuteData execData;
500 execData.flags = flags;
501 execData.process = process;
502
503 // create pipes
504 if ( !traits->CreateEndProcessPipe(execData) )
505 {
506 wxLogError( _("Failed to execute '%s'\n"), *argv );
507
508 ARGS_CLEANUP;
509
510 return ERROR_RETURN_CODE;
511 }
512
513 // pipes for inter process communication
514 wxPipe pipeIn, // stdin
515 pipeOut, // stdout
516 pipeErr; // stderr
517
518 if ( process && process->IsRedirected() )
519 {
520 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
521 {
522 wxLogError( _("Failed to execute '%s'\n"), *argv );
523
524 ARGS_CLEANUP;
525
526 return ERROR_RETURN_CODE;
527 }
528 }
529
530 // fork the process
531 //
532 // NB: do *not* use vfork() here, it completely breaks this code for some
533 // reason under Solaris (and maybe others, although not under Linux)
534 // But on OpenVMS we do not have fork so we have to use vfork and
535 // cross our fingers that it works.
536#ifdef __VMS
537 pid_t pid = vfork();
538#else
539 pid_t pid = fork();
540#endif
541 if ( pid == -1 ) // error?
542 {
543 wxLogSysError( _("Fork failed") );
544
545 ARGS_CLEANUP;
546
547 return ERROR_RETURN_CODE;
548 }
549 else if ( pid == 0 ) // we're in child
550 {
551 // These lines close the open file descriptors to to avoid any
552 // input/output which might block the process or irritate the user. If
553 // one wants proper IO for the subprocess, the right thing to do is to
554 // start an xterm executing it.
555 if ( !(flags & wxEXEC_SYNC) )
556 {
557 // FD_SETSIZE is unsigned under BSD, signed under other platforms
558 // so we need a cast to avoid warnings on all platforms
559 for ( int fd = 0; fd < (int)FD_SETSIZE; fd++ )
560 {
561 if ( fd == pipeIn[wxPipe::Read]
562 || fd == pipeOut[wxPipe::Write]
563 || fd == pipeErr[wxPipe::Write]
564 || traits->IsWriteFDOfEndProcessPipe(execData, fd) )
565 {
566 // don't close this one, we still need it
567 continue;
568 }
569
570 // leave stderr opened too, it won't do any harm
571 if ( fd != STDERR_FILENO )
572 close(fd);
573 }
574 }
575
576#if !defined(__VMS) && !defined(__EMX__)
577 if ( flags & wxEXEC_MAKE_GROUP_LEADER )
578 {
579 // Set process group to child process' pid. Then killing -pid
580 // of the parent will kill the process and all of its children.
581 setsid();
582 }
583#endif // !__VMS
584
585 // reading side can be safely closed but we should keep the write one
586 // opened
587 traits->DetachWriteFDOfEndProcessPipe(execData);
588
589 // redirect stdin, stdout and stderr
590 if ( pipeIn.IsOk() )
591 {
592 if ( dup2(pipeIn[wxPipe::Read], STDIN_FILENO) == -1 ||
593 dup2(pipeOut[wxPipe::Write], STDOUT_FILENO) == -1 ||
594 dup2(pipeErr[wxPipe::Write], STDERR_FILENO) == -1 )
595 {
596 wxLogSysError(_("Failed to redirect child process input/output"));
597 }
598
599 pipeIn.Close();
600 pipeOut.Close();
601 pipeErr.Close();
602 }
603
604 execvp (*mb_argv, mb_argv);
605
606 fprintf(stderr, "execvp(");
607 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
608 for ( char **ppc_ = mb_argv; *ppc_; ppc_++ )
609 fprintf(stderr, "%s%s", ppc_ == mb_argv ? "" : ", ", *ppc_);
610 fprintf(stderr, ") failed with error %d!\n", errno);
611
612 // there is no return after successful exec()
613 _exit(-1);
614
615 // some compilers complain about missing return - of course, they
616 // should know that exit() doesn't return but what else can we do if
617 // they don't?
618 //
619 // and, sure enough, other compilers complain about unreachable code
620 // after exit() call, so we can just always have return here...
621#if defined(__VMS) || defined(__INTEL_COMPILER)
622 return 0;
623#endif
624 }
625 else // we're in parent
626 {
627 ARGS_CLEANUP;
628
629 // save it for WaitForChild() use
630 execData.pid = pid;
631
632 // prepare for IO redirection
633
634#if wxUSE_STREAMS
635 // the input buffer bufOut is connected to stdout, this is why it is
636 // called bufOut and not bufIn
637 wxStreamTempInputBuffer bufOut,
638 bufErr;
639#endif // wxUSE_STREAMS
640
641 if ( process && process->IsRedirected() )
642 {
643#if wxUSE_STREAMS
644 wxOutputStream *inStream =
645 new wxFileOutputStream(pipeIn.Detach(wxPipe::Write));
646
647 wxPipeInputStream *outStream =
648 new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
649
650 wxPipeInputStream *errStream =
651 new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
652
653 process->SetPipeStreams(outStream, inStream, errStream);
654
655 bufOut.Init(outStream);
656 bufErr.Init(errStream);
657
658 execData.bufOut = &bufOut;
659 execData.bufErr = &bufErr;
660#endif // wxUSE_STREAMS
661 }
662
663 if ( pipeIn.IsOk() )
664 {
665 pipeIn.Close();
666 pipeOut.Close();
667 pipeErr.Close();
668 }
669
670 return traits->WaitForChild(execData);
671 }
672
673#if !defined(__VMS) && !defined(__INTEL_COMPILER)
674 return ERROR_RETURN_CODE;
675#endif
676}
677
678#undef ERROR_RETURN_CODE
679#undef ARGS_CLEANUP
680
681// ----------------------------------------------------------------------------
682// file and directory functions
683// ----------------------------------------------------------------------------
684
685const wxChar* wxGetHomeDir( wxString *home )
686{
687 *home = wxGetUserHome( wxEmptyString );
688 wxString tmp;
689 if ( home->empty() )
690 *home = wxT("/");
691#ifdef __VMS
692 tmp = *home;
693 if ( tmp.Last() != wxT(']'))
694 if ( tmp.Last() != wxT('/')) *home << wxT('/');
695#endif
696 return home->c_str();
697}
698
699#if wxUSE_UNICODE
700const wxMB2WXbuf wxGetUserHome( const wxString &user )
701#else // just for binary compatibility -- there is no 'const' here
702char *wxGetUserHome( const wxString &user )
703#endif
704{
705 struct passwd *who = (struct passwd *) NULL;
706
707 if ( !user )
708 {
709 wxChar *ptr;
710
711 if ((ptr = wxGetenv(wxT("HOME"))) != NULL)
712 {
713#if wxUSE_UNICODE
714 wxWCharBuffer buffer( ptr );
715 return buffer;
716#else
717 return ptr;
718#endif
719 }
720 if ((ptr = wxGetenv(wxT("USER"))) != NULL || (ptr = wxGetenv(wxT("LOGNAME"))) != NULL)
721 {
722 who = getpwnam(wxConvertWX2MB(ptr));
723 }
724
725 // We now make sure the the user exists!
726 if (who == NULL)
727 {
728 who = getpwuid(getuid());
729 }
730 }
731 else
732 {
733 who = getpwnam (user.mb_str());
734 }
735
736 return wxConvertMB2WX(who ? who->pw_dir : 0);
737}
738
739// ----------------------------------------------------------------------------
740// network and user id routines
741// ----------------------------------------------------------------------------
742
743// retrieve either the hostname or FQDN depending on platform (caller must
744// check whether it's one or the other, this is why this function is for
745// private use only)
746static bool wxGetHostNameInternal(wxChar *buf, int sz)
747{
748 wxCHECK_MSG( buf, false, wxT("NULL pointer in wxGetHostNameInternal") );
749
750 *buf = wxT('\0');
751
752 // we're using uname() which is POSIX instead of less standard sysinfo()
753#if defined(HAVE_UNAME)
754 struct utsname uts;
755 bool ok = uname(&uts) != -1;
756 if ( ok )
757 {
758 wxStrncpy(buf, wxConvertMB2WX(uts.nodename), sz - 1);
759 buf[sz] = wxT('\0');
760 }
761#elif defined(HAVE_GETHOSTNAME)
762 bool ok = gethostname(buf, sz) != -1;
763#else // no uname, no gethostname
764 wxFAIL_MSG(wxT("don't know host name for this machine"));
765
766 bool ok = false;
767#endif // uname/gethostname
768
769 if ( !ok )
770 {
771 wxLogSysError(_("Cannot get the hostname"));
772 }
773
774 return ok;
775}
776
777bool wxGetHostName(wxChar *buf, int sz)
778{
779 bool ok = wxGetHostNameInternal(buf, sz);
780
781 if ( ok )
782 {
783 // BSD systems return the FQDN, we only want the hostname, so extract
784 // it (we consider that dots are domain separators)
785 wxChar *dot = wxStrchr(buf, wxT('.'));
786 if ( dot )
787 {
788 // nuke it
789 *dot = wxT('\0');
790 }
791 }
792
793 return ok;
794}
795
796bool wxGetFullHostName(wxChar *buf, int sz)
797{
798 bool ok = wxGetHostNameInternal(buf, sz);
799
800 if ( ok )
801 {
802 if ( !wxStrchr(buf, wxT('.')) )
803 {
804 struct hostent *host = gethostbyname(wxConvertWX2MB(buf));
805 if ( !host )
806 {
807 wxLogSysError(_("Cannot get the official hostname"));
808
809 ok = false;
810 }
811 else
812 {
813 // the canonical name
814 wxStrncpy(buf, wxConvertMB2WX(host->h_name), sz);
815 }
816 }
817 //else: it's already a FQDN (BSD behaves this way)
818 }
819
820 return ok;
821}
822
823bool wxGetUserId(wxChar *buf, int sz)
824{
825 struct passwd *who;
826
827 *buf = wxT('\0');
828 if ((who = getpwuid(getuid ())) != NULL)
829 {
830 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
831 return true;
832 }
833
834 return false;
835}
836
837bool wxGetUserName(wxChar *buf, int sz)
838{
839 struct passwd *who;
840
841 *buf = wxT('\0');
842 if ((who = getpwuid (getuid ())) != NULL)
843 {
844 // pw_gecos field in struct passwd is not standard
845#ifdef HAVE_PW_GECOS
846 char *comma = strchr(who->pw_gecos, ',');
847 if (comma)
848 *comma = '\0'; // cut off non-name comment fields
849 wxStrncpy (buf, wxConvertMB2WX(who->pw_gecos), sz - 1);
850#else // !HAVE_PW_GECOS
851 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
852#endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
853 return true;
854 }
855
856 return false;
857}
858
859// this function is in mac/utils.cpp for wxMac
860#ifndef __WXMAC__
861
862wxString wxGetOsDescription()
863{
864 FILE *f = popen("uname -s -r -m", "r");
865 if (f)
866 {
867 char buf[256];
868 size_t c = fread(buf, 1, sizeof(buf) - 1, f);
869 pclose(f);
870 // Trim newline from output.
871 if (c && buf[c - 1] == '\n')
872 --c;
873 buf[c] = '\0';
874 return wxString::FromAscii( buf );
875 }
876 wxFAIL_MSG( _T("uname failed") );
877 return wxEmptyString;
878}
879
880#endif // !__WXMAC__
881
882unsigned long wxGetProcessId()
883{
884 return (unsigned long)getpid();
885}
886
887wxMemorySize wxGetFreeMemory()
888{
889#if defined(__LINUX__)
890 // get it from /proc/meminfo
891 FILE *fp = fopen("/proc/meminfo", "r");
892 if ( fp )
893 {
894 long memFree = -1;
895
896 char buf[1024];
897 if ( fgets(buf, WXSIZEOF(buf), fp) && fgets(buf, WXSIZEOF(buf), fp) )
898 {
899 long memTotal, memUsed;
900 sscanf(buf, "Mem: %ld %ld %ld", &memTotal, &memUsed, &memFree);
901 }
902
903 fclose(fp);
904
905 return (wxMemorySize)memFree;
906 }
907#elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
908 return (wxMemorySize)(sysconf(_SC_AVPHYS_PAGES)*sysconf(_SC_PAGESIZE));
909#elif defined(__SGI__)
910 struct rminfo realmem;
911 if ( sysmp(MP_SAGET, MPSA_RMINFO, &realmem, sizeof realmem) == 0 )
912 return ((wxMemorySize)realmem.physmem * sysconf(_SC_PAGESIZE));
913//#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
914#endif
915
916 // can't find it out
917 return -1;
918}
919
920bool wxGetDiskSpace(const wxString& path, wxDiskspaceSize_t *pTotal, wxDiskspaceSize_t *pFree)
921{
922#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
923 // the case to "char *" is needed for AIX 4.3
924 wxStatfs_t fs;
925 if ( wxStatfs((char *)(const char*)path.fn_str(), &fs) != 0 )
926 {
927 wxLogSysError( wxT("Failed to get file system statistics") );
928
929 return false;
930 }
931
932 // under Solaris we also have to use f_frsize field instead of f_bsize
933 // which is in general a multiple of f_frsize
934#ifdef HAVE_STATVFS
935 wxDiskspaceSize_t blockSize = fs.f_frsize;
936#else // HAVE_STATFS
937 wxDiskspaceSize_t blockSize = fs.f_bsize;
938#endif // HAVE_STATVFS/HAVE_STATFS
939
940 if ( pTotal )
941 {
942 *pTotal = wxDiskspaceSize_t(fs.f_blocks) * blockSize;
943 }
944
945 if ( pFree )
946 {
947 *pFree = wxDiskspaceSize_t(fs.f_bavail) * blockSize;
948 }
949
950 return true;
951#else // !HAVE_STATFS && !HAVE_STATVFS
952 return false;
953#endif // HAVE_STATFS
954}
955
956// ----------------------------------------------------------------------------
957// env vars
958// ----------------------------------------------------------------------------
959
960bool wxGetEnv(const wxString& var, wxString *value)
961{
962 // wxGetenv is defined as getenv()
963 wxChar *p = wxGetenv(var);
964 if ( !p )
965 return false;
966
967 if ( value )
968 {
969 *value = p;
970 }
971
972 return true;
973}
974
975bool wxSetEnv(const wxString& variable, const wxChar *value)
976{
977#if defined(HAVE_SETENV)
978 return setenv(variable.mb_str(),
979 value ? (const char *)wxString(value).mb_str()
980 : NULL,
981 1 /* overwrite */) == 0;
982#elif defined(HAVE_PUTENV)
983 wxString s = variable;
984 if ( value )
985 s << _T('=') << value;
986
987 // transform to ANSI
988 const wxWX2MBbuf p = s.mb_str();
989
990 // the string will be free()d by libc
991 char *buf = (char *)malloc(strlen(p) + 1);
992 strcpy(buf, p);
993
994 return putenv(buf) == 0;
995#else // no way to set an env var
996 return false;
997#endif
998}
999
1000// ----------------------------------------------------------------------------
1001// signal handling
1002// ----------------------------------------------------------------------------
1003
1004#if wxUSE_ON_FATAL_EXCEPTION
1005
1006#include <signal.h>
1007
1008extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER)
1009{
1010 if ( wxTheApp )
1011 {
1012 // give the user a chance to do something special about this
1013 wxTheApp->OnFatalException();
1014 }
1015
1016 abort();
1017}
1018
1019bool wxHandleFatalExceptions(bool doit)
1020{
1021 // old sig handlers
1022 static bool s_savedHandlers = false;
1023 static struct sigaction s_handlerFPE,
1024 s_handlerILL,
1025 s_handlerBUS,
1026 s_handlerSEGV;
1027
1028 bool ok = true;
1029 if ( doit && !s_savedHandlers )
1030 {
1031 // install the signal handler
1032 struct sigaction act;
1033
1034 // some systems extend it with non std fields, so zero everything
1035 memset(&act, 0, sizeof(act));
1036
1037 act.sa_handler = wxFatalSignalHandler;
1038 sigemptyset(&act.sa_mask);
1039 act.sa_flags = 0;
1040
1041 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
1042 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
1043 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
1044 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
1045 if ( !ok )
1046 {
1047 wxLogDebug(_T("Failed to install our signal handler."));
1048 }
1049
1050 s_savedHandlers = true;
1051 }
1052 else if ( s_savedHandlers )
1053 {
1054 // uninstall the signal handler
1055 ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
1056 ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
1057 ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
1058 ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
1059 if ( !ok )
1060 {
1061 wxLogDebug(_T("Failed to uninstall our signal handler."));
1062 }
1063
1064 s_savedHandlers = false;
1065 }
1066 //else: nothing to do
1067
1068 return ok;
1069}
1070
1071#endif // wxUSE_ON_FATAL_EXCEPTION
1072
1073#endif // wxUSE_BASE
1074
1075#if wxUSE_GUI
1076
1077// ----------------------------------------------------------------------------
1078// wxExecute support
1079// ----------------------------------------------------------------------------
1080
1081// Darwin doesn't use the same process end detection mechanisms so we don't
1082// need wxExecute-related helpers for it
1083#if !(defined(__DARWIN__) && defined(__WXMAC__))
1084
1085bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData& execData)
1086{
1087 return execData.pipeEndProcDetect.Create();
1088}
1089
1090bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData& execData, int fd)
1091{
1092 return fd == (execData.pipeEndProcDetect)[wxPipe::Write];
1093}
1094
1095void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData& execData)
1096{
1097 execData.pipeEndProcDetect.Detach(wxPipe::Write);
1098 execData.pipeEndProcDetect.Close();
1099}
1100
1101#else // !Darwin
1102
1103bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData& WXUNUSED(execData))
1104{
1105 return true;
1106}
1107
1108bool
1109wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData& WXUNUSED(execData),
1110 int WXUNUSED(fd))
1111{
1112 return false;
1113}
1114
1115void
1116wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData& WXUNUSED(execData))
1117{
1118 // nothing to do here, we don't use the pipe
1119}
1120
1121#endif // !Darwin/Darwin
1122
1123int wxGUIAppTraits::WaitForChild(wxExecuteData& execData)
1124{
1125 wxEndProcessData *endProcData = new wxEndProcessData;
1126
1127 const int flags = execData.flags;
1128
1129 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1130 // callback function directly if the process terminates before
1131 // the callback can be added to the run loop. Set up the endProcData.
1132 if ( flags & wxEXEC_SYNC )
1133 {
1134 // we may have process for capturing the program output, but it's
1135 // not used in wxEndProcessData in the case of sync execution
1136 endProcData->process = NULL;
1137
1138 // sync execution: indicate it by negating the pid
1139 endProcData->pid = -execData.pid;
1140 }
1141 else
1142 {
1143 // async execution, nothing special to do -- caller will be
1144 // notified about the process termination if process != NULL, endProcData
1145 // will be deleted in GTK_EndProcessDetector
1146 endProcData->process = execData.process;
1147 endProcData->pid = execData.pid;
1148 }
1149
1150
1151#if defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1152 endProcData->tag = wxAddProcessCallbackForPid(endProcData, execData.pid);
1153#else
1154 endProcData->tag = wxAddProcessCallback
1155 (
1156 endProcData,
1157 execData.pipeEndProcDetect.Detach(wxPipe::Read)
1158 );
1159
1160 execData.pipeEndProcDetect.Close();
1161#endif // defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__))
1162
1163 if ( flags & wxEXEC_SYNC )
1164 {
1165 wxBusyCursor bc;
1166 wxWindowDisabler *wd = flags & wxEXEC_NODISABLE ? NULL
1167 : new wxWindowDisabler;
1168
1169 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1170 // process terminates
1171 while ( endProcData->pid != 0 )
1172 {
1173 bool idle = true;
1174
1175#if wxUSE_STREAMS
1176 if ( execData.bufOut )
1177 {
1178 execData.bufOut->Update();
1179 idle = false;
1180 }
1181
1182 if ( execData.bufErr )
1183 {
1184 execData.bufErr->Update();
1185 idle = false;
1186 }
1187#endif // wxUSE_STREAMS
1188
1189 // don't consume 100% of the CPU while we're sitting in this
1190 // loop
1191 if ( idle )
1192 wxMilliSleep(1);
1193
1194 // give GTK+ a chance to call GTK_EndProcessDetector here and
1195 // also repaint the GUI
1196 wxYield();
1197 }
1198
1199 int exitcode = endProcData->exitcode;
1200
1201 delete wd;
1202 delete endProcData;
1203
1204 return exitcode;
1205 }
1206 else // async execution
1207 {
1208 return execData.pid;
1209 }
1210}
1211
1212#endif // wxUSE_GUI
1213#if wxUSE_BASE
1214
1215void wxHandleProcessTermination(wxEndProcessData *proc_data)
1216{
1217 // notify user about termination if required
1218 if ( proc_data->process )
1219 {
1220 proc_data->process->OnTerminate(proc_data->pid, proc_data->exitcode);
1221 }
1222
1223 // clean up
1224 if ( proc_data->pid > 0 )
1225 {
1226 delete proc_data;
1227 }
1228 else
1229 {
1230 // let wxExecute() know that the process has terminated
1231 proc_data->pid = 0;
1232 }
1233}
1234
1235#endif // wxUSE_BASE