natPosixProcess.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. // natPosixProcess.cc - Native side of POSIX process code.
  2. /* Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007
  3. Free Software Foundation
  4. This file is part of libgcj.
  5. This software is copyrighted work licensed under the terms of the
  6. Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
  7. details. */
  8. #include <config.h>
  9. #ifdef HAVE_UNISTD_H
  10. #include <unistd.h>
  11. #endif
  12. #include <errno.h>
  13. #include <fcntl.h>
  14. #include <sys/types.h>
  15. #include <sys/wait.h>
  16. #ifdef HAVE_SYS_TIME_H
  17. #include <sys/time.h>
  18. #endif
  19. #ifdef HAVE_SYS_RESOURCE_H
  20. #include <sys/resource.h>
  21. #endif
  22. #include <signal.h>
  23. #include <string.h>
  24. #include <stdlib.h>
  25. #include <stdio.h>
  26. #include <unistd.h>
  27. #include <pthread.h>
  28. #include <posix.h>
  29. #include <posix-threads.h>
  30. #include <jvm.h>
  31. #include <java/lang/PosixProcess$ProcessManager.h>
  32. #include <java/lang/PosixProcess.h>
  33. #include <java/lang/IllegalThreadStateException.h>
  34. #include <java/lang/InternalError.h>
  35. #include <java/lang/InterruptedException.h>
  36. #include <java/lang/NullPointerException.h>
  37. #include <java/lang/Thread.h>
  38. #include <java/io/File.h>
  39. #include <java/io/FileDescriptor.h>
  40. #include <gnu/java/nio/channels/FileChannelImpl.h>
  41. #include <java/io/FileInputStream.h>
  42. #include <java/io/FileOutputStream.h>
  43. #include <java/io/IOException.h>
  44. #include <java/lang/OutOfMemoryError.h>
  45. #include <java/lang/PosixProcess$EOFInputStream.h>
  46. using gnu::java::nio::channels::FileChannelImpl;
  47. using namespace java::lang;
  48. extern char **environ;
  49. static char *
  50. new_string (jstring string)
  51. {
  52. jsize s = _Jv_GetStringUTFLength (string);
  53. char *buf = (char *) _Jv_Malloc (s + 1);
  54. _Jv_GetStringUTFRegion (string, 0, string->length(), buf);
  55. buf[s] = '\0';
  56. return buf;
  57. }
  58. static void
  59. cleanup (char **args, char **env, char *path)
  60. {
  61. if (args != NULL)
  62. {
  63. for (int i = 0; args[i] != NULL; ++i)
  64. _Jv_Free (args[i]);
  65. _Jv_Free (args);
  66. }
  67. if (env != NULL)
  68. {
  69. for (int i = 0; env[i] != NULL; ++i)
  70. _Jv_Free (env[i]);
  71. _Jv_Free (env);
  72. }
  73. if (path != NULL)
  74. _Jv_Free (path);
  75. }
  76. // This makes our error handling a bit simpler and it lets us avoid
  77. // thread bugs where we close a possibly-reopened file descriptor for
  78. // a second time.
  79. static void
  80. myclose (int &fd)
  81. {
  82. if (fd != -1)
  83. close (fd);
  84. fd = -1;
  85. }
  86. namespace
  87. {
  88. struct ProcessManagerInternal
  89. {
  90. int pipe_ends[2];
  91. struct sigaction old_sigaction;
  92. };
  93. }
  94. // There has to be a signal handler in order to be able to
  95. // sigwait() on SIGCHLD. The information passed is ignored as it
  96. // will be recovered by the waitpid() call.
  97. static void
  98. #ifdef SA_SIGINFO
  99. sigchld_handler (int sig, siginfo_t *si, void *third)
  100. #else
  101. sigchld_handler (int sig)
  102. #endif
  103. {
  104. if (PosixProcess$ProcessManager::nativeData != NULL)
  105. {
  106. ProcessManagerInternal *pmi =
  107. (ProcessManagerInternal *)PosixProcess$ProcessManager::nativeData;
  108. char c = 0;
  109. ::write(pmi->pipe_ends[1], &c, 1);
  110. if (pmi->old_sigaction.sa_handler != SIG_DFL
  111. && pmi->old_sigaction.sa_handler != SIG_IGN)
  112. {
  113. #ifdef SA_SIGINFO
  114. if ((pmi->old_sigaction.sa_flags & SA_SIGINFO) != 0)
  115. pmi->old_sigaction.sa_sigaction(sig, si, third);
  116. else
  117. #endif
  118. (*pmi->old_sigaction.sa_handler)(sig);
  119. }
  120. }
  121. }
  122. // Get ready to enter the main reaper thread loop.
  123. void
  124. java::lang::PosixProcess$ProcessManager::init ()
  125. {
  126. // The nativeData is static to avoid races installing the signal
  127. // handler in the case that it is chained.
  128. if (nativeData == NULL )
  129. {
  130. ProcessManagerInternal *pmi =
  131. (ProcessManagerInternal *)JvAllocBytes(sizeof(ProcessManagerInternal));
  132. if (0 != ::pipe(pmi->pipe_ends))
  133. goto error;
  134. // Make writing non-blocking so that the signal handler will
  135. // never block.
  136. int fl = ::fcntl(pmi->pipe_ends[1], F_GETFL);
  137. ::fcntl(pmi->pipe_ends[1], F_SETFL, fl | O_NONBLOCK);
  138. nativeData = (::gnu::gcj::RawDataManaged *)pmi;
  139. // SIGCHLD is blocked in all threads in posix-threads.cc.
  140. // Setup the SIGCHLD handler.
  141. struct sigaction sa;
  142. memset (&sa, 0, sizeof (sa));
  143. #ifdef SA_SIGINFO
  144. sa.sa_sigaction = sigchld_handler;
  145. // We only want signals when the things exit.
  146. sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
  147. #else
  148. sa.sa_handler = sigchld_handler;
  149. // We only want signals when the things exit.
  150. sa.sa_flags = SA_NOCLDSTOP;
  151. #endif
  152. if (-1 == sigaction (SIGCHLD, &sa, &pmi->old_sigaction))
  153. goto error;
  154. }
  155. // All OK.
  156. return;
  157. error:
  158. throw new InternalError (JvNewStringUTF (strerror (errno)));
  159. }
  160. void
  161. java::lang::PosixProcess$ProcessManager::waitForSignal ()
  162. {
  163. // Wait for SIGCHLD
  164. _Jv_UnBlockSigchld();
  165. ProcessManagerInternal *pmi = (ProcessManagerInternal *)nativeData;
  166. // Try to read multiple (64) notifications in one go.
  167. char c[64];
  168. ::read(pmi->pipe_ends[0], c, sizeof (c));
  169. _Jv_BlockSigchld();
  170. return;
  171. }
  172. jboolean java::lang::PosixProcess$ProcessManager::reap (PosixProcess *p)
  173. {
  174. pid_t rv;
  175. // Try to get the return code from the child process.
  176. int status;
  177. rv = ::waitpid ((pid_t)p->pid, &status, WNOHANG);
  178. if (rv == -1)
  179. throw new InternalError (JvNewStringUTF (strerror (errno)));
  180. if (rv == 0)
  181. return false; // No children to wait for.
  182. JvSynchronize sync (p);
  183. p->status = WIFEXITED (status) ? WEXITSTATUS (status) : -1;
  184. p->state = PosixProcess::STATE_TERMINATED;
  185. p->processTerminationCleanup();
  186. p->notifyAll ();
  187. return true;
  188. }
  189. void
  190. java::lang::PosixProcess$ProcessManager::signalReaper ()
  191. {
  192. ProcessManagerInternal *pmi = (ProcessManagerInternal *)nativeData;
  193. char c = 0;
  194. ::write(pmi->pipe_ends[1], &c, 1);
  195. // Ignore errors. If EPIPE the reaper has already exited.
  196. }
  197. void
  198. java::lang::PosixProcess::nativeDestroy ()
  199. {
  200. int c = ::kill ((pid_t) pid, SIGKILL);
  201. if (c == 0)
  202. return;
  203. // kill() failed.
  204. throw new InternalError (JvNewStringUTF (strerror (errno)));
  205. }
  206. void
  207. java::lang::PosixProcess::nativeSpawn ()
  208. {
  209. using namespace java::io;
  210. // Initialize all locals here to make cleanup simpler.
  211. char **args = NULL;
  212. char **env = NULL;
  213. char *path = NULL;
  214. int inp[2], outp[2], errp[2], msgp[2];
  215. inp[0] = -1;
  216. inp[1] = -1;
  217. outp[0] = -1;
  218. outp[1] = -1;
  219. errp[0] = -1;
  220. errp[1] = -1;
  221. msgp[0] = -1;
  222. msgp[1] = -1;
  223. errorStream = NULL;
  224. inputStream = NULL;
  225. outputStream = NULL;
  226. try
  227. {
  228. // Transform arrays to native form.
  229. args = (char **) _Jv_Malloc ((progarray->length + 1) * sizeof (char *));
  230. // Initialize so we can gracefully recover.
  231. jstring *elts = elements (progarray);
  232. for (int i = 0; i <= progarray->length; ++i)
  233. args[i] = NULL;
  234. for (int i = 0; i < progarray->length; ++i)
  235. args[i] = new_string (elts[i]);
  236. args[progarray->length] = NULL;
  237. if (envp)
  238. {
  239. bool need_path = true;
  240. bool need_ld_library_path = true;
  241. int i;
  242. // Preserve PATH and LD_LIBRARY_PATH unless specified
  243. // explicitly. We need three extra slots. Potentially PATH
  244. // and LD_LIBRARY_PATH will be added plus the NULL
  245. // termination.
  246. env = (char **) _Jv_Malloc ((envp->length + 3) * sizeof (char *));
  247. elts = elements (envp);
  248. // Initialize so we can gracefully recover.
  249. for (i = 0; i < envp->length + 3; ++i)
  250. env[i] = NULL;
  251. for (i = 0; i < envp->length; ++i)
  252. {
  253. env[i] = new_string (elts[i]);
  254. if (!strncmp (env[i], "PATH=", sizeof("PATH=")))
  255. need_path = false;
  256. if (!strncmp (env[i], "LD_LIBRARY_PATH=",
  257. sizeof("LD_LIBRARY_PATH=")))
  258. need_ld_library_path = false;
  259. }
  260. if (need_path)
  261. {
  262. char *path_val = getenv ("PATH");
  263. if (path_val)
  264. {
  265. env[i] = (char *) _Jv_Malloc (strlen (path_val) +
  266. sizeof("PATH=") + 1);
  267. strcpy (env[i], "PATH=");
  268. strcat (env[i], path_val);
  269. i++;
  270. }
  271. }
  272. if (need_ld_library_path)
  273. {
  274. char *path_val = getenv ("LD_LIBRARY_PATH");
  275. if (path_val)
  276. {
  277. env[i] =
  278. (char *) _Jv_Malloc (strlen (path_val) +
  279. sizeof("LD_LIBRARY_PATH=") + 1);
  280. strcpy (env[i], "LD_LIBRARY_PATH=");
  281. strcat (env[i], path_val);
  282. i++;
  283. }
  284. }
  285. env[i] = NULL;
  286. }
  287. // We allocate this here because we can't call malloc() after
  288. // the fork.
  289. if (dir != NULL)
  290. path = new_string (dir->getPath ());
  291. // Create pipes for I/O. MSGP is for communicating exec()
  292. // status. If redirecting stderr to stdout, we don't need to
  293. // create the ERRP pipe.
  294. if (pipe (inp) || pipe (outp) || pipe (msgp)
  295. || fcntl (msgp[1], F_SETFD, FD_CLOEXEC))
  296. throw new IOException (JvNewStringUTF (strerror (errno)));
  297. if (! redirect && pipe (errp))
  298. throw new IOException (JvNewStringUTF (strerror (errno)));
  299. // We create the streams before forking. Otherwise if we had an
  300. // error while creating the streams we would have run the child
  301. // with no way to communicate with it.
  302. if (redirect)
  303. errorStream = PosixProcess$EOFInputStream::instance;
  304. else
  305. errorStream =
  306. new FileInputStream (new
  307. FileChannelImpl (errp[0],
  308. FileChannelImpl::READ));
  309. inputStream =
  310. new FileInputStream (new
  311. FileChannelImpl (inp[0], FileChannelImpl::READ));
  312. outputStream =
  313. new FileOutputStream (new FileChannelImpl (outp[1],
  314. FileChannelImpl::WRITE));
  315. // We don't use vfork() because that would cause the local
  316. // environment to be set by the child.
  317. // Use temporary for fork result to avoid dirtying an extra page.
  318. pid_t pid_tmp;
  319. if ((pid_tmp = fork ()) == -1)
  320. throw new IOException (JvNewStringUTF (strerror (errno)));
  321. if (pid_tmp == 0)
  322. {
  323. // Child process, so remap descriptors, chdir and exec.
  324. if (envp)
  325. environ = env;
  326. // We ignore errors from dup2 because they should never occur.
  327. dup2 (outp[0], 0);
  328. dup2 (inp[1], 1);
  329. dup2 (redirect ? inp[1] : errp[1], 2);
  330. // Use close and not myclose -- we're in the child, and we
  331. // aren't worried about the possible race condition.
  332. close (inp[0]);
  333. close (inp[1]);
  334. if (! redirect)
  335. {
  336. close (errp[0]);
  337. close (errp[1]);
  338. }
  339. close (outp[0]);
  340. close (outp[1]);
  341. close (msgp[0]);
  342. // Change directory.
  343. if (path != NULL)
  344. {
  345. if (chdir (path) != 0)
  346. {
  347. char c = errno;
  348. write (msgp[1], &c, 1);
  349. _exit (127);
  350. }
  351. }
  352. // Make sure all file descriptors are closed. In
  353. // multi-threaded programs, there is a race between when a
  354. // descriptor is obtained, when we can set FD_CLOEXEC, and
  355. // fork(). If the fork occurs before FD_CLOEXEC is set, the
  356. // descriptor would leak to the execed process if we did not
  357. // manually close it. So that is what we do. Since we
  358. // close all the descriptors, it is redundant to set
  359. // FD_CLOEXEC on them elsewhere.
  360. int max_fd;
  361. #ifdef HAVE_GETRLIMIT
  362. rlimit rl;
  363. int rv = getrlimit(RLIMIT_NOFILE, &rl);
  364. if (rv == 0)
  365. max_fd = rl.rlim_max - 1;
  366. else
  367. max_fd = 1024 - 1;
  368. #else
  369. max_fd = 1024 - 1;
  370. #endif
  371. while(max_fd > 2)
  372. {
  373. if (max_fd != msgp[1])
  374. close (max_fd);
  375. max_fd--;
  376. }
  377. // Make sure that SIGCHLD is unblocked for the new process.
  378. sigset_t mask;
  379. sigemptyset (&mask);
  380. sigaddset (&mask, SIGCHLD);
  381. sigprocmask (SIG_UNBLOCK, &mask, NULL);
  382. execvp (args[0], args);
  383. // Send the parent notification that the exec failed.
  384. char c = errno;
  385. write (msgp[1], &c, 1);
  386. _exit (127);
  387. }
  388. // Parent. Close extra file descriptors and mark ours as
  389. // close-on-exec.
  390. pid = (jlong) pid_tmp;
  391. myclose (outp[0]);
  392. myclose (inp[1]);
  393. if (! redirect)
  394. myclose (errp[1]);
  395. myclose (msgp[1]);
  396. char c;
  397. int r = read (msgp[0], &c, 1);
  398. if (r == -1)
  399. throw new IOException (JvNewStringUTF (strerror (errno)));
  400. else if (r != 0)
  401. throw new IOException (JvNewStringUTF (strerror (c)));
  402. }
  403. catch (java::lang::Throwable *thrown)
  404. {
  405. // Do some cleanup we only do on failure. If a stream object
  406. // has been created, we must close the stream itself (to avoid
  407. // duplicate closes when the stream object is collected).
  408. // Otherwise we simply close the underlying file descriptor.
  409. // We ignore errors here as they are uninteresting.
  410. try
  411. {
  412. if (inputStream != NULL)
  413. inputStream->close ();
  414. else
  415. myclose (inp[0]);
  416. }
  417. catch (java::lang::Throwable *ignore)
  418. {
  419. }
  420. try
  421. {
  422. if (outputStream != NULL)
  423. outputStream->close ();
  424. else
  425. myclose (outp[1]);
  426. }
  427. catch (java::lang::Throwable *ignore)
  428. {
  429. }
  430. try
  431. {
  432. if (errorStream != NULL)
  433. errorStream->close ();
  434. else if (! redirect)
  435. myclose (errp[0]);
  436. }
  437. catch (java::lang::Throwable *ignore)
  438. {
  439. }
  440. // These are potentially duplicate, but it doesn't matter due to
  441. // the use of myclose.
  442. myclose (outp[0]);
  443. myclose (inp[1]);
  444. if (! redirect)
  445. myclose (errp[1]);
  446. myclose (msgp[1]);
  447. exception = thrown;
  448. }
  449. myclose (msgp[0]);
  450. cleanup (args, env, path);
  451. }