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