Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent System/exit in code I don't have access to

Tags:

clojure

I'm playing with someone else's code by examining it in the repl.

It keeps calling System/exit, which brings down my repl. This is infuriating.

In all the code I have access to, I've mocked the calls out.

But it's also calling some library code I don't have the source to, both java and clojure, and this occasionally causes exits too.

Is there any way to catch these calls globally, so that an attempt to call them doesn't kill the repl thread? Ideally it would just throw an exception instead.

I think in java I could install a new SecurityManager to get this effect, but I've never done it

there seems to be something in that line here: http://jroller.com/ethdsy/entry/disabling_system_exit

So I'm thinking something like:

(System/setSecurityManager (SecurityManager.))

only I somehow need to attach

  public void checkPermission( Permission permission ) {
    if( "exitVM".equals( permission.getName() ) ) {
      throw new ExitTrappedException() ;
    }
  }

My best shot so far is:

(System/setSecurityManager
 (proxy [SecurityManager] []
   (checkPermission [p]
                    (when (= "exitVM" (.getName p))
                      (throw (Exception. "exit"))))))

or maybe

(System/setSecurityManager 
  (proxy [SecurityManager] [] 
    (checkExit [n] false)))

But they both just destroy the repl

Or is there a better way of doing this?

like image 590
John Lawrence Aspden Avatar asked Feb 11 '11 19:02

John Lawrence Aspden


People also ask

How do I stop system exit?

This can be controlled using the checkExit function call in SecurityManager. According to the reference for SecurityManager checkExit: This method is invoked for the current security manager by the exit method of class Runtime . A status of 0 indicates success; other values indicate various errors.

What can I use instead of system exit in Java?

The main alternative is Runtime. getRuntime(). halt(0) , described as "Forcibly terminates the currently running Java virtual machine". This does not call shutdown hooks or exit finalizers, it just exits.

What does the system exit () do?

System. exit() method. This method terminates the currently running Java Virtual Machine(JVM). It takes an argument “status code” where a non zero status code indicates abnormal termination.

What is the significance of system Exit 0?

exit(0) : Generally used to indicate successful termination. exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful termination. Note : This method does not return any value.


2 Answers

Use AspectJ and intercept all Calls to System.exit() with a no op.

But you are right, just configuring the security manager would be saner.

like image 189
Daniel Avatar answered Oct 07 '22 23:10

Daniel


You can also use clj-sandbox to restrict code you don't trust.

like image 31
aav Avatar answered Oct 07 '22 22:10

aav