Runtime.java 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. /* Runtime.java -- access to the VM process
  2. Copyright (C) 1998, 2002, 2003, 2004, 2005 Free Software Foundation
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.lang;
  32. import gnu.classpath.SystemProperties;
  33. import gnu.classpath.VMStackWalker;
  34. import java.io.File;
  35. import java.io.IOException;
  36. import java.io.InputStream;
  37. import java.io.OutputStream;
  38. import java.util.HashSet;
  39. import java.util.Iterator;
  40. import java.util.Set;
  41. import java.util.StringTokenizer;
  42. /**
  43. * Runtime represents the Virtual Machine.
  44. *
  45. * @author John Keiser
  46. * @author Eric Blake (ebb9@email.byu.edu)
  47. * @author Jeroen Frijters
  48. */
  49. // No idea why this class isn't final, since you can't build a subclass!
  50. public class Runtime
  51. {
  52. /**
  53. * The library path, to search when loading libraries. We can also safely use
  54. * this as a lock for synchronization.
  55. */
  56. private final String[] libpath;
  57. /**
  58. * The thread that started the exit sequence. Access to this field must
  59. * be thread-safe; lock on libpath to avoid deadlock with user code.
  60. * <code>runFinalization()</code> may want to look at this to see if ALL
  61. * finalizers should be run, because the virtual machine is about to halt.
  62. */
  63. private Thread exitSequence;
  64. /**
  65. * All shutdown hooks. This is initialized lazily, and set to null once all
  66. * shutdown hooks have run. Access to this field must be thread-safe; lock
  67. * on libpath to avoid deadlock with user code.
  68. */
  69. private Set shutdownHooks;
  70. /**
  71. * The one and only runtime instance.
  72. */
  73. private static final Runtime current = new Runtime();
  74. /**
  75. * Not instantiable by a user, this should only create one instance.
  76. */
  77. private Runtime()
  78. {
  79. if (current != null)
  80. throw new InternalError("Attempt to recreate Runtime");
  81. // If used by underlying VM this contains the directories where Classpath's own
  82. // native libraries are located.
  83. String bootPath = SystemProperties.getProperty("gnu.classpath.boot.library.path", "");
  84. // If properly set by the user this contains the directories where the application's
  85. // native libraries are located. On operating systems where a LD_LIBRARY_PATH environment
  86. // variable is available a VM should preset java.library.path with value of this
  87. // variable.
  88. String path = SystemProperties.getProperty("java.library.path", ".");
  89. String pathSep = SystemProperties.getProperty("path.separator", ":");
  90. String fileSep = SystemProperties.getProperty("file.separator", "/");
  91. StringTokenizer t1 = new StringTokenizer(bootPath, pathSep);
  92. StringTokenizer t2 = new StringTokenizer(path, pathSep);
  93. libpath = new String[t1.countTokens() + t2.countTokens()];
  94. int i = 0;
  95. while(t1.hasMoreTokens()) {
  96. String prefix = t1.nextToken();
  97. if (! prefix.endsWith(fileSep))
  98. prefix += fileSep;
  99. libpath[i] = prefix;
  100. i++;
  101. }
  102. while(t2.hasMoreTokens()) {
  103. String prefix = t2.nextToken();
  104. if (! prefix.endsWith(fileSep))
  105. prefix += fileSep;
  106. libpath[i] = prefix;
  107. i++;
  108. }
  109. }
  110. /**
  111. * Get the current Runtime object for this JVM. This is necessary to access
  112. * the many instance methods of this class.
  113. *
  114. * @return the current Runtime object
  115. */
  116. public static Runtime getRuntime()
  117. {
  118. return current;
  119. }
  120. /**
  121. * Exit the Java runtime. This method will either throw a SecurityException
  122. * or it will never return. The status code is returned to the system; often
  123. * a non-zero status code indicates an abnormal exit. Of course, there is a
  124. * security check, <code>checkExit(status)</code>.
  125. *
  126. * <p>First, all shutdown hooks are run, in unspecified order, and
  127. * concurrently. Next, if finalization on exit has been enabled, all pending
  128. * finalizers are run. Finally, the system calls <code>halt</code>.</p>
  129. *
  130. * <p>If this is run a second time after shutdown has already started, there
  131. * are two actions. If shutdown hooks are still executing, it blocks
  132. * indefinitely. Otherwise, if the status is nonzero it halts immediately;
  133. * if it is zero, it blocks indefinitely. This is typically called by
  134. * <code>System.exit</code>.</p>
  135. *
  136. * @param status the status to exit with
  137. * @throws SecurityException if permission is denied
  138. * @see #addShutdownHook(Thread)
  139. * @see #runFinalizersOnExit(boolean)
  140. * @see #runFinalization()
  141. * @see #halt(int)
  142. */
  143. public void exit(int status)
  144. {
  145. SecurityManager sm = SecurityManager.current; // Be thread-safe!
  146. if (sm != null)
  147. sm.checkExit(status);
  148. if (runShutdownHooks())
  149. halt(status);
  150. // Someone else already called runShutdownHooks().
  151. // Make sure we are not/no longer in the shutdownHooks set.
  152. // And wait till the thread that is calling runShutdownHooks() finishes.
  153. synchronized (libpath)
  154. {
  155. if (shutdownHooks != null)
  156. {
  157. shutdownHooks.remove(Thread.currentThread());
  158. // Interrupt the exit sequence thread, in case it was waiting
  159. // inside a join on our thread.
  160. exitSequence.interrupt();
  161. // Shutdown hooks are still running, so we clear status to
  162. // make sure we don't halt.
  163. status = 0;
  164. }
  165. }
  166. // If exit() is called again after the shutdown hooks have run, but
  167. // while finalization for exit is going on and the status is non-zero
  168. // we halt immediately.
  169. if (status != 0)
  170. halt(status);
  171. while (true)
  172. try
  173. {
  174. exitSequence.join();
  175. }
  176. catch (InterruptedException e)
  177. {
  178. // Ignore, we've suspended indefinitely to let all shutdown
  179. // hooks complete, and to let any non-zero exits through, because
  180. // this is a duplicate call to exit(0).
  181. }
  182. }
  183. /**
  184. * On first invocation, run all the shutdown hooks and return true.
  185. * Any subsequent invocations will simply return false.
  186. * Note that it is package accessible so that VMRuntime can call it
  187. * when VM exit is not triggered by a call to Runtime.exit().
  188. *
  189. * @return was the current thread the first one to call this method?
  190. */
  191. boolean runShutdownHooks()
  192. {
  193. boolean first = false;
  194. synchronized (libpath) // Synch on libpath, not this, to avoid deadlock.
  195. {
  196. if (exitSequence == null)
  197. {
  198. first = true;
  199. exitSequence = Thread.currentThread();
  200. if (shutdownHooks != null)
  201. {
  202. Iterator i = shutdownHooks.iterator();
  203. while (i.hasNext()) // Start all shutdown hooks.
  204. try
  205. {
  206. ((Thread) i.next()).start();
  207. }
  208. catch (IllegalThreadStateException e)
  209. {
  210. i.remove();
  211. }
  212. }
  213. }
  214. }
  215. if (first)
  216. {
  217. if (shutdownHooks != null)
  218. {
  219. // Check progress of all shutdown hooks. As a hook completes,
  220. // remove it from the set. If a hook calls exit, it removes
  221. // itself from the set, then waits indefinitely on the
  222. // exitSequence thread. Once the set is empty, set it to null to
  223. // signal all finalizer threads that halt may be called.
  224. while (true)
  225. {
  226. Thread[] hooks;
  227. synchronized (libpath)
  228. {
  229. hooks = new Thread[shutdownHooks.size()];
  230. shutdownHooks.toArray(hooks);
  231. }
  232. if (hooks.length == 0)
  233. break;
  234. for (int i = 0; i < hooks.length; i++)
  235. {
  236. try
  237. {
  238. synchronized (libpath)
  239. {
  240. if (!shutdownHooks.contains(hooks[i]))
  241. continue;
  242. }
  243. hooks[i].join();
  244. synchronized (libpath)
  245. {
  246. shutdownHooks.remove(hooks[i]);
  247. }
  248. }
  249. catch (InterruptedException x)
  250. {
  251. // continue waiting on the next thread
  252. }
  253. }
  254. }
  255. synchronized (libpath)
  256. {
  257. shutdownHooks = null;
  258. }
  259. }
  260. // Run finalization on all finalizable objects (even if they are
  261. // still reachable).
  262. VMRuntime.runFinalizationForExit();
  263. }
  264. return first;
  265. }
  266. /**
  267. * Register a new shutdown hook. This is invoked when the program exits
  268. * normally (because all non-daemon threads ended, or because
  269. * <code>System.exit</code> was invoked), or when the user terminates
  270. * the virtual machine (such as by typing ^C, or logging off). There is
  271. * a security check to add hooks,
  272. * <code>RuntimePermission("shutdownHooks")</code>.
  273. *
  274. * <p>The hook must be an initialized, but unstarted Thread. The threads
  275. * are run concurrently, and started in an arbitrary order; and user
  276. * threads or daemons may still be running. Once shutdown hooks have
  277. * started, they must all complete, or else you must use <code>halt</code>,
  278. * to actually finish the shutdown sequence. Attempts to modify hooks
  279. * after shutdown has started result in IllegalStateExceptions.</p>
  280. *
  281. * <p>It is imperative that you code shutdown hooks defensively, as you
  282. * do not want to deadlock, and have no idea what other hooks will be
  283. * running concurrently. It is also a good idea to finish quickly, as the
  284. * virtual machine really wants to shut down!</p>
  285. *
  286. * <p>There are no guarantees that such hooks will run, as there are ways
  287. * to forcibly kill a process. But in such a drastic case, shutdown hooks
  288. * would do little for you in the first place.</p>
  289. *
  290. * @param hook an initialized, unstarted Thread
  291. * @throws IllegalArgumentException if the hook is already registered or run
  292. * @throws IllegalStateException if the virtual machine is already in
  293. * the shutdown sequence
  294. * @throws SecurityException if permission is denied
  295. * @since 1.3
  296. * @see #removeShutdownHook(Thread)
  297. * @see #exit(int)
  298. * @see #halt(int)
  299. */
  300. public void addShutdownHook(Thread hook)
  301. {
  302. SecurityManager sm = SecurityManager.current; // Be thread-safe!
  303. if (sm != null)
  304. sm.checkPermission(new RuntimePermission("shutdownHooks"));
  305. if (hook.isAlive() || hook.getThreadGroup() == null)
  306. throw new IllegalArgumentException("The hook thread " + hook + " must not have been already run or started");
  307. synchronized (libpath)
  308. {
  309. if (exitSequence != null)
  310. throw new IllegalStateException("The Virtual Machine is exiting. It is not possible anymore to add any hooks");
  311. if (shutdownHooks == null)
  312. {
  313. VMRuntime.enableShutdownHooks();
  314. shutdownHooks = new HashSet(); // Lazy initialization.
  315. }
  316. if (! shutdownHooks.add(hook))
  317. throw new IllegalArgumentException(hook.toString() + " had already been inserted");
  318. }
  319. }
  320. /**
  321. * De-register a shutdown hook. As when you registered it, there is a
  322. * security check to remove hooks,
  323. * <code>RuntimePermission("shutdownHooks")</code>.
  324. *
  325. * @param hook the hook to remove
  326. * @return true if the hook was successfully removed, false if it was not
  327. * registered in the first place
  328. * @throws IllegalStateException if the virtual machine is already in
  329. * the shutdown sequence
  330. * @throws SecurityException if permission is denied
  331. * @since 1.3
  332. * @see #addShutdownHook(Thread)
  333. * @see #exit(int)
  334. * @see #halt(int)
  335. */
  336. public boolean removeShutdownHook(Thread hook)
  337. {
  338. SecurityManager sm = SecurityManager.current; // Be thread-safe!
  339. if (sm != null)
  340. sm.checkPermission(new RuntimePermission("shutdownHooks"));
  341. synchronized (libpath)
  342. {
  343. if (exitSequence != null)
  344. throw new IllegalStateException();
  345. if (shutdownHooks != null)
  346. return shutdownHooks.remove(hook);
  347. }
  348. return false;
  349. }
  350. /**
  351. * Forcibly terminate the virtual machine. This call never returns. It is
  352. * much more severe than <code>exit</code>, as it bypasses all shutdown
  353. * hooks and initializers. Use caution in calling this! Of course, there is
  354. * a security check, <code>checkExit(status)</code>.
  355. *
  356. * @param status the status to exit with
  357. * @throws SecurityException if permission is denied
  358. * @since 1.3
  359. * @see #exit(int)
  360. * @see #addShutdownHook(Thread)
  361. */
  362. public void halt(int status)
  363. {
  364. SecurityManager sm = SecurityManager.current; // Be thread-safe!
  365. if (sm != null)
  366. sm.checkExit(status);
  367. VMRuntime.exit(status);
  368. }
  369. /**
  370. * Tell the VM to run the finalize() method on every single Object before
  371. * it exits. Note that the JVM may still exit abnormally and not perform
  372. * this, so you still don't have a guarantee. And besides that, this is
  373. * inherently unsafe in multi-threaded code, as it may result in deadlock
  374. * as multiple threads compete to manipulate objects. This value defaults to
  375. * <code>false</code>. There is a security check, <code>checkExit(0)</code>.
  376. *
  377. * @param finalizeOnExit whether to finalize all Objects on exit
  378. * @throws SecurityException if permission is denied
  379. * @see #exit(int)
  380. * @see #gc()
  381. * @since 1.1
  382. * @deprecated never rely on finalizers to do a clean, thread-safe,
  383. * mop-up from your code
  384. */
  385. public static void runFinalizersOnExit(boolean finalizeOnExit)
  386. {
  387. SecurityManager sm = SecurityManager.current; // Be thread-safe!
  388. if (sm != null)
  389. sm.checkExit(0);
  390. VMRuntime.runFinalizersOnExit(finalizeOnExit);
  391. }
  392. /**
  393. * Create a new subprocess with the specified command line. Calls
  394. * <code>exec(cmdline, null, null)</code>. A security check is performed,
  395. * <code>checkExec</code>.
  396. *
  397. * @param cmdline the command to call
  398. * @return the Process object
  399. * @throws SecurityException if permission is denied
  400. * @throws IOException if an I/O error occurs
  401. * @throws NullPointerException if cmdline is null
  402. * @throws IndexOutOfBoundsException if cmdline is ""
  403. */
  404. public Process exec(String cmdline) throws IOException
  405. {
  406. return exec(cmdline, null, null);
  407. }
  408. /**
  409. * Create a new subprocess with the specified command line and environment.
  410. * If the environment is null, the process inherits the environment of
  411. * this process. Calls <code>exec(cmdline, env, null)</code>. A security
  412. * check is performed, <code>checkExec</code>.
  413. *
  414. * @param cmdline the command to call
  415. * @param env the environment to use, in the format name=value
  416. * @return the Process object
  417. * @throws SecurityException if permission is denied
  418. * @throws IOException if an I/O error occurs
  419. * @throws NullPointerException if cmdline is null, or env has null entries
  420. * @throws IndexOutOfBoundsException if cmdline is ""
  421. */
  422. public Process exec(String cmdline, String[] env) throws IOException
  423. {
  424. return exec(cmdline, env, null);
  425. }
  426. /**
  427. * Create a new subprocess with the specified command line, environment, and
  428. * working directory. If the environment is null, the process inherits the
  429. * environment of this process. If the directory is null, the process uses
  430. * the current working directory. This splits cmdline into an array, using
  431. * the default StringTokenizer, then calls
  432. * <code>exec(cmdArray, env, dir)</code>. A security check is performed,
  433. * <code>checkExec</code>.
  434. *
  435. * @param cmdline the command to call
  436. * @param env the environment to use, in the format name=value
  437. * @param dir the working directory to use
  438. * @return the Process object
  439. * @throws SecurityException if permission is denied
  440. * @throws IOException if an I/O error occurs
  441. * @throws NullPointerException if cmdline is null, or env has null entries
  442. * @throws IndexOutOfBoundsException if cmdline is ""
  443. * @since 1.3
  444. */
  445. public Process exec(String cmdline, String[] env, File dir)
  446. throws IOException
  447. {
  448. StringTokenizer t = new StringTokenizer(cmdline);
  449. String[] cmd = new String[t.countTokens()];
  450. for (int i = 0; i < cmd.length; i++)
  451. cmd[i] = t.nextToken();
  452. return exec(cmd, env, dir);
  453. }
  454. /**
  455. * Create a new subprocess with the specified command line, already
  456. * tokenized. Calls <code>exec(cmd, null, null)</code>. A security check
  457. * is performed, <code>checkExec</code>.
  458. *
  459. * @param cmd the command to call
  460. * @return the Process object
  461. * @throws SecurityException if permission is denied
  462. * @throws IOException if an I/O error occurs
  463. * @throws NullPointerException if cmd is null, or has null entries
  464. * @throws IndexOutOfBoundsException if cmd is length 0
  465. */
  466. public Process exec(String[] cmd) throws IOException
  467. {
  468. return exec(cmd, null, null);
  469. }
  470. /**
  471. * Create a new subprocess with the specified command line, already
  472. * tokenized, and specified environment. If the environment is null, the
  473. * process inherits the environment of this process. Calls
  474. * <code>exec(cmd, env, null)</code>. A security check is performed,
  475. * <code>checkExec</code>.
  476. *
  477. * @param cmd the command to call
  478. * @param env the environment to use, in the format name=value
  479. * @return the Process object
  480. * @throws SecurityException if permission is denied
  481. * @throws IOException if an I/O error occurs
  482. * @throws NullPointerException if cmd is null, or cmd or env has null
  483. * entries
  484. * @throws IndexOutOfBoundsException if cmd is length 0
  485. */
  486. public Process exec(String[] cmd, String[] env) throws IOException
  487. {
  488. return exec(cmd, env, null);
  489. }
  490. /**
  491. * Create a new subprocess with the specified command line, already
  492. * tokenized, and the specified environment and working directory. If the
  493. * environment is null, the process inherits the environment of this
  494. * process. If the directory is null, the process uses the current working
  495. * directory. A security check is performed, <code>checkExec</code>.
  496. *
  497. * @param cmd the command to call
  498. * @param env the environment to use, in the format name=value
  499. * @param dir the working directory to use
  500. * @return the Process object
  501. * @throws SecurityException if permission is denied
  502. * @throws IOException if an I/O error occurs
  503. * @throws NullPointerException if cmd is null, or cmd or env has null
  504. * entries
  505. * @throws IndexOutOfBoundsException if cmd is length 0
  506. * @since 1.3
  507. */
  508. public Process exec(String[] cmd, String[] env, File dir)
  509. throws IOException
  510. {
  511. SecurityManager sm = SecurityManager.current; // Be thread-safe!
  512. if (sm != null)
  513. sm.checkExec(cmd[0]);
  514. return VMRuntime.exec(cmd, env, dir);
  515. }
  516. /**
  517. * Returns the number of available processors currently available to the
  518. * virtual machine. This number may change over time; so a multi-processor
  519. * program want to poll this to determine maximal resource usage.
  520. *
  521. * @return the number of processors available, at least 1
  522. */
  523. public int availableProcessors()
  524. {
  525. return VMRuntime.availableProcessors();
  526. }
  527. /**
  528. * Find out how much memory is still free for allocating Objects on the heap.
  529. *
  530. * @return the number of bytes of free memory for more Objects
  531. */
  532. public long freeMemory()
  533. {
  534. return VMRuntime.freeMemory();
  535. }
  536. /**
  537. * Find out how much memory total is available on the heap for allocating
  538. * Objects.
  539. *
  540. * @return the total number of bytes of memory for Objects
  541. */
  542. public long totalMemory()
  543. {
  544. return VMRuntime.totalMemory();
  545. }
  546. /**
  547. * Returns the maximum amount of memory the virtual machine can attempt to
  548. * use. This may be <code>Long.MAX_VALUE</code> if there is no inherent
  549. * limit (or if you really do have a 8 exabyte memory!).
  550. *
  551. * @return the maximum number of bytes the virtual machine will attempt
  552. * to allocate
  553. */
  554. public long maxMemory()
  555. {
  556. return VMRuntime.maxMemory();
  557. }
  558. /**
  559. * Run the garbage collector. This method is more of a suggestion than
  560. * anything. All this method guarantees is that the garbage collector will
  561. * have "done its best" by the time it returns. Notice that garbage
  562. * collection takes place even without calling this method.
  563. */
  564. public void gc()
  565. {
  566. VMRuntime.gc();
  567. }
  568. /**
  569. * Run finalization on all Objects that are waiting to be finalized. Again,
  570. * a suggestion, though a stronger one than {@link #gc()}. This calls the
  571. * <code>finalize</code> method of all objects waiting to be collected.
  572. *
  573. * @see #finalize()
  574. */
  575. public void runFinalization()
  576. {
  577. VMRuntime.runFinalization();
  578. }
  579. /**
  580. * Tell the VM to trace every bytecode instruction that executes (print out
  581. * a trace of it). No guarantees are made as to where it will be printed,
  582. * and the VM is allowed to ignore this request.
  583. *
  584. * @param on whether to turn instruction tracing on
  585. */
  586. public void traceInstructions(boolean on)
  587. {
  588. VMRuntime.traceInstructions(on);
  589. }
  590. /**
  591. * Tell the VM to trace every method call that executes (print out a trace
  592. * of it). No guarantees are made as to where it will be printed, and the
  593. * VM is allowed to ignore this request.
  594. *
  595. * @param on whether to turn method tracing on
  596. */
  597. public void traceMethodCalls(boolean on)
  598. {
  599. VMRuntime.traceMethodCalls(on);
  600. }
  601. /**
  602. * Load a native library using the system-dependent filename. This is similar
  603. * to loadLibrary, except the only name mangling done is inserting "_g"
  604. * before the final ".so" if the VM was invoked by the name "java_g". There
  605. * may be a security check, of <code>checkLink</code>.
  606. *
  607. * <p>
  608. * The library is loaded using the class loader associated with the
  609. * class associated with the invoking method.
  610. *
  611. * @param filename the file to load
  612. * @throws SecurityException if permission is denied
  613. * @throws UnsatisfiedLinkError if the library is not found
  614. */
  615. public void load(String filename)
  616. {
  617. load(filename, VMStackWalker.getCallingClassLoader());
  618. }
  619. /**
  620. * Same as <code>load(String)</code> but using the given loader.
  621. *
  622. * @param filename the file to load
  623. * @param loader class loader, or <code>null</code> for the boot loader
  624. * @throws SecurityException if permission is denied
  625. * @throws UnsatisfiedLinkError if the library is not found
  626. */
  627. void load(String filename, ClassLoader loader)
  628. {
  629. SecurityManager sm = SecurityManager.current; // Be thread-safe!
  630. if (sm != null)
  631. sm.checkLink(filename);
  632. if (loadLib(filename, loader) == 0)
  633. throw new UnsatisfiedLinkError("Could not load library " + filename);
  634. }
  635. /**
  636. * Do a security check on the filename and then load the native library.
  637. *
  638. * @param filename the file to load
  639. * @param loader class loader, or <code>null</code> for the boot loader
  640. * @return 0 on failure, nonzero on success
  641. * @throws SecurityException if file read permission is denied
  642. */
  643. private static int loadLib(String filename, ClassLoader loader)
  644. {
  645. SecurityManager sm = SecurityManager.current; // Be thread-safe!
  646. if (sm != null)
  647. sm.checkRead(filename);
  648. return VMRuntime.nativeLoad(filename, loader);
  649. }
  650. /**
  651. * Load a native library using a system-independent "short name" for the
  652. * library. It will be transformed to a correct filename in a
  653. * system-dependent manner (for example, in Windows, "mylib" will be turned
  654. * into "mylib.dll"). This is done as follows: if the context that called
  655. * load has a ClassLoader cl, then <code>cl.findLibrary(libpath)</code> is
  656. * used to convert the name. If that result was null, or there was no class
  657. * loader, this searches each directory of the system property
  658. * <code>java.library.path</code> for a file named
  659. * <code>System.mapLibraryName(libname)</code>. There may be a security
  660. * check, of <code>checkLink</code>.
  661. *
  662. * <p>Note: Besides <code>java.library.path</code> a VM may chose to search
  663. * for native libraries in a path that is specified by the
  664. * <code>gnu.classpath.boot.library.path</code> system property. However
  665. * this is for internal usage or development of GNU Classpath only.
  666. * <b>A Java application must not load a non-system library by changing
  667. * this property otherwise it will break compatibility.</b></p>
  668. *
  669. * <p>
  670. * The library is loaded using the class loader associated with the
  671. * class associated with the invoking method.
  672. *
  673. * @param libname the library to load
  674. *
  675. * @throws SecurityException if permission is denied
  676. * @throws UnsatisfiedLinkError if the library is not found
  677. *
  678. * @see System#mapLibraryName(String)
  679. * @see ClassLoader#findLibrary(String)
  680. */
  681. public void loadLibrary(String libname)
  682. {
  683. loadLibrary(libname, VMStackWalker.getCallingClassLoader());
  684. }
  685. /**
  686. * Same as <code>loadLibrary(String)</code> but using the given loader.
  687. *
  688. * @param libname the library to load
  689. * @param loader class loader, or <code>null</code> for the boot loader
  690. * @throws SecurityException if permission is denied
  691. * @throws UnsatisfiedLinkError if the library is not found
  692. */
  693. void loadLibrary(String libname, ClassLoader loader)
  694. {
  695. SecurityManager sm = SecurityManager.current; // Be thread-safe!
  696. if (sm != null)
  697. sm.checkLink(libname);
  698. String filename;
  699. if (loader != null && (filename = loader.findLibrary(libname)) != null)
  700. {
  701. if (loadLib(filename, loader) != 0)
  702. return;
  703. }
  704. else
  705. {
  706. filename = VMRuntime.mapLibraryName(libname);
  707. for (int i = 0; i < libpath.length; i++)
  708. if (loadLib(libpath[i] + filename, loader) != 0)
  709. return;
  710. }
  711. throw new UnsatisfiedLinkError("Native library `" + libname
  712. + "' not found (as file `" + filename + "') in gnu.classpath.boot.library.path and java.library.path");
  713. }
  714. /**
  715. * Return a localized version of this InputStream, meaning all characters
  716. * are localized before they come out the other end.
  717. *
  718. * @param in the stream to localize
  719. * @return the localized stream
  720. * @deprecated <code>InputStreamReader</code> is the preferred way to read
  721. * local encodings
  722. * @XXX This implementation does not localize, yet.
  723. */
  724. public InputStream getLocalizedInputStream(InputStream in)
  725. {
  726. return in;
  727. }
  728. /**
  729. * Return a localized version of this OutputStream, meaning all characters
  730. * are localized before they are sent to the other end.
  731. *
  732. * @param out the stream to localize
  733. * @return the localized stream
  734. * @deprecated <code>OutputStreamWriter</code> is the preferred way to write
  735. * local encodings
  736. * @XXX This implementation does not localize, yet.
  737. */
  738. public OutputStream getLocalizedOutputStream(OutputStream out)
  739. {
  740. return out;
  741. }
  742. } // class Runtime