RootShell: Use a lock object instead of sync methods

This avoids exposing the synchronization implementation details
in the class's interface.

Signed-off-by: Samuel Holland <samuel@sholland.org>
This commit is contained in:
Samuel Holland 2018-01-16 05:47:10 -06:00
parent 75aeec035c
commit d56eda2fd6

View File

@ -31,6 +31,7 @@ public class RootShell {
private final String deviceNotRootedMessage;
private final File localBinaryDir;
private final File localTemporaryDir;
private final Object lock = new Object();
private final String preamble;
private Process process;
private BufferedReader stderr;
@ -57,16 +58,18 @@ public class RootShell {
return false;
}
public synchronized boolean isRunning() {
private boolean isRunning() {
synchronized (lock) {
try {
// Throws an exception if the process hasn't finished yet.
if (process != null)
process.exitValue();
return false;
} catch (final IllegalThreadStateException ignored) {
// The existing process is still running.
return true;
}
return false;
}
}
/**
@ -77,8 +80,10 @@ public class RootShell {
* @param command Command to run as root.
* @return The exit value of the command.
*/
public synchronized int run(final Collection<String> output, final String command)
public int run(final Collection<String> output, final String command)
throws IOException, NoRootException {
synchronized (lock) {
/* Start inside synchronized block to prevent a concurrent call to stop(). */
start();
final String marker = UUID.randomUUID().toString();
final String script = "echo " + marker + "; echo " + marker + " >&2; (" + command +
@ -121,16 +126,18 @@ public class RootShell {
Log.v(TAG, "exit: " + errnoStdout);
return errnoStdout;
}
}
public synchronized void start() throws IOException, NoRootException {
public void start() throws IOException, NoRootException {
if (!isExecutableInPath(SU))
throw new NoRootException(deviceNotRootedMessage);
synchronized (lock) {
if (isRunning())
return;
if (!localBinaryDir.isDirectory() && !localBinaryDir.mkdirs())
throw new FileNotFoundException("Could not create local binary directory");
if (!localTemporaryDir.isDirectory() && !localTemporaryDir.mkdirs())
throw new FileNotFoundException("Could not create local temporary directory");
if (!isExecutableInPath(SU))
throw new NoRootException(deviceNotRootedMessage);
try {
final ProcessBuilder builder = new ProcessBuilder().command(SU);
builder.environment().put("LC_ALL", "C");
@ -167,13 +174,16 @@ public class RootShell {
throw e;
}
}
}
public synchronized void stop() throws IOException {
public void stop() {
synchronized (lock) {
if (process != null) {
process.destroy();
process = null;
}
}
}
public static class NoRootException extends Exception {
public NoRootException(final String message, final Throwable cause) {