Skip to content

Commit

Permalink
Code Cleaning
Browse files Browse the repository at this point in the history
  • Loading branch information
BryanGIG committed Apr 8, 2023
1 parent 0b89179 commit 7d41e07
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 78 deletions.
62 changes: 24 additions & 38 deletions app/src/main/java/com/dumper/android/dumper/Dumper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,21 @@ package com.dumper.android.dumper

import android.content.Context
import android.os.Environment
import com.anggrayudi.storage.extension.closeStreamQuietly
import com.dumper.android.dumper.process.Process
import com.dumper.android.utils.DEFAULT_DIR
import com.dumper.android.utils.copyToFile
import com.dumper.android.utils.removeNullChar
import com.dumper.android.utils.toHex
import com.topjohnwu.superuser.Shell
import java.io.File
import java.io.FileNotFoundException
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.channels.FileChannel

class Dumper(private val pkg: String) {
private val mem = Memory(pkg)
var file: String = ""

private fun dumpFileRoot(autoFix: Boolean, fixerPath: String) : StringBuilder {
private fun dumpFileRoot(autoFix: Boolean, fixerPath: String): StringBuilder {
if (Shell.isAppGrantedRoot() == false)
throw IllegalAccessException("The method need to be executed from root services")

Expand All @@ -28,25 +26,25 @@ class Dumper(private val pkg: String) {
if (!outputDir.exists())
outputDir.mkdirs()

val outputFile = File("${outputDir.absolutePath}/${mem.sAddress.toHex()}-${mem.eAddress.toHex()}-$file")
val outputFile =
File("${outputDir.absolutePath}/${mem.sAddress.toHex()}-${mem.eAddress.toHex()}-$file")
if (!outputDir.exists())
outputFile.createNewFile()

val inputChannel = RandomAccessFile("/proc/${mem.pid}/mem", "r").channel

val archELF = Fixer.getArchELF(inputChannel, mem)

writeChannelIntoFile(inputChannel, outputFile)
inputChannel.copyToFile(mem.sAddress, mem.size, outputFile)

if (autoFix) {
val archELF = Fixer.getArchELF(inputChannel, mem)
log.appendLine(fixDumpFile(fixerPath, archELF, outputFile))
}

log.appendLine("Output: ${outputFile.parent}")
return log
}

private fun dumpFileNonRoot(ctx: Context, autoFix: Boolean, fixerPath: String) : StringBuilder {
private fun dumpFileNonRoot(ctx: Context, autoFix: Boolean, fixerPath: String): StringBuilder {
val log = StringBuilder()

val outputDir = File(ctx.filesDir, "temp")
Expand All @@ -59,15 +57,18 @@ class Dumper(private val pkg: String) {

val inputChannel = RandomAccessFile("/proc/${mem.pid}/mem", "r").channel

val archELF = Fixer.getArchELF(inputChannel, mem)

writeChannelIntoFile(inputChannel, outputFile)
inputChannel.copyToFile(mem.sAddress, mem.size, outputFile)

if (autoFix) {
val archELF = Fixer.getArchELF(inputChannel, mem)
log.appendLine(fixDumpFile(fixerPath, archELF, outputFile))
}

val fileOutPath = listOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), DEFAULT_DIR, pkg.removeNullChar())
val fileOutPath = listOf(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
DEFAULT_DIR,
pkg.removeNullChar()
)
val fileOutputDir = File(fileOutPath.joinToString(File.separator))
if (!fileOutputDir.exists())
fileOutputDir.mkdirs()
Expand All @@ -81,9 +82,9 @@ class Dumper(private val pkg: String) {
return log
}

private fun fixDumpFile(fixerPath: String, archELF: Arch, outputFile: File) : String {
private fun fixDumpFile(fixerPath: String, archELF: Arch, outputFile: File): String {
if (archELF == Arch.UNKNOWN)
return "";
return ""

val log = StringBuilder()
log.appendLine("Fixing...")
Expand All @@ -110,7 +111,8 @@ class Dumper(private val pkg: String) {
*
* @param ctx pass null if using root, vice versa
* @param autoFix if `true` the dumped file will be fixed after dumping
* @param flagCheck if `true` the dumped file will be checked for flags/
* @param fixerPath ELFixer path
* @param flagCheck check for flags r-xp in file
* @return log of the dump
*/
fun dumpFile(ctx: Context?, autoFix: Boolean, fixerPath: String, flagCheck: Boolean): String {
Expand Down Expand Up @@ -146,7 +148,7 @@ class Dumper(private val pkg: String) {

if (ctx == null)
log.appendLine(dumpFileRoot(autoFix, fixerPath))
else
else
log.appendLine(dumpFileNonRoot(ctx, autoFix, fixerPath))

log.appendLine("Dump Success")
Expand All @@ -158,33 +160,17 @@ class Dumper(private val pkg: String) {
return log.toString()
}

private fun writeChannelIntoFile(inputChannel: FileChannel, file: File) {

val outputStream = file.outputStream()

var bytesWritten = 0
val buffer = ByteBuffer.allocate(1024)
while (bytesWritten < mem.size) {
val bytesReaded = inputChannel.read(buffer, mem.sAddress + bytesWritten)
outputStream.write(buffer.array(), 0, bytesReaded)
buffer.clear()
bytesWritten += bytesReaded
}

outputStream.flush()
outputStream.closeStreamQuietly()
inputChannel.close()
}

/**
* Parsing the memory map
*
* @throws FileNotFoundException if required file is not found in memory map
* @throws FileNotFoundException failed to open /proc/{pid}/maps
* @throws RuntimeException start or end address is not found
*/
private fun parseMap(checkFlag: Boolean): Pair<Long, Long> {
val files = File("/proc/${mem.pid}/maps")
if (!files.exists()) {
throw Exception("Failed To Open : ${files.path}")
throw FileNotFoundException("Failed To Open : ${files.path}")
}
val lines = files.readLines()

Expand All @@ -199,14 +185,14 @@ class Dumper(private val pkg: String) {
} else {
map.getPath().contains(file)
}
} ?: throw Exception("Unable find baseAddress of $file")
} ?: throw RuntimeException("Unable find baseAddress of $file")

val mapStart = MapLinux(lineStart)

val lineEnd = lines.findLast {
val map = MapLinux(it)
mapStart.getInode() == map.getInode()
} ?: throw Exception("Unable find endAddress of $file")
} ?: throw RuntimeException("Unable find endAddress of $file")

val mapEnd = MapLinux(lineEnd)
return Pair(mapStart.getStartAddress(), mapEnd.getEndAddress())
Expand Down
67 changes: 36 additions & 31 deletions app/src/main/java/com/dumper/android/dumper/process/Process.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,27 +28,30 @@ object Process {
)
finalAppsBundle.add(data)
}
} catch (_: Exception) { }
} catch (_: Exception) {
}
}
} else {
val proc = File("/proc")
if (proc.exists()) {
val dPID = proc.listFiles()
if (!dPID.isNullOrEmpty()) {
for (line in dPID) {
if (line.name.isDigitsOnly()) {
val comm = File("${line.path}/comm")
val cmdline = File("${line.path}/cmdline")
if (comm.exists() && cmdline.exists()) {
if (!proc.exists())
return finalAppsBundle

val dPID = proc.listFiles()
if (dPID.isNullOrEmpty())
return finalAppsBundle

for (line in dPID) {
if (line.name.isDigitsOnly()) {
val comm = File("${line.path}/comm")
val cmdline = File("${line.path}/cmdline")
if (comm.exists() && cmdline.exists()) {

val processName = comm.readText(Charsets.UTF_8)
val processPkg = cmdline.readText(Charsets.UTF_8)
val processName = comm.readText(Charsets.UTF_8)
val processPkg = cmdline.readText(Charsets.UTF_8)

if (processPkg != "sh" && !processPkg.contains(BuildConfig.APPLICATION_ID)) {
val data = ProcessData(processPkg, processName)
finalAppsBundle.add(data)
}
}
if (processPkg != "sh" && !processPkg.contains(BuildConfig.APPLICATION_ID)) {
val data = ProcessData(processPkg, processName)
finalAppsBundle.add(data)
}
}
}
Expand All @@ -63,24 +66,26 @@ object Process {
*/
fun getProcessID(pkg: String): Int? {
val proc = File("/proc")
if (proc.exists()) {
val dPID = proc.listFiles()
if (!dPID.isNullOrEmpty()) {
dPID.firstOrNull {
if (it.name.isDigitsOnly()) {
val cmdline = File("${it.path}/cmdline")
if (cmdline.exists()) {
val textCmd = cmdline.readText(Charsets.UTF_8)
if (textCmd.contains(pkg)) {
return@firstOrNull true
}
}
if (!proc.exists())
return null

val dPID = proc.listFiles()
if (dPID.isNullOrEmpty())
return null

dPID.find {
if (it.name.isDigitsOnly()) {
val cmdline = File("${it.path}/cmdline")
if (cmdline.exists()) {
val textCmd = cmdline.readText(Charsets.UTF_8)
if (textCmd.contains(pkg)) {
return@find true
}
return@firstOrNull false
}?.let {
return it.name.toInt()
}
}
return@find false
}?.let {
return it.name.toInt()
}
return null
}
Expand Down
23 changes: 23 additions & 0 deletions app/src/main/java/com/dumper/android/utils/IOUtils.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.dumper.android.utils

import com.anggrayudi.storage.extension.closeStreamQuietly
import java.io.File
import java.nio.ByteBuffer
import java.nio.channels.FileChannel

fun FileChannel.copyToFile(startPos: Long, byteSize: Long, outputFile: File) {
val outputStream = outputFile.outputStream()

var bytesWritten = 0
val buffer = ByteBuffer.allocate(1024)
while (bytesWritten < byteSize) {
val bytesRead = read(buffer, startPos + bytesWritten)
outputStream.write(buffer.array(), 0, bytesRead)
buffer.clear()
bytesWritten += bytesRead
}

outputStream.flush()
outputStream.closeStreamQuietly()
close()
}
11 changes: 2 additions & 9 deletions app/src/main/java/com/dumper/android/utils/Utils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,10 @@ fun Long.toHex(): String {
return this.toString(16)
}

fun Long.toMB(): Long {
return this * 1024 * 1024
}

@Suppress("DEPRECATION")
inline fun <reified T : Parcelable> Bundle.getParcelableArrayListCompact(key: String): ArrayList<T>? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
getParcelableArrayList(
key,
T::class.java
)
getParcelableArrayList(key, T::class.java)
} else {
getParcelableArrayList(key)
}
Expand All @@ -42,4 +35,4 @@ fun ApplicationInfo.isInvalid() =
(flags and ApplicationInfo.FLAG_STOPPED != 0) || (flags and ApplicationInfo.FLAG_SYSTEM != 0)


fun String.removeNullChar() : String = replace("\u0000", "")
fun String.removeNullChar(): String = replace("\u0000", "")

0 comments on commit 7d41e07

Please sign in to comment.