From d909cc69038cc328cc99d1d168b50c3dabf33628 Mon Sep 17 00:00:00 2001 From: Mygod Date: Sun, 28 Jun 2020 02:13:13 +0800 Subject: [PATCH] Init RootJava launch string asynchronously --- .../be/mygod/librootkotlinx/RootServer.kt | 46 +++++++++++-------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/mobile/src/main/java/be/mygod/librootkotlinx/RootServer.kt b/mobile/src/main/java/be/mygod/librootkotlinx/RootServer.kt index 3e79e22e..23508b7e 100644 --- a/mobile/src/main/java/be/mygod/librootkotlinx/RootServer.kt +++ b/mobile/src/main/java/be/mygod/librootkotlinx/RootServer.kt @@ -120,27 +120,33 @@ class RootServer @JvmOverloads constructor(private val warnLogger: (String) -> U warnLogger(line) } } - private fun doInit(context: Context, niceName: String) { - val writer: DataOutputStream - val reader: BufferedReader - try { - process = ProcessBuilder("su").start() - val token1 = UUID.randomUUID().toString() - writer = DataOutputStream(process.outputStream.buffered()) - writer.writeBytes("echo $token1\n") - writer.flush() - reader = process.inputStream.bufferedReader() - reader.lookForToken(token1) - } catch (e: Exception) { - throw NoShellException(e) + private suspend fun doInit(context: Context, niceName: String) = coroutineScope { + @Suppress("BlockingMethodInNonBlockingContext") + val init = async { + try { + process = ProcessBuilder("su").start() + val token1 = UUID.randomUUID().toString() + val writer = DataOutputStream(process.outputStream.buffered()) + writer.writeBytes("echo $token1\n") + writer.flush() + val reader = process.inputStream.bufferedReader() + reader.lookForToken(token1) + if (DEBUG) Log.d(TAG, "Root shell initialized") + reader to writer + } catch (e: Exception) { + throw NoShellException(e) + } } - if (DEBUG) Log.d(TAG, "Root shell initialized") - - val appProcess = AppProcess.getAppProcess() val token2 = UUID.randomUUID().toString() - writer.writeBytes(RootJava.getLaunchString(context.packageCodePath + " exec", // hack: plugging in exec - RootServer::class.java.name, appProcess, AppProcess.guessIfAppProcessIs64Bits(appProcess), - arrayOf("$token2\n"), niceName)) + val launchString = async(Dispatchers.IO) { + val appProcess = AppProcess.getAppProcess() + RootJava.getLaunchString(context.packageCodePath + " exec", // hack: plugging in exec + RootServer::class.java.name, appProcess, AppProcess.guessIfAppProcessIs64Bits(appProcess), + arrayOf("$token2\n"), niceName) + } + val list = awaitAll(init, launchString) + val (reader, writer) = list[0] as Pair + writer.writeBytes(list[1] as String) writer.flush() reader.lookForToken(token2) // wait for ready signal output = writer @@ -176,7 +182,7 @@ class RootServer @JvmOverloads constructor(private val warnLogger: (String) -> U val future = CompletableDeferred() worker = Thread { try { - doInit(context, niceName) + runBlocking { doInit(context, niceName) } future.complete(Unit) } catch (e: Throwable) { future.completeExceptionally(e)