...
Code Block |
---|
|
public class InterceptExit {
public static void main(String[] args) {
System// ..out.println("Regular code block");
System.exit(1); //abrupt Abrupt exit call
System.out.println("This is never executed");
}
}
|
Compliant Solution
The This compliant solution installs a custom security manager PasswordSecurityManager
that overrides the checkExistcheckExit()
method defined in the SecurityManager
class. An internal flag is used to keep track of whether the exit is permitted or not. The method setExitAllowed()
is used to set this flag to true. If the flag is not set (false
), a SecurityException
is thrown. The System.exit()
call is not allowed to execute by catching the SecurityException
in a try-catch
block. After intercepting and performing mandatory clean-up operations, the setExitAllowed()
method is invoked. As a result, the program exits gracefully.
Code Block |
---|
|
class PasswordSecurityManager extends SecurityManager{
private boolean isExitAllowedFlag;
public PasswordSecurityManager(){
super();
isExitAllowedFlag = false;
}
public boolean isExitAllowed(){
return isExitAllowedFlag;
}
@Override public void checkExit(int status) {
if(!isExitAllowed())
throw new SecurityException();
}
public void setExitAllowed(boolean f) {
isExitAllowedFlag = f;
}
}
public class InterceptExit {
public static void main(String[] args) {
PasswordSecurityManager secManager = new PasswordSecurityManager();
System.setSecurityManager(secManager);
try {
// System..out.println("Regular code block");
System.exit(1); //abrupt Abrupt exit call
}
catch (Throwable x) {
if (x instanceof SecurityException) {
System.out.println("Intercepted System.exit()");
} else {
x.printStackTrace();// Forward to exception handler
}
}
System.out.println("Executing code block// ...");
secManager.setExitAllowed(true); //permit Permit exit
// System.out.println("Finished block, exiting...");exit() will work subsequently
//exit finally ...
}
}
|
Noncompliant Code Example
...
Code Block |
---|
|
public class InterceptExit {
public static void main(String[] args) {
System.out.println("Regular code block");
//abrupt Abrupt exit such as ctrl + c key pressed
System.out.println("This is never executedexecutes");
}
}
|
Compliant Solution
...
- Hook threads should be light-weight and simple
- They should be thread safe
- They should hold locks when accessing data
Wiki Markup |
---|
They should not rely on system services as theythe services themselves may be shutting down (for example, the logger may shutdown from another hook). Instead of one service it may be better to run a series of shutdown tasks from one thread by using a single shutdown hook. \[[Goetz 06|AA. Java References#Goetz 06]\] |
...
Wiki Markup |
---|
*EX1:* It is permissible for a command line utility to call {{System.exit()}} or terminate prematurely, for example, when the required number of arguments are not input. \[[Bloch 08|AA. Java References#Bloch 08]\] and \[[ESA 05|AA. Java References#ESA 05]\] |
...