import org.apache.commons.configuration2.plist.XMLPropertyListConfiguration;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class RenameExecutor {
private final String configPath, binaryPath;
private final List<Triple<String, byte[], byte[]>> patches;
public RenameExecutor(String configPath, String binaryPath) {
this.binaryPath = binaryPath;
this.configPath = configPath;
this.patches = new ArrayList<>();
readPatchMap();
patchFile();
}
private void patchFile() {
try {
FileInputStream fis = new FileInputStream(new File(this.binaryPath));
byte[] bytes = fis.readAllBytes();
fis.close();
for(Triple<String, byte[], byte[]> patch : patches)
replaceBytes(bytes, patch.getMiddle(), patch.getRight(), patch.getLeft());
FileOutputStream fos = new FileOutputStream(this.binaryPath);
fos.write(bytes);
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void replaceBytes(byte[] bytes, byte[] search, byte[] replace, String comment) {
if(search.length != replace.length)
throw new IllegalStateException("Search and replace array must be the same size!");
System.out.print("* Replacing <" + new String(search) + "> to <" + new String(replace) + ">, ");
int c = 0;
for(int i = 0; i < bytes.length - search.length + 1; i++) {
boolean match = true;
for(int j = 0; j < search.length; j++) {
byte curr = bytes[i + j];
if(curr != search[j]) {
match = false;
break;
}
}
if(!match)
continue;
System.arraycopy(replace, 0, bytes, i, search.length);
c++;
}
System.out.println(c + " occurrances, (" + comment + ")");
}
private void readPatchMap() {
try {
XMLPropertyListConfiguration plist = new XMLPropertyListConfiguration();
FileReader fr = new FileReader(new File(configPath));
plist.read(fr);
fr.close();
XMLPropertyListConfiguration[] arr = (XMLPropertyListConfiguration[]) plist.getArray(XMLPropertyListConfiguration.class, "ACPI.Patch");
for(XMLPropertyListConfiguration a : arr) {
if(!a.getBoolean("Enabled"))
continue;
byte[] find = (byte[]) a.getProperty("Find");
byte[] replace = (byte[]) a.getProperty("Replace");
patches.add(Triple.of(a.getString("Comment"), find, replace));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}