file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
PropertiesFile.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/PropertiesFile.java | package org.flashtool.system;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import org.flashtool.gui.models.TableLine;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PropertiesFile {
String rname;
String fname;
Properties props;
public PropertiesFile() {
props=new Properties();
}
public void setProperties(Properties p) {
props=p;
}
public void mergeWith(PropertiesFile pf) {
Iterator i = pf.keySet().iterator();
while (i.hasNext()) {
String key = (String)i.next();
props.setProperty(key, pf.getProperty(key));
}
}
public void open(String arname, String afname) {
rname = arname;
fname = afname;
try {
props = new Properties();
Reader in = new InputStreamReader(new FileInputStream(fname), "UTF-8");
props.load(in);
}
catch (Exception e) {
try {
props = new Properties();
if (rname.length()>0) {
Reader in = new InputStreamReader(PropertiesFile.class.getClassLoader().getResourceAsStream(rname), "UTF-8");
props.load(in);
}
}
catch (Exception e1) {
}
}
}
public PropertiesFile(String arname, String afname) {
open(arname, afname);
}
public String getProperty(String key) {
return props.getProperty(key);
}
public Set<Object> keySet() {
return props.keySet();
}
public void setProperty(String key, String value) {
props.setProperty(key, value);
}
public void write(String filename,String encoding) {
try {
new File(filename).getParentFile().mkdirs();
Writer out = new OutputStreamWriter(new FileOutputStream(filename), encoding);
props.store(out, null);
out.flush();
out.close();
}
catch (Exception e) {
}
}
public void setFileName(String filename) {
fname = filename;
}
public void write(String encoding) {
write(fname,encoding);
}
public Properties getProperties() {
return props;
}
public void load(InputStream is) throws Exception {
props.load(is);
}
public void remove(String key) {
props.remove(key);
}
public Object[] toArray() {
Vector<TableLine> v = new Vector<TableLine>();
Enumeration<Object> e = props.keys();
while (e.hasMoreElements()) {
String key = (String)e.nextElement();
TableLine l = new TableLine();
l.add(key);
l.add(props.getProperty(key));
v.add(l);
}
return v.toArray();
}
} | 2,731 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
AWTKillerThread.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/AWTKillerThread.java | package org.flashtool.system;
import java.util.Iterator;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class AWTKillerThread extends Thread {
boolean done = false;
public void done() {
done=true;
}
public void run() {
if (OS.getName().equals("mac")) {
this.setName("KillerAWT");
while (!done) {
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
Iterator<Thread> i = threadSet.iterator();
while (i.hasNext()) {
Thread t = i.next();
if (t.getName().startsWith("AWT")) {
t.interrupt();
}
}
Sleep(10);
}
}
}
private void Sleep(int ms) {
try {
sleep(ms);
}
catch (Exception e) {}
}
public void doSleep(int time) {
try {
sleep(time);
}
catch (Exception e) {}
}
} | 802 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
FTDEntry.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/FTDEntry.java | package org.flashtool.system;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.eclipse.swt.SWT;
import org.flashtool.gui.tools.MsgBox;
import org.flashtool.jna.adb.AdbUtility;
import org.flashtool.util.BytesUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FTDEntry {
File ftdfile;
Properties entry = new Properties();
public FTDEntry(String id) throws FileNotFoundException, IOException {
ftdfile = new File(OS.getFolderMyDevices()+File.separator+id+".ftd");
if (!ftdfile.exists()) throw new FileNotFoundException();
JarFile jar = new JarFile(ftdfile);
Enumeration<JarEntry> e = jar.entries();
while (e.hasMoreElements()) {
JarEntry j = e.nextElement();
if (j.getName().contains(id.toUpperCase()+".properties"))
entry.load(jar.getInputStream(j));
}
jar.close();
}
public String getId() {
return entry.getProperty("internalname");
}
public String getName() {
return entry.getProperty("realname");
}
public boolean explode() throws Exception {
String destDir = OS.getFolderMyDevices();
int reply = SWT.YES;
if (new File(destDir).exists())
reply = MsgBox.question("This device already exists. Overwrite it ?");
if (reply == SWT.YES) {
new File(destDir+File.separator+getId()).mkdir();
JarFile jar = new JarFile(ftdfile);
boolean alldirs=false;
Enumeration<JarEntry> e;
while (!alldirs) {
e = jar.entries();
alldirs=true;
while (e.hasMoreElements()) {
JarEntry file = e.nextElement();
File f = new File(destDir + File.separator + file.getName());
if (file.isDirectory()) { // if its a directory, create it
if (!f.exists())
if (!f.mkdir()) alldirs=false;
}
}
}
e = jar.entries();
while (e.hasMoreElements()) {
JarEntry file = (JarEntry) e.nextElement();
File f = new File(destDir + File.separator + file.getName());
if (!file.isDirectory()) { // if its a directory, create it
InputStream is = jar.getInputStream(file); // get the input stream
FileOutputStream fos = new FileOutputStream(f);
byte[] array = new byte[10240];
while (is.available() > 0) { // write contents of 'is' to 'fos'
int read = is.read(array);
fos.write((read<array.length)?BytesUtil.getReply(array, read):array);
}
fos.close();
is.close();
}
}
jar.close();
return true;
}
else {
log.info("Import canceled");
return false;
}
}
} | 2,877 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
RunOutputs.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/RunOutputs.java | package org.flashtool.system;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class RunOutputs {
String stdout;
String stderr;
public RunOutputs(String out, String err) {
stdout = out;
stderr = err;
}
public String getStdOut() {
return stdout;
}
public String getStdErr() {
return stderr;
}
}
| 317 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
Proxy.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/Proxy.java | package org.flashtool.system;
import java.net.ProxySelector;
import com.github.markusbernhardt.proxy.ProxySearch;
import com.github.markusbernhardt.proxy.ProxySearch.Strategy;
import com.github.markusbernhardt.proxy.util.PlatformUtil;
import com.github.markusbernhardt.proxy.util.PlatformUtil.Platform;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Proxy {
private static ProxySelector dps = null;
public static void setProxy() {
if (dps==null) dps=ProxySelector.getDefault();
log.info("Searching for a web proxy");
ProxySearch proxySearch = new ProxySearch();
if (PlatformUtil.getCurrentPlattform() == Platform.WIN) {
proxySearch.addStrategy(Strategy.IE);
proxySearch.addStrategy(Strategy.FIREFOX);
proxySearch.addStrategy(Strategy.JAVA);
} else
if (PlatformUtil.getCurrentPlattform() == Platform.LINUX) {
proxySearch.addStrategy(Strategy.GNOME);
proxySearch.addStrategy(Strategy.KDE);
proxySearch.addStrategy(Strategy.FIREFOX);
} else {
proxySearch.addStrategy(Strategy.OS_DEFAULT);
}
ProxySelector ps = proxySearch.getProxySelector();
if (ps!=null) {
log.info("A proxy has been found. Using it as default");
ProxySelector.setDefault(ps);
}
else {
log.info("No proxy found, using direct connection");
}
}
public static boolean canResolve(String uri) {
DNSResolver tr = new DNSResolver("github.com");
try {
tr.start();
tr.join(2000);
tr.interrupt();
return tr.get()!=null;
} catch (InterruptedException e) {
return tr.get()!=null;
}
}
}
| 1,555 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
ClassPath.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/ClassPath.java | package org.flashtool.system;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Vector;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ClassPath {
private static final Class<?>[] parameters = new Class<?>[] { URL.class };
private static final Vector<URL> added = new Vector<URL>();
public static void addFile(String s) throws IOException {
File f = new File(s);
addFile(f);
}
public static void addFile(File f) throws IOException {
addURL(f.toURI().toURL());
}
public static void addURL(URL u) throws IOException {
if (added.contains(u)) return;
added.add(u);
URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class<?> sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysloader, new Object[] { u });
} catch (Throwable t) {
throw new IOException("Error, could not add URL to system classloader");
}
}
} | 1,085 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
ULCodeFile.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/ULCodeFile.java | package org.flashtool.system;
import java.io.File;
import org.flashtool.jna.adb.AdbUtility;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ULCodeFile extends TextFile {
public ULCodeFile(String serial) {
super(OS.getFolderRegisteredDevices()+File.separator+serial+File.separator+"ulcode.txt", "ISO-8859-1");
}
public String getULCode() {
try {
readLines();
return (String)getLines().iterator().next();
}
catch (Exception e) {
return "";
}
}
public void setCode(String code) {
try {
open(true);
write(code);
close();
log.info("Unlock code saved to "+new File(fFileName).getAbsolutePath());
}
catch (Exception e) {
log.error("Error saving unlock code : " + e.getMessage());
}
}
} | 742 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
CommentedPropertiesFile.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/CommentedPropertiesFile.java | package org.flashtool.system;
import java.io.*;
import java.util.*;
import lombok.extern.slf4j.Slf4j;
@Slf4j
/**
* The CommentedProperties class is an extension of java.util.Properties
* to allow retention of comment lines and blank (whitespace only) lines
* in the properties file.
*
*/
public class CommentedPropertiesFile extends java.util.Properties {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Use a Vector to keep a copy of lines that are a comment or 'blank'
*/
private LinkedList<String> lines = new LinkedList<String>();
private Properties commented = new Properties();
/**
* Load properties from the specified InputStream.
* Overload the load method in Properties so we can keep comment and blank lines.
* @param inStream The InputStream to read.
*/
public void load(File f) throws IOException
{
FileInputStream fin = new FileInputStream(f);
load(fin);
fin.close();
FileReader fread = new FileReader(f);
Scanner sc = new Scanner(fread);
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.trim().startsWith("#") || line.trim().length()==0) {
if (!line.trim().startsWith("##") && line.trim().contains("=")) {
setCommentedProperty(line.trim().split("=")[0].substring(1).trim(),line.trim().split("=")[1].trim());
} else {
lines.add(line);
}
}
else {
// Adding a key
lines.add(line.trim().split("=")[0].trim());
}
}
fread.close();
}
/**
* Write the properties to the specified OutputStream.
*
* Overloads the store method in Properties so we can put back comment
* and blank lines.
*
* @param out The OutputStream to write to.
* @param header Ignored, here for compatability w/ Properties.
*
* @exception IOException
*/
public void store(OutputStream out, String header) throws IOException
{
// The spec says that the file must be encoded using ISO-8859-1.
PrintWriter writer
= new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1"));
// We ignore the header, because if we prepend a commented header
// then read it back in it is now a comment, which will be saved
// and then when we write again we would prepend Another header...
Iterator<String> i = lines.iterator();
while (i.hasNext()) {
String line = i.next();
if (containsKey(line))
writer.println(line+"="+getProperty(line));
else if (commented.containsKey(line)) writer.println("#"+line.substring(2)+"="+commented.getProperty(line));
else writer.println(line);
}
writer.flush ();
writer.close();
out.flush();
out.close();
}
public void updateWith(File f) throws IOException {
CommentedPropertiesFile p = new CommentedPropertiesFile();
p.load(f);
Iterator<Object> i = p.keySet().iterator();
while (i.hasNext()) {
String key = (String)i.next();
unComment(key);
setProperty(key,p.getProperty(key));
}
Iterator<Object> i1 = p.commentedKeySet().iterator();
while (i1.hasNext()) {
String key = ((String)i1.next()).substring(2);
comment(key);
setCommentedProperty(key,p.getCommentedProperty(key));
}
}
public String getCommentedProperty(String key) {
return commented.getProperty("_c"+key);
}
public Set commentedKeySet() {
return commented.keySet();
}
public void updateProperty(String key, String value) {
if (isCommented(key) && !isNotCommented(key)) unComment(key);
setProperty(key,value);
}
public void updateCommentedProperty(String key, String value) {
if (isNotCommented(key) && !isCommented(key)) comment(key);
setCommentedProperty(key,value);
}
public void setCommentedProperty(String key, String value) {
commented.setProperty("_c"+key, value);
if (lines.indexOf("_c"+key)<0) lines.add("_c"+key);
}
public Object setProperty(String key, String value) {
if (lines.indexOf(key)<0) lines.add(key);
return super.setProperty(key,value);
}
public boolean isCommented(String key) {
return commented.containsKey("_c"+key);
}
public boolean isNotCommented(String key) {
return containsKey(key);
}
public void removeCommented(String key) {
commented.remove("_c"+key);
}
public void remove(String key) {
super.remove(key);
}
public void unComment(String key) {
if (getCommentedProperty(key)!=null) {
setProperty(key, getCommentedProperty(key));
removeCommented(key);
int index = lines.indexOf("_c"+key);
lines.set(index, key);
}
}
public void comment(String key) {
if (getProperty(key)!=null) {
commented.setProperty("_c"+key, getProperty(key));
remove(key);
int index = lines.indexOf(key);
lines.set(index, "_c"+key);
}
}
/**
* Add a comment or blank line or comment to the end of the CommentedProperties.
*
* @param line The string to add to the end, make sure this is a comment
* or a 'whitespace' line.
*/
public void addComment(String line) {
lines.add(line);
}
} | 5,654 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
Devices.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/Devices.java | package org.flashtool.system;
import java.io.File;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.flashtool.jna.adb.AdbUtility;
import org.flashtool.jna.adb.FastbootUtility;
import org.flashtool.jna.linux.JUsb;
import org.flashtool.jna.win32.JsetupAPi;
import org.flashtool.jna.win32.SetupApi.HDEVINFO;
import org.flashtool.jna.win32.SetupApi.SP_DRVINFO_DATA;
import org.flashtool.util.BytesUtil;
import org.flashtool.util.HexDump;
//import org.eclipse.swt.SWT;
//import org.eclipse.swt.widgets.Shell;
import java.util.Enumeration;
import com.sun.jna.platform.win32.WinBase;
import com.google.common.primitives.Longs;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.SetupApi.SP_DEVINFO_DATA;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Devices {
private static DeviceEntry _current=null;;
public static Properties devices = null;
public static Properties models = null;
private static boolean waitforreboot=false;
private static final String DriversInfoData = null;
static DeviceIdent lastid = new DeviceIdent();
static String laststatus = "";
public static boolean HasOneAdbConnected() {
return AdbUtility.isConnected();
}
public static boolean HasOneFastbootConnected() {
return FastbootUtility.getDevices().hasMoreElements();
}
public static Enumeration<Object> listDevices(boolean reload) {
if (reload || devices==null) load();
return devices.keys();
}
public static DeviceEntry getDevice(String device) {
try {
if (device==null) return null;
if (devices.containsKey(device))
return (DeviceEntry)devices.get(device);
else {
File f = new File(OS.getFolderMyDevices()+File.separator+device+".ftd");
if (f.exists()) {
DeviceEntry ent=null;
JarFile jar = new JarFile(f);
Enumeration e = jar.entries();
while (e.hasMoreElements()) {
JarEntry file = (JarEntry) e.nextElement();
if (file.getName().endsWith(device+".properties")) {
InputStream is = jar.getInputStream(file); // get the input stream
PropertiesFile p = new PropertiesFile();
p.load(is);
ent = new DeviceEntry(p);
}
}
return ent;
}
else return null;
}
}
catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static void setCurrent(String device) {
AdbUtility.init();
_current = (DeviceEntry)devices.get(device);
_current.queryAll();
}
public static DeviceEntry getCurrent() {
return _current;
}
public static void load() {
log.info("Loading devices database");
if (devices==null) {
devices=new Properties();
models = new Properties();
}
else {
devices.clear();
models.clear();
}
File[] list = (new File(OS.getFolderMyDevices()).listFiles());
if (list==null) return;
for (int i=0;i<list.length;i++) {
if (list[i].isDirectory()) {
PropertiesFile p = new PropertiesFile();
String device = list[i].getPath().substring(list[i].getPath().lastIndexOf(OS.getFileSeparator())+1);
try {
File propfile = new File(list[i].getPath()+OS.getFileSeparator()+device+".properties");
if (propfile.exists()) {
p.open("",propfile.getAbsolutePath());
DeviceEntry entry = new DeviceEntry(p);
if (device.equals(entry.getId())) {
devices.put(device, entry);
Iterator<String> iv = entry.getVariantList().iterator();
while (iv.hasNext()) {
String variant = iv.next();
models.put(variant, entry);
}
}
else log.error(device + " : this bundle is not valid");
}
}
catch (Exception fne) {
log.error(device + " : this bundle is not valid");
}
}
}
list = (new File(OS.getFolderDevices()).listFiles());
if (list==null) return;
for (int i=0;i<list.length;i++) {
if (list[i].isDirectory()) {
PropertiesFile p = new PropertiesFile();
String device = list[i].getPath().substring(list[i].getPath().lastIndexOf(OS.getFileSeparator())+1);
try {
File propfile = new File(list[i].getPath()+OS.getFileSeparator()+device+".properties");
if (propfile.exists()) {
p.open("",propfile.getAbsolutePath());
DeviceEntry entry = new DeviceEntry(p);
if (device.equals(entry.getId())) {
devices.put(device, entry);
Iterator<String> iv = entry.getVariantList().iterator();
while (iv.hasNext()) {
String variant = iv.next();
models.put(variant, entry);
}
}
else log.error(device + " : this bundle is not valid");
}
}
catch (Exception fne) {
log.error(device + " : this bundle is not valid");
}
}
}
log.info("Loaded "+devices.size()+" devices");
}
public static void waitForReboot(boolean tobeforced) {
if (!tobeforced)
log.info("Waiting for device");
else
log.info("Waiting for device. After 60secs, stop waiting will be forced");
waitforreboot=true;
int count=0;
while (waitforreboot) {
sleep(20);
if (tobeforced) {
count++;
if (Devices.getLastConnected(false).getStatus().equals("adb") && count==3000) {
log.info("Forced stop waiting.");
waitforreboot=false;
}
else if (count==3000) count=0;
}
}
}
private static void sleep(int ms) {
try {
Thread.sleep(ms);
}
catch (Exception e) {}
}
public static void stopWaitForReboot() {
waitforreboot=false;
}
public static void setWaitForReboot() {
waitforreboot=true;
}
public static boolean isWaitingForReboot() {
return waitforreboot;
}
public static String identFromRecognition() {
if (devices.isEmpty()) {
log.error("No device is registered in Flashtool.");
log.error("You can only flash devices.");
return "";
}
String dev = DeviceProperties.getProperty("ro.product.device");
String model = DeviceProperties.getProperty("ro.product.model");
DeviceEntry entry = Devices.getDeviceFromVariant(dev);
if (entry != null) return entry.getId();
entry = Devices.getDeviceFromVariant(model);
if (entry != null) return entry.getId();
return "";
}
public static String getVariantName(String variant) {
try {
return getDeviceFromVariant(variant).getName() + "(" + variant + ")";
} catch (Exception e) {
return "Not found ("+variant+")";
}
}
public static DeviceEntry getDeviceFromVariant(String variant)
{
return (DeviceEntry)models.get(variant);
}
public static DeviceIdent getLastConnected(boolean force) {
if (force) return getConnectedDevice();
DeviceIdent id = null;
synchronized (lastid) {
id = new DeviceIdent(lastid);
}
return id;
}
public static synchronized DeviceIdent getConnectedDevice() {
DeviceIdent id;
if (OS.getName().equals("windows")) id=getConnectedDeviceWin32();
else id=getConnectedDeviceLinux();
int count=0;
while (!id.isDriverOk()) {
try {
Thread.sleep(200);
}
catch (Exception e) {
}
if (OS.getName().equals("windows")) id=getConnectedDeviceWin32();
else id=getConnectedDeviceLinux();
count++;
if (count==5) break;
}
return id;
}
public static byte[] longToBytes(long l) {
ArrayList<Byte> bytes = new ArrayList<Byte>();
while (l != 0) {
bytes.add((byte) (l % (0xff + 1)));
l = l >> 8;
}
byte[] bytesp = new byte[bytes.size()];
for (int i = bytes.size() - 1, j = 0; i >= 0; i--, j++) {
bytesp[j] = bytes.get(i);
}
return bytesp;
}
public static DeviceIdent getConnectedDeviceWin32() {
DeviceIdent id = new DeviceIdent();
HDEVINFO hDevInfo = JsetupAPi.getHandleForConnectedInterfaces();
if (hDevInfo.equals(WinBase.INVALID_HANDLE_VALUE)) {
log.error("Cannot have device list");
}
else {
SP_DEVINFO_DATA DeviceInfoData;
int index = 0;
do {
DeviceInfoData = JsetupAPi.enumDevInfo(hDevInfo, index);
String devid = JsetupAPi.getDevId(hDevInfo, DeviceInfoData);
if (devid.contains("VID_0FCE")) {
id.addDevPath(JsetupAPi.getDevicePath(hDevInfo, DeviceInfoData));
id.addDevId(devid);
if (!JsetupAPi.isInstalled(hDevInfo, DeviceInfoData))
id.setDriverOk(devid,false);
else
id.setDriverOk(devid,true);
}
index++;
} while (DeviceInfoData!=null);
JsetupAPi.destroyHandle(hDevInfo);
}
hDevInfo = JsetupAPi.getHandleForConnectedDevices();
if (hDevInfo.equals(WinBase.INVALID_HANDLE_VALUE)) {
log.error("Cannot have device list");
}
else {
SP_DEVINFO_DATA DeviceInfoData;
SP_DRVINFO_DATA DriversInfoData;
int index = 0;
do {
DeviceInfoData = JsetupAPi.enumDevInfo(hDevInfo, index);
String devid = JsetupAPi.getDevId(hDevInfo, DeviceInfoData);
if (devid.contains("VID_0FCE")) {
id.addDevId(devid);
if (!JsetupAPi.isInstalled(hDevInfo, DeviceInfoData))
id.setDriverOk(devid,false);
else {
id.setDriverOk(devid,true);
DriversInfoData=null;
//DriversInfoData=JsetupAPi.getDriver(hDevInfo, DeviceInfoData);
if (JsetupAPi.buildDriverList(hDevInfo, DeviceInfoData)) {
DriversInfoData=null;
int driverindex = 0;
do {
DriversInfoData = JsetupAPi.enumDriverInfo(hDevInfo, DeviceInfoData, driverindex);
if (DriversInfoData!=null) {
String desc = new String(Native.toString(DriversInfoData.Description));
int major = BytesUtil.getInt(Arrays.copyOfRange(Longs.toByteArray(DriversInfoData.DriverVersion), 0, 2));
int minor = BytesUtil.getInt(Arrays.copyOfRange(Longs.toByteArray(DriversInfoData.DriverVersion), 2, 4));
int mili = BytesUtil.getInt(Arrays.copyOfRange(Longs.toByteArray(DriversInfoData.DriverVersion), 4, 6));
int micro = BytesUtil.getInt(Arrays.copyOfRange(Longs.toByteArray(DriversInfoData.DriverVersion), 6, 8));
id.setDriver(desc, major, minor, mili, micro);
}
driverindex++;
} while (DriversInfoData!=null);
}
}
}
index++;
} while (DeviceInfoData!=null);
JsetupAPi.destroyHandle(hDevInfo);
}
synchronized (lastid) {
lastid=id;
}
return id;
}
public static DeviceIdent getConnectedDeviceLinux() {
DeviceIdent id = new DeviceIdent();
try {
JUsb.fillDevice(true);
if (JUsb.getVendorId().equals("0FCE")) {
id.addDevId(JUsb.getVendorId(),JUsb.getProductId(),JUsb.getSerial());
}
synchronized (lastid) {
lastid=id;
}
}
catch (UnsatisfiedLinkError e) {
log.error("libusb-1.0 is not installed");
log.error(e.getMessage());
}
catch (NoClassDefFoundError e1) {
}
return id;
}
public static void CheckAdbDrivers() {
log.info("List of connected devices (Device Id) :");
DeviceIdent id=getLastConnected(false);
String driverstatus;
int maxsize = id.getMaxSize();
Enumeration e = id.getIds().keys();
while (e.hasMoreElements()) {
String dev = (String)e.nextElement();
String driver = id.getIds().getProperty(dev);
log.info(" - "+String.format("%1$-" + maxsize + "s", dev)+"\tDriver installed : "+driver);
}
log.info("List of ADB devices :");
Enumeration<String> e1 = AdbUtility.getDevices();
if (e1.hasMoreElements()) {
while (e1.hasMoreElements()) {
log.info(" - "+e1.nextElement() + " (Device : " + DeviceProperties.getProperty("ro.product.device") + ". Model : "+DeviceProperties.getProperty("ro.product.model")+")");
}
}
else log.info(" - none");
log.info("List of fastboot devices :");
Enumeration<String> e2 = FastbootUtility.getDevices();
if (e2.hasMoreElements()) {
while (e2.hasMoreElements()) {
log.info(" - "+e2.nextElement());
}
}
else log.info(" - none");
}
public static void clean() {
if (!OS.getName().equals("windows"))
try {
JUsb.cleanup();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} | 12,540 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
FTShell.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/FTShell.java | package org.flashtool.system;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.commons.io.IOUtils;
import org.flashtool.jna.adb.AdbUtility;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FTShell {
File _file;
File _runfile=null;
String _name;
String content;
String fsep = OS.getFileSeparator();
public FTShell(File file) throws Exception {
init(file);
}
public void init(File file) throws Exception {
_file = file;
_name = file.getName();
FileInputStream fin = new FileInputStream(_file);
content = IOUtils.toString(fin, "ISO-8859-1");
fin.close();
setProperty("DEVICEWORKDIR",GlobalConfig.getProperty("deviceworkdir"));
setProperty("SHELLPATH",AdbUtility.getShPath(false));
}
public FTShell(String shell) throws Exception {
init(new File(AdbUtility.getShellPath()+fsep+shell));
}
public void save() throws Exception {
_runfile=new File(_file.getAbsoluteFile()+"_work");
FileOutputStream fout = new FileOutputStream(_runfile);
IOUtils.write(content, fout, "ISO-8859-1");
fout.flush();
fout.close();
}
public void setProperty(String property, String value) {
content=content.replaceAll(property, value);
}
public String getName() {
return _name;
}
public String getPath() {
if (_runfile!=null)
return _runfile.getAbsolutePath();
return _file.getAbsolutePath();
}
public void clean() {
if (_runfile!=null)
_runfile.delete();
}
public String run(boolean log) throws Exception {
save();
String result = AdbUtility.run(this,log);
clean();
return result;
}
public String runRoot() throws Exception {
save();
boolean datamounted=true;
boolean systemmounted=true;
if (Devices.getCurrent().isRecovery()) {
datamounted = AdbUtility.isMounted("/data");
systemmounted = AdbUtility.isMounted("/data");
if (!datamounted) AdbUtility.mount("/data", "rw", "yaffs2");
if (!systemmounted) AdbUtility.mount("/system", "ro", "yaffs2");
}
String result = AdbUtility.runRoot(this);
clean();
if (Devices.getCurrent().isRecovery()) {
if (!datamounted) AdbUtility.umount("/data");
if (!systemmounted) AdbUtility.umount("/system");
}
return result;
}
public String runRoot(boolean debug) throws Exception {
save();
boolean datamounted=true;
boolean systemmounted=true;
if (Devices.getCurrent().isRecovery()) {
datamounted = AdbUtility.isMounted("/data");
systemmounted = AdbUtility.isMounted("/data");
if (!datamounted) AdbUtility.mount("/data", "rw", "yaffs2");
if (!systemmounted) AdbUtility.mount("/system", "ro", "yaffs2");
}
String result = AdbUtility.runRoot(this,debug);
clean();
if (Devices.getCurrent().isRecovery()) {
if (!datamounted) AdbUtility.umount("/data");
if (!systemmounted) AdbUtility.umount("/system");
}
return result;
}
} | 2,860 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
DevicesGit.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/DevicesGit.java | package org.flashtool.system;
import java.io.File;
import java.io.IOException;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ResetCommand;
import org.eclipse.jgit.api.ResetCommand.ResetType;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.NoHeadException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DevicesGit {
private static String remotePath="https://github.com/Androxyde/devices.git";
private static String localPath=OS.getFolderDevices()+File.separator+".git";
private static Repository localRepo;
private static Git git;
public static void gitSync() throws IOException, InvalidRemoteException, org.eclipse.jgit.api.errors.TransportException, GitAPIException {
if (openRepository()) {
pullRepository();
}
else cloneRepository();
}
public static void cloneRepository() {
try {
log.info("Cloning devices repository to "+OS.getFolderDevices());
File lPath = new File(OS.getFolderDevices());
OS.deleteDirectory(lPath);
lPath.mkdir();
Git result = Git.cloneRepository()
.setURI(remotePath)
.setDirectory(lPath)
.call();
result.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean openRepository() {
try {
log.info("Opening devices repository.");
FileRepositoryBuilder builder = new FileRepositoryBuilder();
log.debug("Local path : "+localPath);
localRepo = builder.setGitDir(new File(localPath))
.readEnvironment() // scan environment GIT_* variables
.findGitDir() // scan up the file system tree
.build();
log.debug("Getting new git object");
git = new Git(localRepo);
return true;
} catch (Exception e) {
log.info("Error opening devices repository.");
closeRepository();
return false;
}
}
public static void pullRepository() {
try {
log.info("Scanning devices folder for changes.");
git.add().addFilepattern(".").call();
Status status = git.status().call();
if (status.getChanged().size()>0 || status.getAdded().size()>0 || status.getModified().size()>0) {
log.info("Changes have been found. Doing a hard reset (removing user modifications).");
ResetCommand reset = git.reset();
reset.setMode(ResetType.HARD);
reset.setRef(Constants.HEAD);
reset.call();
}
log.info("Pulling changes from github.");
git.pull().call();
} catch (NoHeadException e) {
log.info("Pull failed. Trying to clone repository instead");
closeRepository();
cloneRepository();
}
catch (Exception e1) {
closeRepository();
}
}
public static void closeRepository() {
log.info("Quietly closing devices repository.");
try {
git.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
localRepo.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} | 3,325 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
XMLFwInfo.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/XMLFwInfo.java | package org.flashtool.system;
import org.jdom2.input.SAXBuilder;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.Element;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Data
public class XMLFwInfo {
private String project="";
private String product="";
private String model="";
private String cda="";
private String market="";
private String operator="";
private String network="";
private String swVer="";
private String cdfVer="";
public XMLFwInfo(File xmlsource) throws IOException, JDOMException {
SAXBuilder builder = new SAXBuilder();
FileInputStream fin = new FileInputStream(xmlsource);
Document document = builder.build(fin);
fin.close();
Iterator i = document.getRootElement().getChildren().iterator();
while (i.hasNext()) {
Element element = (Element)i.next();
if (element.getName().equals("project"))
project = element.getValue();
if (element.getName().equals("product"))
product = element.getValue();
if (element.getName().equals("model"))
model = element.getValue();
if (element.getName().equals("cda"))
cda = element.getValue();
if (element.getName().equals("market"))
market = element.getValue();
if (element.getName().equals("operator"))
operator = element.getValue();
if (element.getName().equals("network"))
network = element.getValue();
if (element.getName().equals("swVer"))
swVer = element.getValue();
if (element.getName().equals("cdfVer"))
cdfVer = element.getValue();
}
}
public String getVersion() {
return swVer;
}
public String getCDA() {
return cda;
}
public String getOperator() {
return operator;
}
public String getModel() {
return model;
}
public String getProduct() {
return product;
}
public String getRevision() {
return cdfVer;
}
} | 2,063 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
RC4OutputStream.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/RC4OutputStream.java | package org.flashtool.system;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.google.common.io.BaseEncoding;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class RC4OutputStream extends OutputStream {
private CipherOutputStream localCipherOutputStream;
public RC4OutputStream(OutputStream out) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
if (Security.getProvider("BC") == null) {
Security.addProvider(new BouncyCastleProvider());
}
SecretKeySpec secretKeySpec = new SecretKeySpec(BaseEncoding.base64().decode(OS.RC4Key), "RC4");
Cipher cipher = Cipher.getInstance("RC4");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
localCipherOutputStream = new CipherOutputStream(out, cipher);
}
@Override
public void write(int b) throws IOException {
localCipherOutputStream.write(b);
}
@Override
public void flush() throws IOException {
localCipherOutputStream.flush();
}
@Override
public void close() throws IOException {
localCipherOutputStream.close();
}
} | 1,425 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
DNSResolver.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/DNSResolver.java | package org.flashtool.system;
import java.net.InetAddress;
import java.net.UnknownHostException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DNSResolver extends Thread {
private String domain;
private InetAddress inetAddr=null;
public DNSResolver(String domain) {
this.domain = domain;
}
public void run() {
try {
InetAddress addr = InetAddress.getByName(domain);
set(addr);
} catch (UnknownHostException e) {
}
}
public synchronized void set(InetAddress inetAddr) {
this.inetAddr = inetAddr;
}
public synchronized InetAddress get() {
return inetAddr;
}
} | 703 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
GlobalConfig.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/GlobalConfig.java | package org.flashtool.system;
import java.io.File;
import java.io.FileReader;
import java.util.Enumeration;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class GlobalConfig {
private static PropertiesFile config;
public static String getProperty (String property) {
if (config==null) {
reloadProperties();
}
return config.getProperty(property);
}
public static void setProperty(String property, String value) {
config.setProperty(property, value);
config.write("UTF-8");
}
public static void reloadProperties() {
String folder = OS.getUserHome()+File.separator+".flashTool";
new File(folder).mkdirs();
Properties p = null;
try {
File pfile = new File(folder+File.separator+"config.properties");
if (pfile.exists()) {
p = new Properties();
FileReader pread = new FileReader(pfile);
p.load(pread);
pread.close();
pfile.delete();
}
} catch (Exception e) {
p = null;
}
config = new PropertiesFile("gui/ressources/config.properties","");
config.setFileName(folder+File.separator+"config.properties");
if (p!=null) {
Enumeration keys = p.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
GlobalConfig.setProperty(key, p.getProperty(key));
}
}
if (config.getProperty("devfeatures")==null)
config.setProperty("devfeatures", "no");
if (config.getProperty("bundle")!=null)
config.remove("bundle");
config.write("UTF-8");
String userfolder = GlobalConfig.getProperty("user.flashtool");
if (userfolder ==null) GlobalConfig.setProperty("user.flashtool", folder);
}
} | 1,629 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
ProcessBuilderWrapper.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/ProcessBuilderWrapper.java | package org.flashtool.system;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ProcessBuilderWrapper {
private StringWriter infos;
private StringWriter errors;
private int status;
private boolean print = false;
public ProcessBuilderWrapper(File directory, List<String> command) throws Exception {
run(directory, command);
}
public void run(File directory, List<String> command) throws Exception {
infos = new StringWriter();
errors = new StringWriter();
ProcessBuilder pb = new ProcessBuilder(command);
if(directory != null)
pb.directory(directory);
Process process = pb.start();
StreamBoozer seInfo = new StreamBoozer(process.getInputStream(), new PrintWriter(infos, true));
StreamBoozer seError = new StreamBoozer(process.getErrorStream(), new PrintWriter(errors, true));
seInfo.start();
seError.start();
status = process.waitFor();
seInfo.join();
seError.join();
}
public ProcessBuilderWrapper(List<String> command) throws Exception {
run(null, command);
}
public ProcessBuilderWrapper(String[] command, boolean print) throws Exception {
this.print = print;
List<String> cmd = new ArrayList<String>();
for (int i=0;i<command.length;i++)
cmd.add(command[i]);
run(null, cmd);
}
public String getStdErr() {
return errors.toString();
}
public String getStdOut() {
return infos.toString();
}
public RunOutputs getOutputs() {
return new RunOutputs(infos.toString(), errors.toString());
}
public int getStatus() {
return status;
}
class StreamBoozer extends Thread {
private InputStream in;
private PrintWriter pw;
StreamBoozer(InputStream in, PrintWriter pw) {
this.in = in;
this.pw = pw;
}
@Override
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(in));
String line = null;
while ( (line = br.readLine()) != null) {
if (line.trim().replaceAll("\n", "").length()>0) {
line = line.replaceAll("\n", "");
if (print)
log.info(line);
else
log.debug(line);
pw.println(line);
}
}
}
catch (Exception e) {}
finally {
try {
br.close();
} catch (IOException e) {}
}
}
}
public void kill() {
}
} | 2,985 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
StatusEvent.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/StatusEvent.java | package org.flashtool.system;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class StatusEvent {
String newstatus;
boolean driverok;
public StatusEvent(String news, boolean dok) {
newstatus = news;
driverok = dok;
}
public String getNew() {
return newstatus;
}
public boolean isDriverOk() {
return driverok;
}
}
| 336 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
GlobalState.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/GlobalState.java | package org.flashtool.system;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class GlobalState {
private static Properties serials = new Properties();
private static boolean isgui=false;
public synchronized static String getStates (String pserial, String pid) {
Properties p = (Properties) serials.get(pserial);
if (p!=null) {
String state = p.getProperty(pid);
if (state==null) state = "";
return state;
}
else return "";
}
public synchronized static void setStates(String pserial, String pid, String status) {
if (!serials.containsKey(pserial))
serials.put(pserial, new Properties());
((Properties)serials.get(pserial)).setProperty(pid, status);
}
public synchronized static boolean isGUI() {
return isgui;
}
public synchronized static void setGUI() {
isgui=true;
}
} | 847 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
Profile.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/Profile.java | package org.flashtool.system;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import org.flashtool.gui.tools.DeviceApps;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Profile {
public static void save(DeviceApps apps) {
try {
File ftp = new File(Devices.getCurrent().getCleanDir()+File.separator+apps.getCurrentProfile()+".ftp");
byte buffer[] = new byte[10240];
StringBuffer sbuf = new StringBuffer();
sbuf.append("Manifest-Version: 1.0\n");
sbuf.append("Created-By: FlashTool\n");
sbuf.append("profileName: "+apps.getCurrentProfile()+"\n");
Manifest manifest = new Manifest(new ByteArrayInputStream(sbuf.toString().getBytes("UTF-8")));
FileOutputStream stream = new FileOutputStream(ftp);
JarOutputStream out = new JarOutputStream(stream, manifest);
out.setLevel(JarOutputStream.STORED);
JarEntry jarAdd = new JarEntry("safelist"+apps.getCurrentProfile()+".properties");
out.putNextEntry(jarAdd);
InputStream in = new FileInputStream(new File(Devices.getCurrent().getCleanDir()+File.separator+"safelist"+apps.getCurrentProfile()+".properties"));
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
}
in.close();
jarAdd = new JarEntry("customlist.properties");
out.putNextEntry(jarAdd);
in = new FileInputStream(new File(Devices.getCurrent().getCleanDir()+File.separator+"customlist.properties"));
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
}
in.close();
Iterator<String> i = apps.getCurrent().iterator();
while (i.hasNext()) {
String key = i.next();
if (apps.customList().containsKey(key)) {
jarAdd = new JarEntry(key);
out.putNextEntry(jarAdd);
in = new FileInputStream(new File(Devices.getCurrent().getAppsDir()+key));
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
}
in.close();
}
}
out.close();
stream.close();
}
catch (Exception e) {
}
}
}
| 2,647 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
DeviceIdent.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/DeviceIdent.java | package org.flashtool.system;
import java.util.Enumeration;
import java.util.Properties;
import org.flashtool.jna.adb.AdbUtility;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DeviceIdent {
private String pid="";
private String vid="";
private String devicepath="";
private Properties devid;
private int maxsize=0;
private String serial = "";
private String driverdesc = "";
private int drivermajor=0;
private int driverminor=0;
private int drivermili=0;
private int drivermicro=0;
public DeviceIdent() {
pid="";
vid="";
devicepath="";
devid=new Properties();
}
public DeviceIdent(DeviceIdent id) {
devid=new Properties();
Enumeration<Object> e = id.getIds().keys();
while (e.hasMoreElements()) {
String key = (String)e.nextElement();
addDevId(key);
devid.setProperty(key, id.getIds().getProperty(key));
}
addDevPath(id.getDevPath());
}
public void addDevPath(String path) {
if (path.length()>0)
devicepath=path;
}
public String getDevPath() {
return devicepath;
}
public void setDriver(String desc, int maj, int min,int mil, int mic) {
driverdesc = desc;
drivermajor=maj;
driverminor=min;
drivermili=mil;
drivermicro=mic;
}
public String getDriverDescription() {
return driverdesc;
}
public int getDriverMajor() {
return drivermajor;
}
public int getDriverMinor() {
return driverminor;
}
public int getDriverMili() {
return drivermili;
}
public int getDriverMicro() {
return drivermicro;
}
public void addDevId(String device) {
if (device.length()>maxsize) maxsize=device.length();
vid=device.substring(device.indexOf("VID_")+4, device.indexOf("PID_")-1);
int begin = device.indexOf("PID_")+4;
pid=device.substring(begin,begin+4);
if (!device.contains("MI")) {
serial = device.substring(begin+5,device.length());
}
devid.setProperty(device, Boolean.toString(true));
}
public void addDevId(String vendor, String product, String ser) {
vid = vendor;
pid = product;
serial = ser;
devid.setProperty("VID_"+vendor+"&"+"PID_"+product+"\\", "true");
}
public void setDriverOk(String device,boolean status) {
devid.setProperty(device, Boolean.toString(status));
}
public String getPid() {
return pid;
}
public String getVid() {
return vid;
}
public String getSerial() {
return serial;
}
public boolean isDriverOk() {
Enumeration e = devid.elements();
while (e.hasMoreElements()) {
String value = (String)e.nextElement();
boolean b = Boolean.parseBoolean(value);
if (!b) return false;
}
return true;
}
public String getDeviceId() {
Enumeration<Object> e = devid.keys();
while (e.hasMoreElements()) {
String value = (String)e.nextElement();
if (!value.contains("MI")) return value;
}
return "none";
}
public String getStatus() {
if (!getVid().equals("0FCE")) return "none";
if (!isDriverOk()) return "notinstalled";
if (getPid().equals("ADDE") || getPid().equals("B00B")) {
if (OS.getName().equals("windows")) {
if (drivermajor==3 && driverminor >=1)
return "flash";
if (drivermajor>3)
return "flash";
return "flash_obsolete";
}
else return "flash";
}
if (getPid().equals("0DDE")) return "fastboot";
return AdbUtility.getStatus();
}
public Properties getIds() {
return devid;
}
public int getMaxSize() {
return maxsize;
}
}
| 3,380 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
RC4InputStream.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/RC4InputStream.java | package org.flashtool.system;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.google.common.io.BaseEncoding;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class RC4InputStream extends InputStream {
private InputStream in = null;
private CipherInputStream localCipherInputStream;
public RC4InputStream(InputStream in) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
this.in = in;
if (Security.getProvider("BC") == null) {
Security.addProvider(new BouncyCastleProvider());
}
SecretKeySpec secretKeySpec = new SecretKeySpec(BaseEncoding.base64().decode(OS.RC4Key), "RC4");
Cipher cipher = Cipher.getInstance("RC4");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
localCipherInputStream = new CipherInputStream(in, cipher);
}
@Override
public int read() throws IOException {
return localCipherInputStream.read();
}
@Override
public int read(byte[] b) throws IOException {
return localCipherInputStream.read(b);
}
@Override
public boolean markSupported() {
return localCipherInputStream.markSupported();
}
} | 1,477 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
PhoneThread.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/PhoneThread.java | package org.flashtool.system;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PhoneThread extends Thread {
boolean done = false;
boolean paused = false;
boolean forced = false;
String status = "none";
String pid = "";
StatusListener listener;
public void run() {
this.setName("Phonne-connect-watchdog");
int count = 0;
DeviceIdent id=null;
int nbstatustocount=0;
String lstatus="";
while (!done) {
if (!paused) {
id = Devices.getConnectedDevice();
if (!pid.equals(id.getPid())) {
nbstatustocount=0;
pid=id.getPid();
}
else {
if (nbstatustocount<Integer.parseInt(GlobalConfig.getProperty("usbdetectthresold"))) nbstatustocount++;
else lstatus=id.getStatus();
}
if (!status.equals(lstatus) && (nbstatustocount==Integer.parseInt(GlobalConfig.getProperty("usbdetectthresold")))) {
status=lstatus;
if (status.equals("adb")) {
DeviceProperties.reload();
}
fireStatusChanged(new StatusEvent(lstatus,id.isDriverOk()));
}
}
try {
while ((count<50) && (!done)) {
sleep(10);
count++;
}
count = 0;
} catch (Exception e) {}
}
Devices.clean();
}
public void pause(boolean ppaused) {
paused = ppaused;
status="paused";
}
public void end() {
done = true;
}
public void addStatusListener(StatusListener listener) {
this.listener = listener;
}
public void removeStatusListener(StatusListener listener) {
this.listener = null;
}
public StatusListener getStatusListeners() {
return listener;
}
protected void fireStatusChanged(StatusEvent e) {
if (listener!=null)
listener.statusChanged(e);
}
public void forceDetection() {
if (!forced) forced = true;
}
public void doSleep(int time) {
try {
sleep(time);
}
catch (Exception e) {}
}
}
| 1,893 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
DeviceChangedListener.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/DeviceChangedListener.java | package org.flashtool.system;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DeviceChangedListener {
public static PhoneThread usbwatch;
public static void starts(StatusListener listener) {
usbwatch = new PhoneThread();
usbwatch.addStatusListener(listener);
usbwatch.start();
}
public static void stop() {
try {
usbwatch.end();
usbwatch.join();
}
catch (Exception e) {}
}
public static void enableDetection() {
usbwatch.pause(false);
}
public static void disableDetection() {
usbwatch.pause(true);
}
public static void forceDetection() {
usbwatch.forceDetection();
}
} | 621 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
URLDownloader.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/URLDownloader.java | package org.flashtool.system;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import org.flashtool.logger.LogProgress;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class URLDownloader {
long mFileLength = 0;
long mDownloaded = -1;
String strLastModified = "";
BufferedInputStream input = null;
RandomAccessFile outFile = null;
boolean canceled = false;
public long Download(String strurl, String filedest, long seek) throws IOException {
try {
// Setup connection.
URL url = new URL(strurl);
URLConnection connection = url.openConnection();
File fdest = new File(filedest);
connection.connect();
mDownloaded = 0;
mFileLength = connection.getContentLength();
strLastModified = connection.getHeaderField("Last-Modified");
Map<String, List<String>> map = connection.getHeaderFields();
// Setup streams and buffers.
int chunk = 131072;
input = new BufferedInputStream(connection.getInputStream(), chunk);
outFile = new RandomAccessFile(fdest, "rw");
outFile.seek(seek);
byte data[] = new byte[chunk];
LogProgress.initProgress(100);
long i=0;
// Download file.
for (int count=0; (count=input.read(data, 0, chunk)) != -1; i++) {
outFile.write(data, 0, count);
mDownloaded += count;
LogProgress.updateProgressValue((int) (mDownloaded * 100 / mFileLength));
if (mDownloaded >= mFileLength)
break;
if (canceled) break;
}
// Close streams.
outFile.close();
input.close();
return mDownloaded;
}
catch (IOException ioe) {
try {
outFile.close();
} catch (Exception ex1) {}
try {
input.close();
} catch (Exception ex2) {}
if (canceled) throw new IOException("Job canceled");
throw ioe;
}
}
public void Cancel() {
canceled = true;
while (input==null);
try {
input.close();
} catch (Exception e) {}
}
} | 2,246 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
XMLUpdate.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/XMLUpdate.java | package org.flashtool.system;
import org.jdom2.input.SAXBuilder;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.Element;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class XMLUpdate {
private String noerase="";
public XMLUpdate(File xmlsource) throws IOException, JDOMException {
SAXBuilder builder = new SAXBuilder();
FileInputStream fin = new FileInputStream(xmlsource);
Document document = builder.build(fin);
fin.close();
Iterator i = document.getRootElement().getChildren().iterator();
while (i.hasNext()) {
Element element = (Element)i.next();
if (element.getName().equals("NOERASE") || element.getName().equals("FACTORY_ONLY"))
noerase = noerase + element.getValue() + ",";
}
}
public String getNoErase() {
if (noerase.length()==0) return noerase;
return noerase.substring(0, noerase.length()-1);
}
} | 990 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
UpdateURL.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/UpdateURL.java | package org.flashtool.system;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class UpdateURL {
String url = "";
Properties parameters = new Properties();
String path;
String cpath;
public UpdateURL(String fullurl) throws Exception {
url = fullurl.substring(0,fullurl.indexOf("?"));
String params = fullurl.substring(fullurl.indexOf("?")+1,fullurl.length());
String[] list = params.split("&");
for (int i=0;i<list.length;i++) {
parameters.setProperty(list[i].split("=")[0], list[i].split("=")[1]);
}
String devId = getDeviceID();
if (devId.length()==0) throw new Exception("Device not found in database");
DeviceEntry ent = Devices.getDevice(devId);
path = ent.getDeviceDir()+File.separator+"updates"+File.separator+getVariant();
cpath = ent.getMyDeviceDir()+File.separator+"updates"+File.separator+getVariant();
}
public boolean exists() {
return (new File(path).exists() || new File(cpath).exists());
}
public String getParameters() {
return parameters.toString();
}
public String getParameter(String parameter) {
return parameters.getProperty(parameter);
}
public void setParameter(String parameter, String value) {
parameters.setProperty(parameter, value);
}
public String getFullURL() {
String fullurl = url + "?";
Enumeration<Object> e = parameters.keys();
while (e.hasMoreElements()) {
String key = (String)e.nextElement();
fullurl = fullurl+key + "=" + parameters.getProperty(key)+"&";
}
return fullurl.substring(0, fullurl.length()-1);
}
public String getDeviceID() {
String uid = this.getParameter("model");
String id = Devices.getDeviceFromVariant(uid).getId();
if (id.equals(uid)) return "";
return id;
}
public String getVariant() {
String uid = this.getParameter("model");
return uid;
}
public void dumpToFile() throws IOException {
TextFile t = new TextFile(cpath+File.separator+"updateurl","ISO8859-15");
t.open(false);
t.write(this.getFullURL());
t.close();
}
} | 2,092 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
OS.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/OS.java | package org.flashtool.system;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.TimeZone;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.crypto.NoSuchPaddingException;
import org.apache.commons.io.FileUtils;
import org.flashtool.logger.LogProgress;
import org.flashtool.util.HexDump;
import java.util.zip.CheckedInputStream;
import java.util.zip.Adler32;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class OS {
public static String RC4Key = "DoL6FBfnYcNJBjH31Vnz6lKATTaDGe4y";
public static String AESKey = "qAp!wmvl!cOS7xSQV!aoR7Qz*neY^5Sx";
public static String AESIV = "5621616F5237517A21634F5337785351";
public static String getPlatform() {
return System.getProperty("sun.arch.data.model");
}
public static void writeToFile(InputStream is, File f) throws IOException {
FileUtils.copyInputStreamToFile(is, f);
}
public static void deleteDirectory(File directory) throws IOException {
FileUtils.deleteDirectory(directory);
}
public static String getName() {
String os = "";
if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
os = "windows";
} else if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
os = "linux";
} else if (System.getProperty("os.name").toLowerCase().indexOf("mac") > -1) {
os = "mac";
}
return os;
}
public static String getTimeStamp() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setTimeZone( TimeZone.getTimeZone("PST"));
String date = ( df.format(new Date()));
DateFormat df1 = new SimpleDateFormat("hh-mm-ss") ;
df1.setTimeZone( TimeZone.getDefault()) ;
String time = ( df1.format(new Date()));
return date+"_"+time;
}
public static void unyaffs(String yaffsfile, String folder) {
try {
File f = new File(folder);
if (!f.exists()) f.mkdirs();
else if (f.isFile()) throw new IOException("destination must be a folder");
ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {getWorkDir()+File.separator+"x10flasher_lib"+File.separator+"unyaffs",yaffsfile,folder},false);
}
catch (Exception e) {
log.warn("Failed : "+e.getMessage());
}
}
public static String getPathAdb() {
if (OS.getName().equals("windows"))
return new File(System.getProperty("user.dir")+File.separator+"x10flasher_native"+File.separator+"adb.exe").getAbsolutePath();
else
return new File(System.getProperty("user.dir")+File.separator+"x10flasher_native"+File.separator+"adb").getAbsolutePath();
}
public static String getPathBin2Sin() {
if (OS.getName().equals("windows"))
return new File(System.getProperty("user.dir")+File.separator+"x10flasher_native"+File.separator+"bin2sin.exe").getAbsolutePath();
else
return new File(System.getProperty("user.dir")+File.separator+"x10flasher_native"+File.separator+"bin2sin").getAbsolutePath();
}
public static String getPathBin2Elf() {
String fsep = OS.getFileSeparator();
if (OS.getName().equals("windows"))
return new File(System.getProperty("user.dir")+fsep+"x10flasher_native"+fsep+"bin2elf.exe").getAbsolutePath();
else
return new File(System.getProperty("user.dir")+fsep+"x10flasher_native"+fsep+"bin2elf").getAbsolutePath();
}
public static String getPathXperiFirmWrapper() {
String fsep = OS.getFileSeparator();
return new File(System.getProperty("user.dir")+fsep+"x10flasher_native"+fsep+"xperifirm").getAbsolutePath();
}
public static String getPathFastBoot() {
String fsep = OS.getFileSeparator();
if (OS.getName().equals("windows"))
return new File(System.getProperty("user.dir")+fsep+"x10flasher_native"+fsep+"fastboot.exe").getAbsolutePath();
else
return new File(System.getProperty("user.dir")+fsep+"x10flasher_native"+fsep+"fastboot").getAbsolutePath();
}
public static String getPathXperiFirm() {
String fsep = OS.getFileSeparator();
return new File(OS.getFolderUserFlashtool()+fsep+"XperiFirm.exe").getAbsolutePath();
}
public static String getWorkDir() {
return System.getProperty("user.dir");
}
public static String getSHA256(byte[] array) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(array, 0, array.length);
byte[] sha256 = digest.digest();
return HexDump.toHex(sha256);
}
catch(NoSuchAlgorithmException nsa) {
throw new RuntimeException("Unable to process file for SHA-256", nsa);
}
}
public static String getSHA1(byte[] array) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(array, 0, array.length);
byte[] sha1 = digest.digest();
return HexDump.toHex(sha1);
}
catch(NoSuchAlgorithmException nsa) {
throw new RuntimeException("Unable to process file for SHA-256", nsa);
}
}
public static String getSHA256(File f) {
byte[] buffer = new byte[8192];
int read = 0;
InputStream is=null;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
is = new FileInputStream(f);
while( (read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] sha256 = digest.digest();
BigInteger bigInt = new BigInteger(1, sha256);
String output = bigInt.toString(32);
return output.toUpperCase();
}
catch(IOException e) {
throw new RuntimeException("Unable to process file for SHA-256", e);
}
catch(NoSuchAlgorithmException nsa) {
throw new RuntimeException("Unable to process file for SHA-256", nsa);
}
finally {
try {
is.close();
}
catch(IOException e) {
throw new RuntimeException("Unable to close input stream for SHA-256 calculation", e);
}
}
}
public static void copyfile(String srFile, String dtFile){
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
if (!f1.getAbsolutePath().equals(f2.getAbsolutePath())) {
InputStream in = new FileInputStream(f1);
//For Append the file.
// OutputStream out = new FileOutputStream(f2,true);
//For Overwrite the file.
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
catch(FileNotFoundException ex){
log.error(ex.getMessage() + " in the specified directory.");
}
catch(IOException e){
log.error(e.getMessage());
}
}
public static long getAlder32(File f) {
try {
FileInputStream inputStream = new FileInputStream(f);
Adler32 adlerChecksum = new Adler32();
CheckedInputStream cinStream = new CheckedInputStream(inputStream, adlerChecksum);
byte[] b = new byte[128];
while (cinStream.read(b) >= 0) {
}
long checksum = cinStream.getChecksum().getValue();
cinStream.close();
return checksum;
} catch (IOException e) {
return 0;
}
}
public static String getMD5(File f) {
byte[] buffer = new byte[8192];
int read = 0;
InputStream is=null;
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
is = new FileInputStream(f);
while( (read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
String output = bigInt.toString(16);
return String.format("%32s", output).replace(' ', '0');
}
catch(IOException e) {
throw new RuntimeException("Unable to process file for MD5", e);
}
catch(NoSuchAlgorithmException nsa) {
throw new RuntimeException("Unable to process file for MD5", nsa);
}
finally {
try {
is.close();
}
catch(IOException e) {
throw new RuntimeException("Unable to close input stream for MD5 calculation", e);
}
}
}
public static String getVersion() {
return System.getProperty("os.version");
}
public static String getFileSeparator() {
return System.getProperty("file.separator");
}
public static String getWinDir() {
if (System.getenv("WINDIR")==null) return System.getenv("SYSTEMROOT");
if (System.getenv("WINDIR").length()==0) return System.getenv("SYSTEMROOT");
return System.getenv("WINDIR");
}
public static String getSystem32Dir() {
return getWinDir()+getFileSeparator()+"System32";
}
public static Collection<File> listFileTree(File dir) {
Set<File> fileTree = new HashSet<File>();
for (File entry : dir.listFiles()) {
if (entry.isFile()) fileTree.add(entry);
else {
fileTree.addAll(listFileTree(entry));
fileTree.add(entry);
}
}
return fileTree;
}
public static byte[] copyBytes(byte[] arr, int length)
{
byte[] newArr = null;
if (arr.length == length)
newArr = arr;
else
{
newArr = new byte[length];
for (int i = 0; i < length; i++)
{
newArr[i] = (byte) arr[i];
}
}
return newArr;
}
public static RandomAccessFile generateEmptyFile(String fname, long size, byte fill) {
// To fill the empty file with FF values
if ((size/1024/1024)<0)
log.info("File size : "+size/1024/1024+" Mb");
else
log.info("File size : "+size/1024+" Kb");
try {
byte[] empty = new byte[65*1024];
for (int i=0; i<empty.length;i++)
empty[i] = fill;
// Creation of empty file
File f = new File(fname);
f.delete();
FileOutputStream fout = new FileOutputStream(f);
LogProgress.initProgress(size/empty.length+size%empty.length);
for (long i = 0; i<size/empty.length; i++) {
fout.write(empty);
LogProgress.updateProgress();
}
for (long i = 0; i<size%empty.length; i++) {
fout.write(fill);
LogProgress.updateProgress();
}
LogProgress.initProgress(0);
fout.flush();
fout.close();
RandomAccessFile fo = new RandomAccessFile(f,"rw");
return fo;
}
catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
return null;
}
}
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
public static void ZipExplodeToFolder(String zippath) throws FileNotFoundException, IOException {
byte buffer[] = new byte[10240];
File zipfile = new File(zippath);
File outfolder = new File(zipfile.getParentFile().getAbsolutePath()+File.separator+zipfile.getName().replace(".zip", "").replace(".ZIP", ""));
outfolder.mkdirs();
ZipInputStream zis = new ZipInputStream(new FileInputStream(zippath));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
FileOutputStream fout = new FileOutputStream(outfolder.getAbsolutePath()+File.separator+ze.getName());
int len;
while ((len=zis.read(buffer))>0) {
fout.write(buffer,0,len);
}
fout.close();
ze=zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
public static void ZipExplodeToHere(String zippath) throws FileNotFoundException, IOException {
byte buffer[] = new byte[10240];
File zipfile = new File(zippath);
File outfolder = new File(zipfile.getParentFile().getAbsolutePath());
outfolder.mkdirs();
ZipInputStream zis = new ZipInputStream(new FileInputStream(zippath));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
FileOutputStream fout = new FileOutputStream(outfolder.getAbsolutePath()+File.separator+ze.getName());
int len;
while ((len=zis.read(buffer))>0) {
fout.write(buffer,0,len);
}
fout.close();
ze=zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
public static void ZipExplodeTo(InputStream stream, File outfolder) throws FileNotFoundException, IOException {
byte buffer[] = new byte[10240];
outfolder.mkdirs();
ZipInputStream zis = new ZipInputStream(stream);
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
FileOutputStream fout = new FileOutputStream(outfolder.getAbsolutePath()+File.separator+ze.getName());
int len;
while ((len=zis.read(buffer))>0) {
fout.write(buffer,0,len);
}
fout.close();
ze=zis.getNextEntry();
}
zis.closeEntry();
zis.close();
stream.close();
}
public static void viewAllThreads() {
// Walk up all the way to the root thread group
ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
ThreadGroup parent;
while ((parent = rootGroup.getParent()) != null) {
rootGroup = parent;
}
listThreads(rootGroup, "");
}
// List all threads and recursively list all subgroup
public static void listThreads(ThreadGroup group, String indent) {
System.out.println(indent + "Group[" + group.getName() +
":" + group.getClass()+"]");
int nt = group.activeCount();
Thread[] threads = new Thread[nt*2 + 10]; //nt is not accurate
nt = group.enumerate(threads, false);
// List every thread in the group
for (int i=0; i<nt; i++) {
Thread t = threads[i];
System.out.println(indent + " Thread[" + t.getName()
+ ":" + t.getClass() + "]");
}
// Recursively list all subgroups
int ng = group.activeGroupCount();
ThreadGroup[] groups = new ThreadGroup[ng*2 + 10];
ng = group.enumerate(groups, false);
for (int i=0; i<ng; i++) {
listThreads(groups[i], indent + " ");
}
}
public static Manifest getManifest( Class<?> cl ) {
InputStream inputStream = null;
try {
URLClassLoader classLoader = (URLClassLoader)cl.getClassLoader();
String classFilePath = cl.getName().replace('.','/')+".class";
URL classUrl = classLoader.getResource(classFilePath);
if ( classUrl==null ) return null;
String classUri = classUrl.toString();
if ( !classUri.startsWith("jar:") ) return null;
int separatorIndex = classUri.lastIndexOf('!');
if ( separatorIndex<=0 ) return null;
String manifestUri = classUri.substring(0,separatorIndex+2)+"META-INF/MANIFEST.MF";
URL url = new URL(manifestUri);
inputStream = url.openStream();
return new Manifest( inputStream );
} catch ( Throwable e ) {
// handle errors
//...
return null;
} finally {
if ( inputStream!=null ) {
try {
inputStream.close();
} catch ( Throwable e ) {
// ignore
}
}
}
}
public static String getChannel() {
Enumeration resEnum;
try {
resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
while (resEnum.hasMoreElements()) {
try {
URL url = (URL)resEnum.nextElement();
InputStream is = url.openStream();
if (is != null) {
Manifest manifest = new Manifest(is);
Attributes mainAttribs = manifest.getMainAttributes();
String version = mainAttribs.getValue("Internal-Channel");
if(version != null) {
return version;
}
}
}
catch (Exception e) {
// Silently ignore wrong manifests on classpath?
}
}
} catch (IOException e1) {
// Silently ignore wrong manifests on classpath?
}
return null;
}
public static void decrypt(File infile) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
byte[] buf = new byte[1024];
try {
if (!infile.getName().endsWith(".enc")) throw new IOException("Bad filename");
RC4InputStream in = new RC4InputStream(new FileInputStream(infile));
File outfile = new File(infile.getAbsolutePath().substring(0, infile.getAbsolutePath().length()-4));
OutputStream out = new FileOutputStream(outfile);
int len;
while((len = in.read(buf)) >= 0) {
out.write(buf, 0, len);
}
out.flush();
out.close();
in.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public static void encrypt(File infile) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
byte[] buf = new byte[1024];
try {
String outname = infile.getAbsolutePath()+".enc";
FileInputStream in = new FileInputStream(infile);
RC4OutputStream out = new RC4OutputStream(new FileOutputStream(outname));
int len;
while((len = in.read(buf)) >= 0) {
if (len > 0)
out.write(buf, 0, len);
}
out.flush();
out.close();
in.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public static String getUserHome() {
return System.getProperty("user.home");
}
public static String getFolderCustom() {
return getWorkDir()+File.separator+"custom";
}
public static String getFolderDevices() {
return OS.getFolderUserFlashtool()+File.separator+"devices";
}
public static String getFolderUserFlashtool() {
String folder = GlobalConfig.getProperty("user.flashtool");
if (folder==null) folder = getUserHome()+File.separator+".flashTool";
new File(folder).mkdirs();
GlobalConfig.setProperty("user.flashtool", folder);
return folder;
}
public static String getFolderFirmwares() {
new File(OS.getFolderUserFlashtool()+File.separator+"firmwares").mkdirs();
return OS.getFolderUserFlashtool()+File.separator+"firmwares";
}
public static String getFolderFirmwaresPrepared() {
new File(OS.getFolderFirmwares()+File.separator+"prepared").mkdirs();
return OS.getFolderFirmwares()+File.separator+"prepared";
}
public static String getFolderFirmwaresDownloaded() {
new File(OS.getFolderFirmwares()+File.separator+"Downloads").mkdirs();
return OS.getFolderFirmwares()+File.separator+"Downloads";
}
public static String getFolderFirmwaresScript() {
new File(OS.getFolderFirmwares()+File.separator+"Scripts").mkdirs();
return OS.getFolderFirmwares()+File.separator+"Scripts";
}
public static String getFolderFirmwaresSinExtracted() {
new File(OS.getFolderFirmwares()+File.separator+"sinExtracted").mkdirs();
return OS.getFolderFirmwares()+File.separator+"sinExtracted";
}
public static String getFolderMyDevices() {
new File(OS.getFolderUserFlashtool()+File.separator+"mydevices").mkdirs();
return OS.getFolderUserFlashtool()+File.separator+"mydevices";
}
public static String getFolderRegisteredDevices() {
new File(OS.getFolderUserFlashtool()+File.separator+"registeredDevices").mkdirs();
return OS.getFolderUserFlashtool()+File.separator+"registeredDevices";
}
public static void unpackArchive(URL url, File targetDir) throws IOException {
if (!targetDir.exists()) {
targetDir.mkdirs();
}
OS.ZipExplodeTo(new BufferedInputStream(url.openStream()),new File(OS.getFolderUserFlashtool()));
}
public static void copyInputStream(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len >= 0) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
in.close();
out.close();
}
} | 20,077 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
AESOutputStream.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/system/AESOutputStream.java | package org.flashtool.system;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class AESOutputStream extends OutputStream {
private CipherOutputStream localCipherOutputStream;
public AESOutputStream(OutputStream out) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, NoSuchProviderException, InvalidAlgorithmParameterException {
if (Security.getProvider("BC") == null) {
Security.addProvider(new BouncyCastleProvider());
}
SecretKeySpec secretKeySpec = new SecretKeySpec(Hashing.sha256().hashBytes(OS.AESKey.getBytes("UTF-8")).asBytes(), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(BaseEncoding.base16().decode(OS.AESIV));
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
localCipherOutputStream = new CipherOutputStream(out, cipher);
}
@Override
public void write(int b) throws IOException {
localCipherOutputStream.write(b);
}
@Override
public void flush() throws IOException {
localCipherOutputStream.flush();
}
@Override
public void close() throws IOException {
localCipherOutputStream.close();
}
} | 1,901 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
TARawParser.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/ta/TARawParser.java | package org.flashtool.parsers.ta;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.flashtool.gui.models.TABag;
import org.flashtool.system.OS;
import com.igormaznitsa.jbbp.JBBPParser;
import com.igormaznitsa.jbbp.io.JBBPBitInputStream;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TARawParser {
JBBPBitInputStream ddStream = null;
FileInputStream fin = null;
BufferedInputStream bin = null;
File ddFile = null;
Vector<TABag> bags = new Vector<TABag>();
JBBPParser partblock = JBBPParser.prepare(
" <int magic;"
+ "<int hash;"
+ "byte unknown;"
+ "byte partnumber;"
+ "byte partition;"
+ "byte numblocks;"
+ "byte[131072-12] units;"
);
public TARawParser(File ddfile) throws FileNotFoundException, IOException {
if (ddfile.getName().endsWith(".fta")) {
open(ddfile);
ddFile=new File(ddfile.getParentFile().getAbsolutePath()+File.separator+"prepared"+File.separator+"ta.dd");
}
else
ddFile = ddfile;
log.info("Parsing image "+ddFile.getAbsolutePath());
openStreams();
while (ddStream.hasAvailableData()) {
TARawBlock parsedblock = partblock.parse(ddStream).mapTo(new TARawBlock());
if (parsedblock.magic==0x3BF8E9C1) {
parsedblock.parseUnits();
Iterator<TABag> ib = bags.iterator();
TABag b = null;
boolean found = false;
while (ib.hasNext()) {
b = ib.next();
if (b.partition==parsedblock.partition) {
found=true;
break;
}
}
if (!found) b = new TABag(parsedblock.partition);
Iterator<TAUnit> iu = parsedblock.getUnits().iterator();
while (iu.hasNext()) {
b.addUnit(iu.next());
}
if (!found) bags.add(b);
}
}
closeStreams();
log.info("Parsing finished");
}
public void closeStreams() {
try {
ddStream.close();
} catch (Exception e) {}
try {
fin.close();
} catch (Exception e) {}
try {
bin.close();
} catch (Exception e) {}
}
public void openStreams() throws FileNotFoundException {
closeStreams();
fin=new FileInputStream(ddFile);
ddStream = new JBBPBitInputStream(fin);
}
public Vector<TABag> getBags() {
return bags;
}
public boolean open(File bundle) {
try {
log.info("Preparing files for flashing");
String prepared = bundle.getParentFile().getAbsolutePath()+File.separator+"prepared";
OS.deleteDirectory(new File(prepared));
File f = new File(prepared);
f.mkdir();
log.debug("Created the "+f.getName()+" folder");
JarFile jar=new JarFile(bundle);
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().startsWith("ta")) {
InputStream in = jar.getInputStream(entry);
String outname=prepared+File.separator+entry.getName();
OutputStream out = new BufferedOutputStream(new FileOutputStream(outname));
byte[] buffer = new byte[10240];
int len;
while((len = in.read(buffer)) >= 0)
out.write(buffer, 0, len);
in.close();
out.close();
}
}
return true;
}
catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
return false;
}
}
} | 3,623 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
TAFileParser.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/ta/TAFileParser.java | package org.flashtool.parsers.ta;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TAFileParser {
private static final Pattern COMMENT_LINE_PATTERN = Pattern.compile("^//.*");
private static final Pattern BLANK_LINE_PATTERN = Pattern.compile("^[\\s]*$");
private static final Pattern PARTITION_LINE_PATTERN = Pattern.compile("^\\p{XDigit}{2}$");
private static final Pattern DATA_LINE_PATTERN = Pattern.compile("^(\\p{XDigit}{8})(?: |\\t)+(\\p{XDigit}{4,8})((?:(?: |\\t)+\\p{XDigit}{2}{2})*)\\s*$");
private static final Pattern CONTINUATION_DATA_LINE_PATTERN = Pattern.compile("^((?:(?: |\\t)+\\p{XDigit}{2})+)\\s*$");
private BufferedReader aReader;
protected int aPartition;
private long aUnit;
private int aUnitSize;
private ArrayList<String> aContinuationUnitDataList = new ArrayList();
private byte[] aUnitDataArray;
private boolean aFoundPartition = false;
private boolean aContinuationData = false;
private Vector<TAUnit> units = new Vector<TAUnit>();
private File tafile;
public TAFileParser(File taf) throws TAFileParseException, IOException {
tafile=taf;
FileInputStream inputStream = new FileInputStream(taf);
this.parse(inputStream);
inputStream.close();
}
public String getName() {
return tafile.getName();
}
public TAFileParser(InputStream inputStream) throws TAFileParseException, IOException {
this.parse(inputStream);
inputStream.close();
}
public void parse(InputStream inputStream) throws TAFileParseException, IOException {
this.aReader = new BufferedReader(new InputStreamReader(inputStream));
this.aPartition = -1;
this.aFoundPartition = false;
this.aContinuationData = false;
this.parsePartition();
while (getNextUnit()>0) {
getUnitData();
TAUnit unit = new TAUnit((int)this.aUnit,this.aUnitDataArray);
units.addElement(unit);
}
}
public Vector<TAUnit> entries() {
return units;
}
public int getPartition() {
return this.aPartition;
}
public boolean overridePartition() {
return false;
}
public long getNextUnit() throws TAFileParseException, IOException {
this.aUnitDataArray = null;
this.aContinuationUnitDataList = new ArrayList();
if (this.aContinuationData) {
throw new TAFileParseException("Expecting more data from unit :[" + this.aUnit + "] before reading next unit.");
}
String string = "";
while ((string = this.aReader.readLine()) != null) {
if (this.matchDataLine(string)) {
return this.aUnit;
}
if (this.matchComment(string) || this.matchBlankLine(string)) continue;
throw new TAFileParseException("Expected unit data line, at line:[" + string + "].");
}
return -1;
}
public byte[] getUnitData() throws TAFileParseException, IOException {
while (this.aContinuationData) {
String string = "";
string = this.aReader.readLine();
if (string == null) {
throw new TAFileParseException("Expected more data for unit:[" + this.aUnit + "].");
}
if (this.matchContinuationDataLine(string)) continue;
throw new TAFileParseException("Expected more data for unit:[" + this.aUnit + "] at line:[" + string + "].");
}
return this.aUnitDataArray;
}
private int parsePartition() throws TAFileParseException, IOException {
if (this.aPartition != -1) {
return this.aPartition;
}
String string = "";
while ((string = this.aReader.readLine()) != null) {
if (this.matchPartition(string)) {
return this.aPartition;
}
if (this.matchComment(string) || this.matchBlankLine(string)) continue;
throw new TAFileParseException("Expected partition at line:[" + string + "].");
}
throw new TAFileParseException("No partition found in data.");
}
private boolean matchComment(String string) {
Matcher matcher = COMMENT_LINE_PATTERN.matcher((CharSequence)string);
return matcher.matches();
}
private boolean matchPartition(String string) throws TAFileParseException {
Matcher matcher = PARTITION_LINE_PATTERN.matcher((CharSequence)string);
if (matcher.matches()) {
if (this.aFoundPartition) {
throw new TAFileParseException("Parse exception: Duplicate partitions in data.");
}
String string2 = matcher.group();
this.aPartition = Integer.parseInt(string2, 16);
if (this.aPartition != 1 && this.aPartition != 2) {
throw new TAFileParseException("Unexpected partition in data :[" + string2 + "]");
}
this.aFoundPartition = true;
return true;
}
return false;
}
private boolean matchDataLine(String string) throws TAFileParseException {
Matcher matcher = DATA_LINE_PATTERN.matcher((CharSequence)string);
if (matcher.matches()) {
if (!this.aFoundPartition) {
throw new TAFileParseException("Parse exception: Expected partition.");
}
String string2 = matcher.group(1);
this.aUnit = Long.parseLong(string2, 16);
string2 = matcher.group(2);
this.aUnitSize = Integer.parseInt(string2, 16);
string2 = matcher.group(3);
String[] arrstring = string2.trim().split("(?: |\\t)+");
this.aContinuationUnitDataList = new ArrayList();
if (arrstring.length < this.aUnitSize) {
for (int i = 0; i < arrstring.length; ++i) {
this.aContinuationUnitDataList.add(arrstring[i]);
}
this.aContinuationData = true;
return true;
}
if (arrstring.length > this.aUnitSize) {
if (this.aUnitSize == 0 && arrstring.length == 1 && arrstring[0].equals("")) {
this.aUnitDataArray = new byte[0];
return true;
}
throw new TAFileParseException("Parse exception: Too much data for unit [" + this.aUnit + "]");
}
this.aUnitDataArray = this.asBytes(arrstring);
return true;
}
return false;
}
private boolean matchContinuationDataLine(String string) throws TAFileParseException {
if (!this.aFoundPartition) {
throw new TAFileParseException("Parse exception: Expected partition.");
}
Matcher matcher = CONTINUATION_DATA_LINE_PATTERN.matcher((CharSequence)string);
if (matcher.matches()) {
String string2 = matcher.group(1);
String[] arrstring = string2.trim().split("(?: |\\t)+");
long l = this.aContinuationUnitDataList.size() + arrstring.length;
for (int i = 0; i < arrstring.length; ++i) {
this.aContinuationUnitDataList.add(arrstring[i]);
}
if (l < (long)this.aUnitSize) {
this.aContinuationData = true;
return true;
}
if (l > (long)this.aUnitSize) {
throw new TAFileParseException("Parse exception: Too much data for unit [" + this.aUnit + "] : " + l);
}
this.aUnitDataArray = this.asBytes(this.aContinuationUnitDataList);
this.aContinuationData = false;
return true;
}
return false;
}
private boolean matchBlankLine(String string) {
Matcher matcher = BLANK_LINE_PATTERN.matcher((CharSequence)string);
return matcher.matches();
}
private byte[] asBytes(String[] arrstring) {
byte[] arrby = new byte[arrstring.length];
for (int i = 0; i < arrstring.length; ++i) {
arrby[i] = (byte)Integer.parseInt(arrstring[i], 16);
}
return arrby;
}
private byte[] asBytes(Collection<String> collection) {
byte[] arrby = new byte[collection.size()];
int n = 0;
Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()) {
arrby[n++] = (byte)Integer.parseInt(iterator.next(), 16);
}
return arrby;
}
}
| 8,824 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
TAUnit.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/ta/TAUnit.java | package org.flashtool.parsers.ta;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import org.flashtool.util.BytesUtil;
import org.flashtool.util.HexDump;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TAUnit {
private int aUnitNumber;
private byte[] aUnitData;
public TAUnit(int l, byte[] arrby) {
this.aUnitNumber = l;
this.aUnitData = arrby;
}
public byte[] getFlashBytes() {
byte [] head = BytesUtil.concatAll(BytesUtil.getBytesWord(aUnitNumber, 4), BytesUtil.getBytesWord(getDataLength(),4));
if (aUnitData == null) return head;
return BytesUtil.concatAll(head,aUnitData);
}
public byte[] getUnitData() {
return this.aUnitData;
}
public int getDataLength() {
if (aUnitData==null) return 0;
return aUnitData.length;
}
public long getUnitNumber() {
return this.aUnitNumber;
}
public boolean equals(Object object) {
boolean bl = false;
if (object instanceof TAUnit) {
TAUnit tAUnit = (TAUnit)object;
if (tAUnit.aUnitNumber == this.aUnitNumber) {
bl = Arrays.equals(tAUnit.aUnitData, this.aUnitData);
}
}
return bl;
}
public String getUnitHex() {
return HexDump.toHex(aUnitNumber);
}
public String toString() {
String result = HexDump.toHex(aUnitNumber) + " " + HexDump.toHex((short)getDataLength()) + " ";
try {
ByteArrayInputStream is = new ByteArrayInputStream(aUnitData);
byte[] part = new byte[16];
int nbread = is.read(part);
result += HexDump.toHex(BytesUtil.getReply(part, nbread));
while ((nbread=is.read(part))>0) {
result+="\n "+HexDump.toHex(BytesUtil.getReply(part, nbread));
}
} catch (Exception e) {}
return result;
}
} | 1,878 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
TAFileParseException.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/ta/TAFileParseException.java | package org.flashtool.parsers.ta;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TAFileParseException
extends Exception {
private static final long serialVersionUID = 1;
public TAFileParseException(String string) {
super(string);
}
}
| 265 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
TARawBlock.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/ta/TARawBlock.java | package org.flashtool.parsers.ta;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Vector;
import org.flashtool.util.HexDump;
import com.igormaznitsa.jbbp.JBBPParser;
import com.igormaznitsa.jbbp.io.JBBPBitInputStream;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TARawBlock {
@Bin public int magic;
@Bin public int hash;
@Bin public byte unknown;
@Bin public byte partnumber;
@Bin public byte partition;
@Bin public byte numblocks;
@Bin public byte[] units;
Vector<TAUnit> unitList = null;
public String toString() {
return "Magic : " + HexDump.toHex(magic) + " unknown : "+unknown+" partnumber : "+partnumber+" partition : "+partition+" numblocks : "+numblocks;
}
public void parseUnits() throws IOException {
unitList = new Vector<TAUnit>();
JBBPParser unitblock = JBBPParser.prepare(
" <int unitNumber;"
+ "<int length;"
+ "<int magic;"
+ "<int unknown;"
);
JBBPBitInputStream unitsStream = new JBBPBitInputStream(new ByteArrayInputStream(units));
try {
while (unitsStream.hasAvailableData()) {
TARawUnit rawunit = unitblock.parse(unitsStream).mapTo(new TARawUnit());
rawunit.fetchContent(unitsStream);
if (rawunit.isValid()) unitList.add(rawunit.getUnit());
}
} catch (Exception ioe) {}
unitsStream.close();
}
public Vector<TAUnit> getUnits() {
return unitList;
}
} | 1,538 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
TARawUnit.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/ta/TARawUnit.java | package org.flashtool.parsers.ta;
import java.io.IOException;
import org.flashtool.util.HexDump;
import com.igormaznitsa.jbbp.io.JBBPBitInputStream;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TARawUnit {
@Bin public int unitNumber;
@Bin public int length;
@Bin public int magic;
@Bin public int unknown;
TAUnit unit=null;
public void fetchContent(JBBPBitInputStream stream) throws IOException {
if (magic==0x3BF8E9C1) {
unit = new TAUnit(unitNumber,stream.readByteArray(length));
if (length % 4 != 0) {
stream.skip(4 - length % 4);
}
}
}
public boolean isValid() {
return (magic==0x3BF8E9C1);
}
public String toString() {
return unit.toString();
}
public TAUnit getUnit() {
return unit;
}
} | 801 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
SinFile.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/SinFile.java | package org.flashtool.parsers.sin;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.flashtool.flashsystem.Category;
import org.rauschig.jarchivelib.ArchiveFormat;
import org.rauschig.jarchivelib.Archiver;
import org.rauschig.jarchivelib.ArchiverFactory;
import org.rauschig.jarchivelib.CompressionType;
import com.igormaznitsa.jbbp.JBBPParser;
import com.igormaznitsa.jbbp.io.JBBPBitInputStream;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SinFile {
File sinfile=null;
int version=0;
JBBPBitInputStream sinStream = null;
FileInputStream fin = null;
BufferedInputStream bin = null;
private long packetsize=0;
private long nbchunks=0;
private long filesize;
long totalread = 0;
int partcount=0;
File unpackFolder=null;
public org.flashtool.parsers.sin.v1.SinParser sinv1 = null;
public org.flashtool.parsers.sin.v2.SinParser sinv2 = null;
public org.flashtool.parsers.sin.v3.SinParser sinv3 = null;
public org.flashtool.parsers.sin.v4.SinParser sinv4 = null;
public SinFile(File f) throws SinFileException {
sinfile = f;
JBBPParser sinParserV1 = JBBPParser.prepare(
"byte multipleHeaders;"
+ "int headerLen;"
+ "byte payloadType;"
+ "short unknown;"
+ "byte memId;"
+ "byte compression;"
+ "int hashLen;"
);
JBBPParser sinParserV2 = JBBPParser.prepare(
"byte multipleHeaders;"
+ "int headerLen;"
+ "byte payloadType;"
+ "short unknown;"
+ "byte memId;"
+ "byte compression;"
+ "int hashLen;"
);
JBBPParser sinParserV3 = JBBPParser.prepare(
"byte[3] magic;"
+ "int headerLen;"
+ "int payloadType;"
+ "int hashType;"
+ "int reserved;"
+ "int hashLen;"
);
JBBPParser sinParserv4 = JBBPParser.prepare(
"byte[2] magic;"
);
try {
openStreams();
version = sinStream.readByte();
if (version==1) {
sinv1 = sinParserV1.parse(sinStream).mapTo(new org.flashtool.parsers.sin.v1.SinParser());
sinv1.setLength(sinfile.length());
sinv1.setFile(sinfile);
if (sinv1.hashLen>sinv1.headerLen) throw new SinFileException("Error parsing sin file");
sinv1.parseHash(sinStream);
closeStreams();
}
if (version==2) {
sinv2 = sinParserV2.parse(sinStream).mapTo(new org.flashtool.parsers.sin.v2.SinParser());
sinv2.setLength(sinfile.length());
sinv2.setFile(sinfile);
if (sinv2.hashLen>sinv2.headerLen) throw new SinFileException("Error parsing sin file");
sinv2.parseHash(sinStream);
closeStreams();
}
if (version==3) {
sinv3 = sinParserV3.parse(sinStream).mapTo(new org.flashtool.parsers.sin.v3.SinParser());
sinv3.setLength(sinfile.length());
sinv3.setFile(sinfile);
if (!new String(sinv3.magic).equals("SIN")) throw new SinFileException("Error parsing sin file");
if (sinv3.hashLen>sinv3.headerLen) throw new SinFileException("Error parsing sin file");
sinv3.parseHash(sinStream);
openStreams();
sinStream.skip(sinv3.headerLen);
sinv3.parseDataHeader(sinStream);
closeStreams();
} else {
closeStreams();
version=4;
sinv4 = new org.flashtool.parsers.sin.v4.SinParser(sinfile);
}
} catch (Exception ioe) {
closeStreams();
throw new SinFileException(ioe.getMessage());
}
}
public File getFile() {
return sinfile;
}
public byte[] getHeader() throws IOException {
if (sinv1!=null) {
return sinv1.getHeader();
}
if (sinv2!=null) {
return sinv2.getHeader();
}
if (sinv3!=null) {
return sinv3.getHeader();
}
if (sinv4!=null) {
return sinv4.getHeader();
}
return null;
}
public byte getPartitionType() {
if (sinv1!=null) {
return sinv1.payloadType;
}
if (sinv2!=null) {
return sinv2.payloadType;
}
if (sinv3!=null) {
return (byte)sinv3.payloadType;
}
return 0;
}
public String getPartypeString() {
if (getPartitionType()==0x09)
return "Without spare";
if (getPartitionType()==0x0A)
return "With spare";
if (getPartitionType()==0x20)
return "Loader";
if (getPartitionType()==0)
return "Loader";
if (getPartitionType()==3)
return "Boot";
if (getPartitionType()==0x24)
return "MBR";
if (getPartitionType()==14)
return "MBR";
if (getPartitionType()==15)
return "Without spare";
if (getPartitionType()==0x27)
return "MMC";
return String.valueOf(getPartitionType());
}
public void closeStreams() {
try {
sinStream.close();
} catch (Exception e) {}
try {
fin.close();
} catch (Exception e) {}
try {
bin.close();
} catch (Exception e) {}
}
public void openStreams() throws FileNotFoundException, IOException {
closeStreams();
fin=new FileInputStream(sinfile);
sinStream = new JBBPBitInputStream(fin);
}
public String getName() {
return sinfile.getName();
}
public int getVersion() {
return version;
}
public String toString() {
StringBuilder builder = new StringBuilder();
if (version==1) {
builder.append("Version : "+version+"\n"
+ "Multiple Headers : "+sinv1.multipleHeaders+"\n"
+ "Header Length : "+sinv1.headerLen+"\n"
+ "PayLoad Type : "+sinv1.payloadType+"\n"
+ "Mem Id : "+sinv1.memId+"\n"
+ "Compression : "+sinv1.compression+"\n"
+ "Hash Length : "+sinv1.hashLen+"\n"
+ "Cert Length "+sinv1.certLen+"\n");
}
if (version==2) {
builder.append("Version : "+version+"\n"
+ "Multiple Headers : "+sinv2.multipleHeaders+"\n"
+ "Header Length : "+sinv2.headerLen+"\n"
+ "PayLoad Type : "+sinv2.payloadType+"\n"
+ "Mem Id : "+sinv2.memId+"\n"
+ "Compression : "+sinv2.compression+"\n"
+ "Hash Length : "+sinv2.hashLen+"\n"
+ "Cert Length "+sinv2.certLen+"\n");
}
if (version==3) {
builder.append("Version : "+version+"\nMagic : "+new String(sinv3.magic)+"\nHeader Length : "+sinv3.headerLen+"\nPayLoad Type : "+sinv3.payloadType+"\nHash type : "+sinv3.hashType+"\nReserved : "+sinv3.reserved+"\nHashList Length : "+sinv3.hashLen+" ("+sinv3.blocks.blocks.length+" hashblocks) \nCert len : "+sinv3.certLen+"\n");
}
return builder.toString();
}
public String getType() {
if (sinv1!=null) {
if (new String(sinv1.cert).contains("S1_Loader")) return "LOADER";
if (new String(sinv1.cert).contains("S1_Boot")) return "BOOT";
}
if (sinv2!=null) {
if (new String(sinv2.cert).contains("S1_Loader")) return "LOADER";
if (new String(sinv2.cert).contains("S1_Boot")) return "BOOT";
}
if (sinv3!=null) {
if (new String(sinv3.cert).contains("S1_Loader")) return "LOADER";
if (new String(sinv3.cert).contains("S1_Boot")) return "BOOT";
}
return "";
}
public int getHeaderLength() {
if (sinv1!=null) {
return sinv1.headerLen;
}
if (sinv2!=null) {
return sinv2.headerLen;
}
if (sinv3!=null) {
return sinv3.headerLen;
}
return 0;
}
public boolean hasPartitionInfo() {
if (sinv1!=null) {
return sinv1.hasPartitionInfo();
}
if (sinv2!=null) {
return sinv2.hasPartitionInfo();
}
if (sinv3!=null) {
return sinv3.hasPartitionInfo();
}
return false;
}
public byte[] getPartitionInfo() throws IOException {
if (hasPartitionInfo()) {
if (sinv1!=null) {
return sinv1.getPartitionInfo();
}
if (sinv2!=null) {
return sinv2.getPartitionInfo();
}
if (sinv3!=null) {
return sinv3.getPartitionInfo();
}
return null;
}
else return null;
}
public int getDataOffset() {
if (sinv1!=null) {
return sinv1.headerLen;
}
if (sinv2!=null) {
return sinv2.headerLen;
}
if (sinv3!=null) {
return sinv3.getDataOffset();
}
return 0;
}
public String getDataType() throws IOException {
if (sinv1!=null) {
return sinv1.getDataType();
}
if (sinv2!=null) {
return sinv2.getDataType();
}
if (sinv3!=null) {
return sinv3.getDataType();
}
return "";
}
public long getDataSize() throws IOException{
if (sinv1!=null) {
return sinv1.getDataSize()/1024/1024;
}
if (sinv2!=null) {
return sinv2.getDataSize();
}
if (sinv3!=null) {
return sinv3.getDataSize();
}
return 0;
}
public void dumpImage() throws IOException{
if (sinv1!=null) {
sinv1.dumpImage();
}
if (sinv2!=null) {
sinv2.dumpImage();
}
if (sinv3!=null) {
sinv3.dumpImage();
}
if (sinv4!=null) {
log.error("This sin version is not yet supported");
}
return;
}
public void dumpHeader() throws IOException {
if (sinv1!=null) {
return;
}
if (sinv2!=null) {
sinv2.dumpHeader();
}
if (sinv3!=null) {
sinv3.dumpHeader();
}
if (sinv4!=null) {
log.error("This sin version is not yet supported");
}
return;
}
public String getShortName() {
return SinFile.getShortName(this.getName());
}
public static String getShortName(String pname) {
String name = pname;
int extpos = name.lastIndexOf(".");
if (name.toUpperCase().endsWith(".TA")) {
if (extpos!=-1)
name = name.substring(0,extpos);
return name;
}
if (extpos!=-1) {
name = name.substring(0,extpos);
}
if (name.indexOf("_AID")!=-1)
name = name.substring(0, name.indexOf("_AID"));
if (name.indexOf("_PLATFORM")!=-1)
name = name.substring(0, name.indexOf("_PLATFORM"));
if (name.indexOf("_S1")!=-1)
name = name.substring(0, name.indexOf("_S1"));
if (name.indexOf("_X-")!=-1)
name = name.substring(0, name.indexOf("_X-"));
if (name.indexOf("_X_BOOT")!=-1)
name = name.substring(0, name.indexOf("_X_BOOT"));
if (name.indexOf("_X_Boot")!=-1)
name = name.substring(0, name.indexOf("_X_Boot"));
if (name.indexOf("-LUN")!=-1)
name = name.substring(0, name.indexOf("-LUN")+5);
if (name.toUpperCase().matches("^PARTITION-IMAGE_[0-9]+"))
name = "partition-image";
if (name.startsWith("elabel"))
name = "elabel";
//if (name.indexOf("-")!=-1)
//name = name.substring(0, name.indexOf("-"));
return name;
}
public void setChunkSize(long size) {
packetsize=size;
filesize=sinfile.length()-getHeaderLength();
try {
nbchunks = filesize/packetsize;
if (filesize%packetsize>0) nbchunks++;
} catch (Exception e) {}
}
public long getChunkSize() {
return packetsize;
}
public long getNbChunks() throws IOException {
return nbchunks;
}
public void openForSending() throws IOException {
fin = new FileInputStream(sinfile);
bin = new BufferedInputStream(fin);
bin.skip(getHeaderLength());
totalread=getHeaderLength();
partcount=0;
}
public boolean hasData() throws IOException {
return totalread < sinfile.length();
}
public void closeFromSending() {
try {
bin.close();
fin.close();
} catch (Exception e) {}
}
public byte[] getNextChunk() throws IOException {
long remaining = sinfile.length()-totalread;
long bufsize=(remaining<packetsize)?remaining:packetsize;
byte[] buf = new byte[(int)bufsize];
int read = bin.read(buf);
totalread+=bufsize;
partcount++;
return buf;
}
public void unpackContent() throws IOException {
if (getVersion()==4) {
Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP);
unpackFolder=new File(sinfile.getParent()+File.separator+Category.getCategoryFromName(sinfile.getName()));
unpackFolder.mkdirs();
log.info("Extracting sin content to "+Category.getCategoryFromName(sinfile.getName()));
archiver.extract(sinfile.getAbsoluteFile(), unpackFolder);
}
}
public String getPartitionName() {
if (getVersion()==4) {
Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP);
try {
String content = archiver.stream(sinfile).getNextEntry().getName();
return content.substring(0, content.lastIndexOf("."));
} catch (IOException ioe) {
return "";
}
}
return "";
}
public TarArchiveInputStream getTarInputStream() throws FileNotFoundException, IOException {
if (sinv4.isGZipped())
return new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(sinfile)));
else
return new TarArchiveInputStream(new FileInputStream(sinfile));
}
} | 12,593 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
SinFileException.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/SinFileException.java | package org.flashtool.parsers.sin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SinFileException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public SinFileException(String msg){
super(msg);
}
public SinFileException(String msg, Throwable t){
super(msg,t);
}
} | 341 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
DataHeader.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/v3/DataHeader.java | package org.flashtool.parsers.sin.v3;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DataHeader {
@Bin public byte[] mmcfMagic;
@Bin public int mmcfLen;
@Bin public byte[] gptpMagic;
@Bin public int gptpLen;
@Bin public byte[] gptpuid;
}
| 294 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
AddrBlock.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/v3/AddrBlock.java | package org.flashtool.parsers.sin.v3;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Bin
public class AddrBlock {
public int blockLen;
public long dataOffset;
public long fileOffset;
public long dataLen;
public int hashType;
public byte[] checksum;
}
| 295 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
SinParser.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/v3/SinParser.java | package org.flashtool.parsers.sin.v3;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Vector;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;
import org.flashtool.logger.LogProgress;
import org.flashtool.parsers.sin.v1.PartitionInfo;
import org.flashtool.system.OS;
import org.flashtool.util.BytesUtil;
import com.igormaznitsa.jbbp.JBBPParser;
import com.igormaznitsa.jbbp.io.JBBPBitInputStream;
import com.igormaznitsa.jbbp.io.JBBPByteOrder;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SinParser {
static byte[] hashv3len = {0, 0, 32};
@Bin public byte[] magic;
@Bin public int headerLen;
@Bin public int payloadType;
@Bin public int hashType;
@Bin public int reserved;
@Bin public int hashLen;
public byte[] hashBlocks;
public int certLen;
public byte[] cert;
//public byte[] dheader;
public HashBlocks blocks;
public DataHeader dataHeader;
public Vector<Object> dataBlocks;
public long size;
private File sinfile;
private long dataSize=0L;
public byte[] partitioninfo = null;
String dataType;
public void setFile(File f) {
sinfile=f;
}
public void parseHash(JBBPBitInputStream sinStream) throws IOException {
hashBlocks = sinStream.readByteArray(hashLen);
certLen = sinStream.readInt(JBBPByteOrder.BIG_ENDIAN);
cert = sinStream.readByteArray(certLen);
JBBPParser hashBlocksV3 = JBBPParser.prepare(
"blocks[_] {int length;"
+ "byte["+hashv3len[hashType]+"] crc;}"
);
blocks = hashBlocksV3.parse(hashBlocks).mapTo(new org.flashtool.parsers.sin.v3.HashBlocks());
}
public void parseDataHeader(JBBPBitInputStream sinStream) throws IOException {
JBBPParser dataHeaderParser = JBBPParser.prepare(
"byte[4] mmcfMagic;"
+ "int mmcfLen;"
+ "byte[4] gptpMagic;"
+ "int gptpLen;"
+ "byte[gptpLen-8] gptpuid;"
);
JBBPParser addrBlocksParser = JBBPParser.prepare(
"int blockLen;"
+ ">long dataOffset;"
+ ">long dataLen;"
+ ">long fileOffset;"
+ "int hashType;"
+ "byte[blockLen-36] checksum;"
);
JBBPParser LZ4ABlocksParser = JBBPParser.prepare(
"int blockLen;"
+ ">long dataOffset;"
+ ">long uncompDataLen;"
+ ">long compDataLen;"
+ ">long fileOffset;"
+ ">long reserved;"
+ "int hashType;"
+ "byte[blockLen-52] checksum;"
);
// First hash block seems to be Data header (addr map)
//dheader = sinStream.readByteArray(blocks.blocks[0].length);
//JBBPBitInputStream dheaderStream = new JBBPBitInputStream(new ByteArrayInputStream(dheader));
try {
byte[] mmcfmagic = new byte[4];
sinStream.read(mmcfmagic);
if (!new String(mmcfmagic).equals("MMCF")) throw new Exception("No MMCF");
sinStream.skip(-4);
dataHeader = dataHeaderParser.parse(sinStream).mapTo(new DataHeader());
} catch (Exception e) {
dataHeader = new DataHeader();
dataHeader.mmcfMagic=new String("NULL").getBytes();
dataHeader.gptpLen=0;
dataHeader.mmcfLen=0;
}
if (new String(dataHeader.mmcfMagic).equals("MMCF")) {
long addrLength = dataHeader.mmcfLen-dataHeader.gptpLen;
long read=0;
byte[] amagic = new byte[4];
dataBlocks = new Vector<Object>();
while (read<addrLength) {
sinStream.read(amagic);
read+=4;
if (new String(amagic).equals("ADDR")) {
AddrBlock addrBlock = addrBlocksParser.parse(sinStream).mapTo(new AddrBlock());
dataBlocks.add(addrBlock);
read+=(addrBlock.blockLen-4);
}
if (new String(amagic).equals("LZ4A")) {
LZ4ABlock lz4aBlock = LZ4ABlocksParser.parse(sinStream).mapTo(new LZ4ABlock());
dataBlocks.add(lz4aBlock);
read+=(lz4aBlock.blockLen-4);
}
}
}
else {
dataHeader = new DataHeader();
dataHeader.gptpLen=0;
dataHeader.mmcfLen=0;
}
dataType=getDataTypePriv();
dataSize = getDataSizePriv();
}
public void setLength(long s) {
size=s;
}
public long getDataSizePriv() throws IOException {
if (dataSize>0) return dataSize;
if (dataHeader.mmcfLen>0) {
Object last = dataBlocks.lastElement();
if (last instanceof AddrBlock)
return ((AddrBlock)last).fileOffset+((AddrBlock)last).dataLen;
else
return ((LZ4ABlock)last).fileOffset+((LZ4ABlock)last).uncompDataLen;
}
else {
long size=0;
for (int i=0;i<this.blocks.blocks.length;i++) {
size+=this.blocks.blocks[i].length;
}
return size;
}
}
public String getDataTypePriv(byte[] res) throws IOException {
if (BytesUtil.startsWith(res, new byte[] {0x7F,0x45,0x4C,0x46})) return "elf";
int pos = BytesUtil.indexOf(res, new byte[]{(byte)0x53,(byte)0xEF,(byte)0x01,(byte)0x00});
if (pos==-1) return "unknown";
pos = pos - 56;
byte[] header = new byte[58];
System.arraycopy(res, pos, header, 0, header.length);
byte[] bcount = new byte[4];
System.arraycopy(header, 4, bcount, 0, bcount.length);
BytesUtil.revert(bcount);
long blockcount = BytesUtil.getInt(bcount);
dataSize = blockcount*4L*1024L;
return "ext4";
}
public String getDataTypePriv() throws IOException {
RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
byte[] res=null;
byte[] rescomp=null;
if (dataHeader.mmcfLen>0) {
Object block = dataBlocks.firstElement();
if (block instanceof AddrBlock) {
res = new byte[(int)((AddrBlock)block).dataLen];
fin.seek(getDataOffset()+((AddrBlock)block).dataOffset);
fin.read(res);
fin.close();
}
else {
rescomp = new byte[(int)((LZ4ABlock)block).compDataLen];
fin.seek(getDataOffset()+((LZ4ABlock)block).dataOffset);
fin.read(rescomp);
fin.close();
LZ4Factory factory = LZ4Factory.fastestInstance();
LZ4FastDecompressor decomp = factory.fastDecompressor();
res = decomp.decompress(rescomp, (int)((LZ4ABlock)block).uncompDataLen);
}
}
else {
res = new byte[blocks.blocks[0].length];
fin.seek(getDataOffset());
fin.read(res);
fin.close();
}
return getDataTypePriv(res);
}
public boolean hasPartitionInfo() {
return false;
}
public byte[] getPartitionInfo() {
return null;
}
public long getDataSize() {
return dataSize;
}
public String getDataType() {
return dataType;
}
public void dumpImage() throws IOException{
RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
int count = 0;
int bcount=0;
if (dataHeader.mmcfLen>0)
bcount = dataBlocks.size();
else
bcount = blocks.blocks.length;
String ext = "."+dataType;
String foutname = sinfile.getAbsolutePath().substring(0, sinfile.getAbsolutePath().length()-4)+ext;
log.info("Generating empty container file");
RandomAccessFile fout = OS.generateEmptyFile(foutname, dataSize, (byte)0xFF);
if (fout!=null) {
log.info("Container generated. Now extracting data to container");
LogProgress.initProgress(bcount);
long srcoffset=0;
long destoffset=0;
long dataLen=0;
LZ4Factory factory = LZ4Factory.fastestInstance();
LZ4FastDecompressor decomp = factory.fastDecompressor();
long uncompLen=0;
for (int i=0;i<bcount;i++) {
if (dataHeader.mmcfLen>0) {
Object objblock = dataBlocks.elementAt(i);
if (objblock instanceof AddrBlock) {
AddrBlock block = (AddrBlock)objblock;
srcoffset=getDataOffset()+block.dataOffset;
destoffset=block.fileOffset;
dataLen=block.dataLen;
uncompLen=0;
}
else {
LZ4ABlock block = (LZ4ABlock)objblock;
srcoffset=getDataOffset()+block.dataOffset;
destoffset=block.fileOffset;
dataLen=block.compDataLen;
uncompLen=block.uncompDataLen;
}
}
else {
HashBlock block = blocks.blocks[i];
if (i>0) srcoffset=srcoffset+blocks.blocks[i-1].length;
else srcoffset=getDataOffset();
destoffset=srcoffset-getDataOffset();
dataLen=block.length;
}
fin.seek(srcoffset);
fout.seek(destoffset);
byte[] data = new byte[(int)dataLen];
int nbread = fin.read(data);
if (uncompLen>0) {
byte[] res = factory.fastDecompressor().decompress(data,(int)uncompLen);
fout.write(res);
}
else
fout.write(data);
LogProgress.updateProgress();
}
fout.close();
fin.close();
LogProgress.initProgress(0);
log.info("Extraction finished to "+foutname);
}
else {
log.error("An error occured while generating container");
}
}
public void dumpHeader() throws IOException {
RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
String foutname = sinfile.getAbsolutePath().substring(0, sinfile.getAbsolutePath().length()-4)+".header";
RandomAccessFile fout = new RandomAccessFile(foutname,"rw");
byte[] buff = new byte[headerLen];
fin.read(buff);
fout.write(buff);
fout.close();
fin.close();
log.info("Extraction finished to "+foutname);
}
public byte[] getHeader() throws IOException {
RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
byte[] buff = new byte[headerLen];
fin.read(buff);
fin.close();
return buff;
}
public int getDataOffset() {
if (dataHeader.mmcfLen>0)
return headerLen+dataHeader.mmcfLen+8;
else
return headerLen;
}
}
| 9,609 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
HashBlocks.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/v3/HashBlocks.java | package org.flashtool.parsers.sin.v3;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Bin
public class HashBlocks {
public HashBlock [] blocks;
}
| 189 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
LZ4ABlock.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/v3/LZ4ABlock.java | package org.flashtool.parsers.sin.v3;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Bin
public class LZ4ABlock {
public int blockLen;
public long dataOffset;
public long uncompDataLen;
public long compDataLen;
public long fileOffset;
public long reserved;
public int hashType;
public byte[] checksum;
} | 349 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
HashBlock.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/v3/HashBlock.java | package org.flashtool.parsers.sin.v3;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class HashBlock {
@Bin public int length;
@Bin public byte[] crc;
}
| 199 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
SinParser.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/v1/SinParser.java | package org.flashtool.parsers.sin.v1;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.flashtool.logger.LogProgress;
import org.flashtool.parsers.sin.v2.HashBlock;
import org.flashtool.parsers.sin.v2.HashBlocks;
import org.flashtool.system.OS;
import org.flashtool.util.BytesUtil;
import com.igormaznitsa.jbbp.JBBPParser;
import com.igormaznitsa.jbbp.io.JBBPBitInputStream;
import com.igormaznitsa.jbbp.io.JBBPByteOrder;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SinParser {
@Bin public byte multipleHeaders;
@Bin public int headerLen;
@Bin public byte payloadType;
@Bin public short unknown;
@Bin public byte memId;
@Bin public byte compression;
@Bin public int hashLen;
public HashBlocks blocks;
public PartitionInfo parti;
public int certLen;
public byte[] cert;
public byte[] partitioninfo = null;
private File sinfile;
private long size;
private long dataSize=0L;
String dataType;
public void parseHash(JBBPBitInputStream sinStream) throws IOException {
JBBPParser hashBlocksV2 = JBBPParser.prepare(
"block[_] {int offset;"
+ "int length;"
+ "byte hashLen;"
+ "byte[hashLen] crc;}"
);
if (hashLen>0) {
byte[] hashBlocks = sinStream.readByteArray(hashLen);
blocks = hashBlocksV2.parse(hashBlocks).mapTo(new org.flashtool.parsers.sin.v2.HashBlocks());
certLen = sinStream.readInt(JBBPByteOrder.BIG_ENDIAN);
cert = sinStream.readByteArray(certLen);
if (blocks.block.length==1 && blocks.block[0].offset!=0) blocks.block[0].offset=0;
if (blocks.block[0].length==16) {
partitioninfo = sinStream.readByteArray(16);
JBBPParser partInfo = JBBPParser.prepare(
"<int mot1;"
+ "<int mot2;"
+ "<int offset;"
+ "<int blockcount;"
);
parti = partInfo.parse(partitioninfo).mapTo(new org.flashtool.parsers.sin.v1.PartitionInfo());
if (blocks.block.length>1)
dataSize=parti.blockcount*blocks.block[1].length;
}
blocks.setSpare(this.payloadType);
}
dataType=getDataTypePriv();
}
public void setFile(File f) {
sinfile = f;
}
public void setLength(long s) {
size=s;
}
public String getDataType() {
return dataType;
}
public long getDataSize() {
return dataSize;
}
public byte[] getHeader() throws IOException {
RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
byte[] buff = new byte[headerLen];
fin.read(buff);
fin.close();
return buff;
}
public boolean hasPartitionInfo() {
return partitioninfo!=null;
}
public byte[] getPartitionInfo() throws IOException {
return partitioninfo;
}
public String getDataTypePriv(byte[] res) throws IOException {
if (BytesUtil.startsWith(res, new byte[] {0x7F,0x45,0x4C,0x46})) return "elf";
if (BytesUtil.startsWith(res, new byte[] {0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, (byte)0xFF, (byte)0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})) return "yaffs2";
int pos = BytesUtil.indexOf(res, new byte[]{(byte)0x53,(byte)0xEF,(byte)0x01,(byte)0x00});
if (pos==-1) return "unknown";
pos = pos - 56;
byte[] header = new byte[58];
System.arraycopy(res, pos, header, 0, header.length);
byte[] bcount = new byte[4];
System.arraycopy(header, 4, bcount, 0, bcount.length);
BytesUtil.revert(bcount);
long blockcount = BytesUtil.getInt(bcount);
dataSize = blockcount*4L*1024L;
return "ext4";
}
public String getDataTypePriv() throws IOException {
RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
byte[] res=null;
fin.seek(headerLen);
if (hashLen==0) {
res = new byte[(int)size-headerLen];
fin.read(res);
}
else {
int i=0;
while (i < blocks.block.length && blocks.block[i].offset==0 ) {
res = new byte[blocks.block[i].length];
fin.read(res);
i++;
}
}
fin.close();
return getDataTypePriv(res);
}
public void dumpImage() throws IOException {
try {
RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
log.info("Generating container file");
String ext = "."+getDataType();
String foutname = sinfile.getAbsolutePath().substring(0, sinfile.getAbsolutePath().length()-4)+ext;
RandomAccessFile fout = OS.generateEmptyFile(foutname, dataSize, (byte)0xFF);
log.info("Finished Generating container file");
// Positionning in files
log.info("Extracting data into container");
fin.seek(headerLen);
LogProgress.initProgress(blocks.block.length);
for (int i=0;i<blocks.block.length;i++) {
HashBlock b = blocks.block[i];
byte[] data = new byte[b.length];
fin.read(data);
if (!b.validate(data)) throw new Exception("Corrupted data");
fout.seek(blocks.block.length==1?0:b.offset);
fout.write(data);
LogProgress.updateProgress();
}
LogProgress.initProgress(0);
fout.close();
log.info("Extraction finished to "+foutname);
}
catch (Exception e) {
log.error("Error while extracting data : "+e.getMessage());
LogProgress.initProgress(0);
e.printStackTrace();
}
}
} | 5,328 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
PartitionInfo.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/v1/PartitionInfo.java | package org.flashtool.parsers.sin.v1;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PartitionInfo {
@Bin public int mot1;
@Bin public int mot2;
@Bin public int offset;
@Bin public int blockcount;
}
| 261 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
SinParser.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/v2/SinParser.java | package org.flashtool.parsers.sin.v2;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Vector;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;
import org.flashtool.logger.LogProgress;
import org.flashtool.parsers.sin.v1.PartitionInfo;
import org.flashtool.parsers.sin.v3.AddrBlock;
import org.flashtool.parsers.sin.v3.LZ4ABlock;
import org.flashtool.system.OS;
import org.flashtool.util.BytesUtil;
import com.igormaznitsa.jbbp.JBBPParser;
import com.igormaznitsa.jbbp.io.JBBPBitInputStream;
import com.igormaznitsa.jbbp.io.JBBPByteOrder;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SinParser {
@Bin public byte multipleHeaders;
@Bin public int headerLen;
@Bin public byte payloadType;
@Bin public short unknown;
@Bin public byte memId;
@Bin public byte compression;
@Bin public int hashLen;
public HashBlocks blocks;
public PartitionInfo parti;
public int certLen;
public byte[] cert;
private File sinfile;
private long size;
private long dataSize=0L;
String dataType;
public void setFile(File f) {
sinfile = f;
}
public void setLength(long s) {
size=s;
}
public void parseHash(JBBPBitInputStream sinStream) throws IOException {
JBBPParser hashBlocksV2 = JBBPParser.prepare(
"block[_] {int offset;"
+ "int length;"
+ "byte hashLen;"
+ "byte[hashLen] crc;}"
);
if (hashLen>0) {
byte[] hashBlocks = sinStream.readByteArray(hashLen);
blocks = hashBlocksV2.parse(hashBlocks).mapTo(new org.flashtool.parsers.sin.v2.HashBlocks());
certLen = sinStream.readInt(JBBPByteOrder.BIG_ENDIAN);
cert = sinStream.readByteArray(certLen);
if (blocks.block.length==1 && blocks.block[0].offset!=0) blocks.block[0].offset=0;
if (blocks.block[0].length==16) {
byte[] partinfo = sinStream.readByteArray(16);
JBBPParser partInfo = JBBPParser.prepare(
"<int mot1;"
+ "<int mot2;"
+ "<int offset;"
+ "<int blockcount;"
);
parti = partInfo.parse(partinfo).mapTo(new org.flashtool.parsers.sin.v1.PartitionInfo());
}
}
dataType=getDataTypePriv();
dataSize = getDataSizePriv();
}
public byte[] getHeader() throws IOException {
RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
byte[] buff = new byte[headerLen];
fin.read(buff);
fin.close();
return buff;
}
public boolean hasPartitionInfo() {
return blocks.block[0].length==16 && blocks.block.length>1;
}
public byte[] getPartitionInfo() throws IOException {
RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
byte[] buff = new byte[blocks.block[0].length];
fin.seek(headerLen+blocks.block[0].offset);
fin.read(buff);
fin.close();
return buff;
}
public long getDataSizePriv() throws IOException {
if (dataSize>0) return dataSize;
if (hashLen==0) dataSize=size-headerLen;
else {
HashBlock last = blocks.block[blocks.block.length-1];
dataSize=last.offset+last.length;
}
return dataSize;
}
public String getDataTypePriv(byte[] res) throws IOException {
if (BytesUtil.startsWith(res, new byte[] {0x7F,0x45,0x4C,0x46})) return "elf";
int pos = BytesUtil.indexOf(res, new byte[]{(byte)0x53,(byte)0xEF,(byte)0x01,(byte)0x00});
if (pos==-1) return "unknown";
pos = pos - 56;
byte[] header = new byte[58];
System.arraycopy(res, pos, header, 0, header.length);
byte[] bcount = new byte[4];
System.arraycopy(header, 4, bcount, 0, bcount.length);
BytesUtil.revert(bcount);
long blockcount = BytesUtil.getInt(bcount);
dataSize = blockcount*4L*1024L;
return "ext4";
}
public String getDataTypePriv() throws IOException {
RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
byte[] res=null;
fin.seek(headerLen);
if (hashLen==0) {
res = new byte[(int)size-headerLen];
fin.read(res);
}
else {
int i=0;
while (i < blocks.block.length && blocks.block[i].offset==0 ) {
res = new byte[blocks.block[i].length];
fin.read(res);
i++;
}
}
fin.close();
return getDataTypePriv(res);
}
public long getDataSize() {
return dataSize;
}
public String getDataType() {
return dataType;
}
public void dumpImage() throws IOException {
try {
RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
log.info("Generating container file");
String ext = "."+getDataType();
String foutname = sinfile.getAbsolutePath().substring(0, sinfile.getAbsolutePath().length()-4)+ext;
RandomAccessFile fout = OS.generateEmptyFile(foutname, dataSize, (byte)0xFF);
log.info("Finished Generating container file");
// Positionning in files
log.info("Extracting data into container");
fin.seek(headerLen);
LogProgress.initProgress(blocks.block.length);
for (int i=0;i<blocks.block.length;i++) {
HashBlock b = blocks.block[i];
byte[] data = new byte[b.length];
fin.read(data);
if (!b.validate(data)) throw new Exception("Corrupted data");
fout.seek(blocks.block.length==1?0:b.offset);
fout.write(data);
LogProgress.updateProgress();
}
LogProgress.initProgress(0);
fout.close();
log.info("Extraction finished to "+foutname);
}
catch (Exception e) {
log.error("Error while extracting data : "+e.getMessage());
LogProgress.initProgress(0);
e.printStackTrace();
}
}
public void dumpHeader() throws IOException {
RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
String foutname = sinfile.getAbsolutePath().substring(0, sinfile.getAbsolutePath().length()-4)+".header";
RandomAccessFile fout = new RandomAccessFile(foutname,"rw");
byte[] buff = new byte[headerLen];
fin.read(buff);
fout.write(buff);
fout.close();
fin.close();
log.info("Extraction finished to "+foutname);
}
} | 6,113 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
HashBlocks.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/v2/HashBlocks.java | package org.flashtool.parsers.sin.v2;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Bin
public class HashBlocks {
public HashBlock [] block;
public void setSpare(int sparetype) {
if (sparetype==0x0A && block.length>1 && block[0].length==16) {
int spare = block[1].length%131072;
for (int i=1;i<block.length;i++) {
int newoffset=block[i].offset+(spare*(i-1));
block[i].offset = block[i].offset+(spare*(i-1));
}
}
}
} | 513 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
HashBlock.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/v2/HashBlock.java | package org.flashtool.parsers.sin.v2;
import org.flashtool.system.OS;
import org.flashtool.util.HexDump;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class HashBlock {
@Bin public int offset;
@Bin public int length;
@Bin public byte hashLen;
@Bin public byte[] crc;
public boolean validate(byte[] data) {
String checksum="";
if (hashLen==20)
checksum = OS.getSHA1(data);
if (hashLen==32)
checksum = OS.getSHA256(data);
return checksum.equals(HexDump.toHex(crc));
}
}
| 536 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
PartitionInfo.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/v2/PartitionInfo.java | package org.flashtool.parsers.sin.v2;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PartitionInfo {
@Bin public int mot1;
@Bin public int mot2;
@Bin public int offset;
@Bin public int blockcount;
}
| 261 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
SinParser.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/sin/v4/SinParser.java | package org.flashtool.parsers.sin.v4;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.flashtool.util.CircularByteBuffer;
import org.rauschig.jarchivelib.IOUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SinParser {
private File sinfile;
Map<String, CircularByteBuffer> databuffer = new HashMap<String, CircularByteBuffer>();
public SinParser(File f) throws Exception {
this.sinfile=f;
if (!isTared() && !isGZipped() ) throw new Exception("Not a sin file");
}
public boolean isTared() {
try {
TarArchiveInputStream tarIn = new TarArchiveInputStream(new FileInputStream(sinfile));
try {
while ((tarIn.getNextTarEntry()) != null) {
break;
}
tarIn.close();
return true;
} catch (IOException ioe) {
try { tarIn.close(); } catch (Exception e) {}
return false;
}
} catch (FileNotFoundException fne) {
return false;
}
}
public boolean isGZipped() {
try {
InputStream in = new FileInputStream(sinfile);
if (!in.markSupported()) {
in = new BufferedInputStream(in);
}
in.mark(2);
int magic = 0;
try {
magic = in.read() & 0xff | ((in.read() << 8) & 0xff00);
in.close();
} catch (IOException ioe) {
try {
in.close();
} catch (Exception e) {}
return false;
}
return magic == GZIPInputStream.GZIP_MAGIC;
} catch (FileNotFoundException fne) {
return false;
}
}
public byte[] getHeader() {
try {
TarArchiveEntry entry=null;
TarArchiveInputStream tarIn=null;
if (isGZipped())
tarIn = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(sinfile)));
else
tarIn = new TarArchiveInputStream(new FileInputStream(sinfile));
ByteArrayOutputStream bout = new ByteArrayOutputStream();
while ((entry = tarIn.getNextTarEntry()) != null) {
if (entry.getName().endsWith("cms")) {
IOUtils.copy(tarIn, bout);
break;
}
}
tarIn.close();
return bout.toByteArray();
} catch (Exception e) {
return null;
}
}
public void dumpImage() {
try {
TarArchiveEntry entry=null;
TarArchiveInputStream tarIn=null;
if (isGZipped())
tarIn = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(sinfile)));
else
tarIn = new TarArchiveInputStream(new FileInputStream(sinfile));
FileOutputStream fout = new FileOutputStream(new File("D:\\test.ext4"));
while ((entry = tarIn.getNextTarEntry()) != null) {
if (!entry.getName().endsWith("cms")) {
IOUtils.copy(tarIn, fout);
}
}
tarIn.close();
fout.flush();
fout.close();
log.info("Extraction finished to "+"D:\\test.ext4");
} catch (Exception e) {}
}
} | 3,204 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
FlashCommand.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/simpleusblogger/FlashCommand.java | package org.flashtool.parsers.simpleusblogger;
import java.util.Arrays;
import org.flashtool.libusb.LibUsbException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FlashCommand {
String command = "";
String parameters="";
String lastsubcommand="";
String lastsubparameters="";
byte[] signdata;
byte[] reply;
String sinfile = "";
int unit = 0;
int partition = 0;
public FlashCommand(String command) {
String[] parsed = command.split(":");
this.command = parsed[0];
if (this.command.equals("Read-TA")) {
partition = Integer.parseInt(parsed[1]);
unit = Integer.parseInt(parsed[2]);
}
if (parsed.length>1) {
for (int i=1;i<parsed.length;i++)
parameters=parameters+(parameters.length()==0?"":":")+parsed[i];
}
}
public int getUnit() {
return unit;
}
public int getPartition() {
return partition;
}
public byte[] getReply() {
return reply;
}
public String getCommand() {
return command;
}
public String getFinalCommand() {
if (command.equals("signature"))
return lastsubcommand;
return command;
}
public String getParameters() {
if (command.equals("signature"))
return lastsubparameters+":"+sinfile;
else return parameters;
}
public void setSubCommand(String command) {
lastsubparameters="";
String[] parsed = command.split(":");
this.lastsubcommand = parsed[0];
if (parsed.length>1) {
for (int i=1;i<parsed.length;i++)
lastsubparameters=lastsubparameters+(lastsubparameters.length()==0?"":":")+parsed[i];
}
}
public String getLastSubCommand() {
return lastsubcommand;
}
public void setFile(String file) {
sinfile=file;
}
public void addSignData (byte[] content) {
signdata = Arrays.copyOf(content, content.length);
}
public void addReply (byte[] d) {
reply = d;
}
public String toString() {
return command + " " + lastsubcommand + " " + (signdata!=null?sinfile:""+" "+(reply!=null?new String(reply):""));
}
} | 1,944 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
USBHeader.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/simpleusblogger/USBHeader.java | package org.flashtool.parsers.simpleusblogger;
import org.flashtool.libusb.LibUsbException;
import org.flashtool.util.HexDump;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class USBHeader {
@Bin short usb_Length;
@Bin short usb_Function;
@Bin int usb_Status;
@Bin long usb_UsbDeviceHandle;
@Bin long usb_UsbdFlags;
@Bin long usb_PipeHandle;
@Bin int usb_TransferFlags;
@Bin int usb_TransferBufferLength;
@Bin long usb_TransferBuffer;
@Bin long usb_TransferBufferMDL;
@Bin long usb_UrbLink;
@Bin long usb_hcdendpoint;
@Bin long usb_hcdirp;
@Bin long usb_hcdlistentry;
@Bin long usb_flink;
@Bin long usb_blink;
@Bin long usb_hcdlistentry2;
@Bin long usb_hcdcurrentflushpointer;
@Bin long usb_hcdextension;
public String toString() {
return "header length : "+usb_Length+" / function : "+usb_Function+" / status : "+usb_Status+" / usbdevicehandle "+HexDump.toHex(usb_UsbDeviceHandle)+" / usbdflags : "+usb_UsbdFlags +
" / pipehandle : " + HexDump.toHex(usb_PipeHandle) +
" / transferflag : " + usb_TransferFlags +
" / transferbufferlength : " + usb_TransferBufferLength;
}
} | 1,150 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
USBHeaderExtended.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/simpleusblogger/USBHeaderExtended.java | package org.flashtool.parsers.simpleusblogger;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class USBHeaderExtended {
@Bin byte brmRequestType;
@Bin byte bRequest;
@Bin short wValue;
@Bin short wIndex;
@Bin short wLength;
}
| 275 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
Parser.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/simpleusblogger/Parser.java | package org.flashtool.parsers.simpleusblogger;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.flashtool.libusb.LibUsbException;
import org.flashtool.parsers.sin.SinFile;
import org.flashtool.util.BytesUtil;
import org.flashtool.util.HexDump;
import org.flashtool.util.StreamSearcher;
import org.riversun.bigdoc.bin.BigFileSearcher;
import com.igormaznitsa.jbbp.JBBPParser;
import com.igormaznitsa.jbbp.io.JBBPBitInputStream;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Parser {
static JBBPParser USBRecord = JBBPParser.prepare(
"<long irp;" +
"<int unknown1;" +
"<int recordid;" +
"<int recordlength;" +
"byte[28] reserved2;"
);
static JBBPParser SinHeader = JBBPParser.prepare(
"byte version;" +
"byte[3] magic;" +
"int headerLen;" +
"int payloadType;" +
"int hashType;" +
"int reserved;" +
"int hashLen;"
);
static JBBPParser S1Packet = JBBPParser.prepare(
"byte[4] command;"
+ "byte[4] flag;"
+ "byte[4] length;"
+ "byte headercksum;"
);
//public static byte[] record = new byte[] {(byte)0x80,0x00,0x09,0x00,0x00,0x00,0x00,0x00};
public static Session parse(String usblog, String extractedsin) throws Exception {
Session session = new Session();
S1Packet current=null;
FlashCommand ccurrent=null;
byte[] downloadContent = null;
USBHeader head=null;
FileInputStream fin=new FileInputStream(new File(usblog));
boolean s1parser=true;
StreamSearcher searcher = new StreamSearcher(BytesUtil.getBytes("1B0000001300000000000000"));
long startpos=searcher.search(new FileInputStream(new File(usblog)));
JBBPBitInputStream usbStream = new JBBPBitInputStream(fin);
usbStream.skip(startpos-48);
int recnum = 0;
HashSet<String> set = new HashSet<String>();
while (usbStream.hasAvailableData()) {
USBRecord rec = readRecord(usbStream);
rec.recnum=recnum++;
if (rec.header==null) continue;
if (rec.header.usb_UsbDeviceHandle==0) continue;
if (rec.getDataString().contains("getvar") && s1parser==true) s1parser=false;
if (s1parser==false) {
if (rec.getDirection().equals("WRITE")) {
//if (rec.getDataString().matches("^[A-Za-z].*$") && rec.getData().length<100)
//System.out.println(rec.getDirection()+" : "+rec.getDataString());
if (!rec.getDataString().equals("signature") &&
!rec.getDataString().startsWith("Write-TA:") &&
!rec.getDataString().startsWith("Read-TA:") &&
!rec.getDataString().startsWith("getvar:") &&
!rec.getDataString().equals("powerdown") &&
!rec.getDataString().equals("Sync") &&
!rec.getDataString().equals("Get-emmc-info") &&
!rec.getDataString().startsWith("Getlog") &&
!rec.getDataString().startsWith("set_active:") &&
!rec.getDataString().startsWith("Get-ufs-info") &&
!rec.getDataString().startsWith("Get-gpt-info:") &&
!rec.getDataString().startsWith("flash:") &&
!rec.getDataString().startsWith("erase:") &&
!rec.getDataString().startsWith("download:") &&
!rec.getDataString().startsWith("Repartition:") &&
!rec.getDataString().equals("Get-root-key-hash")) {
downloadContent = rec.getData();
}
if (rec.getDataString().equals("signature") ||
rec.getDataString().startsWith("Write-TA:") ||
rec.getDataString().startsWith("Read-TA:") ||
rec.getDataString().startsWith("getvar:") ||
rec.getDataString().equals("powerdown") ||
rec.getDataString().equals("Sync") ||
rec.getDataString().equals("Get-emmc-info") ||
rec.getDataString().startsWith("Getlog") ||
rec.getDataString().startsWith("set_active:") ||
rec.getDataString().startsWith("Get-ufs-info") ||
rec.getDataString().startsWith("Get-gpt-info:") ||
rec.getDataString().equals("Get-root-key-hash")) {
if (ccurrent!=null) {
session.addCommand(ccurrent);
}
ccurrent = new FlashCommand(rec.getDataString());
if (rec.getDataString().startsWith("signature")) {
ccurrent.addSignData(downloadContent);
ccurrent.setFile(getSin(extractedsin, ccurrent.signdata));
}
}
else {
if (ccurrent.getCommand().startsWith("signature")) {
if (ccurrent.getLastSubCommand().length()==0) {
if (rec.getDataString().startsWith("erase") || rec.getDataString().startsWith("flash") || rec.getDataString().startsWith("Repartition") || rec.getDataString().startsWith("download")) {
ccurrent.setSubCommand(rec.getDataString());
}
else
ccurrent.addSignData(rec.getData());
}
else {
if (rec.getDataString().startsWith("erase") || rec.getDataString().startsWith("flash") || rec.getDataString().startsWith("Repartition")) {
ccurrent.setSubCommand(rec.getDataString());
}
}
}
}
}
else {
if (ccurrent.getCommand().startsWith("Read-TA")) {
if (!rec.getDataString().startsWith("DATA") && !rec.getDataString().startsWith("OKAY") && !rec.getDataString().startsWith("FAIL"))
ccurrent.addReply(rec.getData());
}
if (ccurrent.getCommand().startsWith("getvar")) {
ccurrent.addReply(rec.getData());
}
}
}
else {
if (rec.data.length<13) {
if (current!=null)
current.addData(rec.data);
}
else {
JBBPBitInputStream dataStream = new JBBPBitInputStream(new ByteArrayInputStream(rec.data));
S1Packet p = S1Packet.parse(dataStream).mapTo(new S1Packet());
if (p.isHeaderOK()) {
if (rec.header.usb_TransferBufferLength > 13) {
p.addData(dataStream.readByteArray(rec.data.length-13));
}
p.setRecord(rec.recnum);
p.setDirection(rec.header.usb_TransferFlags);
if (current!=null) {
current.finalise();
if (current.direction.equals("READ REPLY")) {
if (current.getLength()>0)
if (current.getCommand()!=6) {
session.addPacket(current);
}
} else {
if (current.getCommand()==5)
current.setFileName(getSin(extractedsin,current.data));
if (current.getCommand()!=6)
session.addPacket(current);
}
}
current = p;
}
else {
if (current!=null)
current.addData(rec.data);
}
dataStream.close();
}
}
}
if (ccurrent!=null) {
if (ccurrent.getCommand().startsWith("signature")) {
ccurrent.setFile(getSin(extractedsin,ccurrent.signdata));
}
session.addCommand(ccurrent);
}
usbStream.close();
/* Iterator<S1Packet> ipacket = session.getPackets();
while (ipacket.hasNext()) {
S1Packet p = ipacket.next();
}*/
return session;
}
private static USBRecord readRecord(JBBPBitInputStream usbStream) throws Exception {
USBRecord rec = USBRecord.parse(usbStream).mapTo(new USBRecord());
rec.parse(usbStream);
return rec;
}
private static String getSin(String folder, byte[] source) throws Exception {
Collection<File> sinfiles = FileUtils.listFiles(new File(folder), new String[] {"sin"}, true);
Iterator<File> ifiles = sinfiles.iterator();
while (ifiles.hasNext()) {
try {
SinFile sinfile = new SinFile(ifiles.next());
if (sinfile.getVersion()!=4) {
JBBPBitInputStream sinStream = new JBBPBitInputStream(new FileInputStream(sinfile.getFile()));
byte[] res = sinStream.readByteArray(source.length);
if (Arrays.equals(source, res))
return sinfile.getShortName();
}
else {
if (Arrays.equals(source, sinfile.getHeader())) return sinfile.getFile().getName();
}
} catch (EOFException eof) {
}
}
return "Not identified";
}
}
| 8,139 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
USBRecord.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/simpleusblogger/USBRecord.java | package org.flashtool.parsers.simpleusblogger;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.flashtool.util.BytesUtil;
import org.flashtool.util.HexDump;
import com.igormaznitsa.jbbp.JBBPParser;
import com.igormaznitsa.jbbp.io.JBBPBitInputStream;
import com.igormaznitsa.jbbp.io.JBBPByteOrder;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class USBRecord {
@Bin long irp;
@Bin int unknown1;
@Bin int recordid;
@Bin int recordlength;
@Bin byte[] reserved2;
USBHeader header=null;
USBHeaderExtended headerext=null;
public int recnum=0;
public byte[] data=null;
public void parse(JBBPBitInputStream usbStream) throws IOException {
JBBPParser USBHeaderParser = JBBPParser.prepare(
"<short usb_Length;" +
"<short usb_Function;" +
"<int usb_Status;" +
"<long usb_UsbDeviceHandle;" +
"<long usb_UsbdFlags;" +
"<long usb_PipeHandle;" +
"<int usb_TransferFlags;" +
"<int usb_TransferBufferLength;" +
"<long usb_TransferBuffer;" +
"<long usb_TransferBufferMDL;" +
"<long usb_UrbLink;" +
"<long usb_hcdendpoint;" +
"<long usb_hcdirp;" +
"<long usb_hcdlistentry;" +
"<long usb_flink;" +
"<long usb_blink;" +
"<long usb_hcdlistentry2;" +
"<long usb_hcdcurrentflushpointer;" +
"<long usb_hcdextension;"
);
JBBPParser USBHeaderExtended = JBBPParser.prepare(
"byte brmRequestType;" +
"byte bRequest;" +
"<short wValue;" +
"<short wIndex;" +
"<short wLength;"
);
if (recordlength>=128) {
header = USBHeaderParser.parse(usbStream).mapTo(new USBHeader());
}
else {
usbStream.skip(recordlength);
}
try {
if (header.usb_Length!=128) {
header=null;
usbStream.skip(recordlength-128);
}
else data = usbStream.readByteArray(recordlength-128);
} catch (NullPointerException npe) {}
}
public byte[] getData() {
return data;
}
public String getDirection() {
if (header.usb_TransferFlags==0) return "WRITE";
else return "READ REPLY";
}
public String getDataString() {
byte[] buffer = new byte[200];
try {
ByteArrayInputStream in = new ByteArrayInputStream(data);
int nbread = in.read(buffer);
in.close();
return new String(BytesUtil.getReply(buffer, nbread));
} catch (Exception e) {
return "";
}
}
public String toString() {
return "Record : "+recnum+" length : "+recordlength+"\n "+header+"\n read : "+data.length;
}
} | 2,479 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
S1Packet.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/simpleusblogger/S1Packet.java | package org.flashtool.parsers.simpleusblogger;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.flashtool.libusb.LibUsbException;
import org.flashtool.parsers.ta.TAUnit;
import org.flashtool.util.BytesUtil;
import org.flashtool.util.HexDump;
import com.igormaznitsa.jbbp.io.JBBPBitInputStream;
import com.igormaznitsa.jbbp.io.JBBPByteOrder;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class S1Packet {
@Bin byte[] command;
@Bin byte[] flag;
@Bin byte[] length;
@Bin byte headercksum;
byte[] data = null;
byte[] crc = null;
int startrecord=0;
int datalength=0;
int nbparts=1;
String direction="";
String sinname="";
String action = "";
String actionreply="";
public int getStartRecord() {
return startrecord;
}
public int getNbParts() {
return nbparts;
}
public byte[] getHeader() {
return BytesUtil.concatAll(command, flag, length);
}
public boolean isHeaderOK() {
if (headercksum==0 && getCommandName().length()>0 && (getFlag()==1 || getFlag()==3 || getFlag()==7)) return true;
byte computed = calcSum(BytesUtil.concatAll(command, flag, length));
return (computed == headercksum) && (getCommandName().length() >0);
}
public int getCommand() {
return BytesUtil.getInt(command);
}
public int getFlag() {
return BytesUtil.getInt(flag);
}
public String getCommandName() {
if (getCommand() == 0x01) return "getLoaderInfos";
if (getCommand() == 0x09) return "openTA";
if (getCommand() == 0x0A) return "closeTA";
if (getCommand() == 0x0C) return "readTA";
if (getCommand() == 0x0D) return "writeTA";
if (getCommand() == 0x05) return "uploadImage";
if (getCommand() == 0x06) return "Send sin data";
if (getCommand() == 0x19) return "setLoaderConfig";
if (getCommand() == 0x04) return "End flashing";
if (getCommand() == 0x07) return "Get Error";
//System.out.println(HexDump.toHex(BytesUtil.concatAll(command, flag, length)));
return "";
}
public String getDirection() {
return direction;
}
public int getLength() {
return BytesUtil.getInt(length);
}
private byte calcSum(byte paramArray[])
{
byte byte0 = 0;
if(paramArray.length < 12)
return 0;
for(int i = 0; i < 12; i++)
byte0 ^= paramArray[i];
byte0 += 7;
return byte0;
}
public void finalise() throws IOException {
if (data!=null) {
JBBPBitInputStream dataStream = new JBBPBitInputStream(new ByteArrayInputStream(data));
if (data.length >4)
data = dataStream.readByteArray(data.length-4);
else data = null;
crc = dataStream.readByteArray(4);
}
if (data==null) datalength=0;
else datalength = data.length;
}
public void addData(byte[] pdata) {
if (data==null)
data = pdata;
else
data = BytesUtil.concatAll(data, pdata);
nbparts++;
}
public void setRecord(int recnum) {
startrecord=recnum;
}
public void setDirection(int dir) {
if (dir==0) direction = "WRITE";
else direction = "READ REPLY";
}
public TAUnit getTA() {
try {
JBBPBitInputStream taStream = new JBBPBitInputStream(new ByteArrayInputStream(data));
int unit=taStream.readInt(JBBPByteOrder.BIG_ENDIAN);
int talength = taStream.readInt(JBBPByteOrder.BIG_ENDIAN);
TAUnit u = new TAUnit(unit, taStream.readByteArray(talength));
taStream.close();
return u;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void setFileName(String name) {
sinname = name;
}
public String getInfo() {
TAUnit ta = null;
if (this.getCommand()==0x0D) ;
ta=getTA();
if (ta!=null) return ta.toString();
if (getCommand()==5)
return sinname;
if (getCommand()==0x09)
return "Partition : "+BytesUtil.getInt(data);
if (getCommand()==0x0C) {
if (direction.equals("READ REPLY"))
return "Value : "+HexDump.toHex(data);
else
return "Unit : "+HexDump.toHex(data);
}
return "";
}
public String toString() {
return direction + " : " + getCommandName()+" "+getInfo();
}
public byte[] getData() {
return data;
}
public String getSin() {
if (sinname==null) return "";
return sinname;
}
}
| 4,173 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
Session.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/parsers/simpleusblogger/Session.java | package org.flashtool.parsers.simpleusblogger;
import java.io.File;
import java.util.Iterator;
import java.util.Vector;
import org.flashtool.gui.models.TableLine;
import org.flashtool.libusb.LibUsbException;
import org.flashtool.parsers.sin.SinFile;
import org.flashtool.parsers.ta.TAUnit;
import org.flashtool.system.DeviceEntry;
import org.flashtool.system.Devices;
import org.flashtool.system.OS;
import org.flashtool.system.TextFile;
import org.flashtool.util.BytesUtil;
import org.flashtool.util.HexDump;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Session {
private Vector<S1Packet> packets = new Vector<S1Packet>();
private Vector<FlashCommand> commands = new Vector<FlashCommand>();
private String readUnit="";
private String model="";
private String version="";
public void addCommand(FlashCommand c) {
commands.add(c);
if (c.getCommand().startsWith("Read-TA")) {
if (c.getUnit()==2210) model=new String(c.getReply());
if (c.getUnit()==2202) {
try {
version = new String(c.getReply()).split("_")[1];
} catch (ArrayIndexOutOfBoundsException npe1 ) {
version = new String(c.getReply());
}
}
}
}
public void addPacket(S1Packet p) {
if (p.getCommandName().equals("readTA")) {
if (p.getDirection().equals("WRITE"))
readUnit = Integer.toString(BytesUtil.getInt(p.data));
else {
if (readUnit.equals("2210")) {
model = new String(p.data);
}
if (readUnit.equals("2206")) {
version = new String(p.data).split("_")[1];
}
}
}
if (p.getCommandName().equals("closeTA") && packets.get(packets.size()-1).getCommandName().equals("openTA")) {
packets.remove(packets.size()-1);
}
else if (!p.getCommandName().equals("readTA") && !p.getCommandName().equals("Get Error"))
packets.add(p);
}
public String getModel() {
return model;
}
public String getVersion() {
return version;
}
public Iterator<S1Packet> getPackets() {
return packets.iterator();
}
public String saveScript() {
try {
DeviceEntry ent = Devices.getDeviceFromVariant(model);
String folder = "";
if (ent!=null)
folder = ent.getMyDeviceDir();
else
folder = OS.getFolderFirmwaresScript();
String filename = folder+File.separator+model+(version.length()>0?"_"+version:"")+".fsc";
TextFile tf = new TextFile(filename,"ISO8859-1");
tf.open(false);
Iterator<TableLine> i = getScript().iterator();
while (i.hasNext()) {
TableLine tl = i.next();
tf.writeln(tl.getValueOf(0)+(tl.getValueOf(1).length()>0?":":"")+tl.getValueOf(1));
}
tf.close();
return filename;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public Vector<TableLine> getScript() {
Vector<TableLine> v = new Vector<TableLine>();
if (!packets.isEmpty()) {
Iterator<S1Packet> i = packets.iterator();
int count=0;
boolean start = false;
while (i.hasNext()) {
S1Packet p = i.next();
TableLine tl = new TableLine();
/* if (p.getDirection().equals("READ REPLY")) {
if (p.getCommand()==1) {
tl.add("readLoaderInfos");
tl.add("");
v.add(tl);
}
}*/
if (p.getDirection().equals("WRITE")) {
if (p.getCommand()==0x0D) {
if (p.getTA().getUnitNumber()==10100) {
tl.add("setFlashState");
tl.add(Integer.toString(BytesUtil.getInt(p.getTA().getUnitData())));
}
else if (p.getTA().getUnitNumber()==10021) {
tl.add("setFlashTimestamp");
tl.add("");
}
else {
tl.add("writeTA");
tl.add(Long.toString(p.getTA().getUnitNumber()));
}
v.add(tl);
}
else {
tl.add(p.getCommandName());
if (p.getCommand()==0x05) {
tl.add(SinFile.getShortName(p.sinname));
}
else if (p.getCommand()==0x09)
tl.add(Integer.toString(BytesUtil.getInt(p.getData())));
else if (p.getCommand()==0x0C)
tl.add(HexDump.toHex(p.getData()));
else if (p.getCommand()==0x19)
tl.add(HexDump.toHex(p.getData()));
else tl.add("");
v.add(tl);
}
}
count++;
}
}
if (!commands.isEmpty()) {
Iterator<FlashCommand> ic = commands.iterator();
while (ic.hasNext()) {
FlashCommand c = ic.next();
TableLine t1 = new TableLine();
t1.add(c.getFinalCommand());
t1.add(c.getParameters());
v.add(t1);
}
}
return v;
}
}
| 4,417 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
SWTResourceManager.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/windowbuilder/swt/SWTResourceManager.java | /*******************************************************************************
* Copyright (c) 2011 Google, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Google, Inc. - initial API and implementation
*******************************************************************************/
package org.flashtool.windowbuilder.swt;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import lombok.extern.slf4j.Slf4j;
/**
* Utility class for managing OS resources associated with SWT controls such as colors, fonts, images, etc.
* <p>
* !!! IMPORTANT !!! Application code must explicitly invoke the <code>dispose()</code> method to release the
* operating system resources managed by cached objects when those objects and OS resources are no longer
* needed (e.g. on application shutdown)
* <p>
* This class may be freely distributed as part of any application or plugin.
* <p>
* @author scheglov_ke
* @author Dan Rubel
*/
@Slf4j
public class SWTResourceManager {
////////////////////////////////////////////////////////////////////////////
//
// Color
//
////////////////////////////////////////////////////////////////////////////
private static Map<RGB, Color> m_colorMap = new HashMap<RGB, Color>();
/**
* Returns the system {@link Color} matching the specific ID.
*
* @param systemColorID
* the ID value for the color
* @return the system {@link Color} matching the specific ID
*/
public static Color getColor(int systemColorID) {
Display display = Display.getCurrent();
return display.getSystemColor(systemColorID);
}
/**
* Returns a {@link Color} given its red, green and blue component values.
*
* @param r
* the red component of the color
* @param g
* the green component of the color
* @param b
* the blue component of the color
* @return the {@link Color} matching the given red, green and blue component values
*/
public static Color getColor(int r, int g, int b) {
return getColor(new RGB(r, g, b));
}
/**
* Returns a {@link Color} given its RGB value.
*
* @param rgb
* the {@link RGB} value of the color
* @return the {@link Color} matching the RGB value
*/
public static Color getColor(RGB rgb) {
Color color = m_colorMap.get(rgb);
if (color == null) {
Display display = Display.getCurrent();
color = new Color(display, rgb);
m_colorMap.put(rgb, color);
}
return color;
}
/**
* Dispose of all the cached {@link Color}'s.
*/
public static void disposeColors() {
for (Color color : m_colorMap.values()) {
color.dispose();
}
m_colorMap.clear();
}
////////////////////////////////////////////////////////////////////////////
//
// Image
//
////////////////////////////////////////////////////////////////////////////
/**
* Maps image paths to images.
*/
private static Map<String, Image> m_imageMap = new HashMap<String, Image>();
/**
* Returns an {@link Image} encoded by the specified {@link InputStream}.
*
* @param stream
* the {@link InputStream} encoding the image data
* @return the {@link Image} encoded by the specified input stream
*/
protected static Image getImage(InputStream stream) throws IOException {
try {
Display display = Display.getCurrent();
ImageData data = new ImageData(stream);
if (data.transparentPixel > 0) {
return new Image(display, data, data.getTransparencyMask());
}
return new Image(display, data);
} finally {
stream.close();
}
}
/**
* Returns an {@link Image} stored in the file at the specified path.
*
* @param path
* the path to the image file
* @return the {@link Image} stored in the file at the specified path
*/
public static Image getImage(String path) {
Image image = m_imageMap.get(path);
if (image == null) {
try {
image = getImage(new FileInputStream(path));
m_imageMap.put(path, image);
} catch (Exception e) {
image = getMissingImage();
m_imageMap.put(path, image);
}
}
return image;
}
/**
* Returns an {@link Image} stored in the file at the specified path relative to the specified class.
*
* @param clazz
* the {@link Class} relative to which to find the image
* @param path
* the path to the image file, if starts with <code>'/'</code>
* @return the {@link Image} stored in the file at the specified path
*/
public static Image getImage(Class<?> clazz, String path) {
String key = clazz.getName() + '|' + path;
Image image = m_imageMap.get(key);
if (image == null) {
try {
image = getImage(clazz.getResourceAsStream(path));
m_imageMap.put(key, image);
} catch (Exception e) {
image = getMissingImage();
m_imageMap.put(key, image);
}
}
return image;
}
private static final int MISSING_IMAGE_SIZE = 10;
/**
* @return the small {@link Image} that can be used as placeholder for missing image.
*/
private static Image getMissingImage() {
Image image = new Image(Display.getCurrent(), MISSING_IMAGE_SIZE, MISSING_IMAGE_SIZE);
//
GC gc = new GC(image);
gc.setBackground(getColor(SWT.COLOR_RED));
gc.fillRectangle(0, 0, MISSING_IMAGE_SIZE, MISSING_IMAGE_SIZE);
gc.dispose();
//
return image;
}
/**
* Style constant for placing decorator image in top left corner of base image.
*/
public static final int TOP_LEFT = 1;
/**
* Style constant for placing decorator image in top right corner of base image.
*/
public static final int TOP_RIGHT = 2;
/**
* Style constant for placing decorator image in bottom left corner of base image.
*/
public static final int BOTTOM_LEFT = 3;
/**
* Style constant for placing decorator image in bottom right corner of base image.
*/
public static final int BOTTOM_RIGHT = 4;
/**
* Internal value.
*/
protected static final int LAST_CORNER_KEY = 5;
/**
* Maps images to decorated images.
*/
@SuppressWarnings("unchecked")
private static Map<Image, Map<Image, Image>>[] m_decoratedImageMap = new Map[LAST_CORNER_KEY];
/**
* Returns an {@link Image} composed of a base image decorated by another image.
*
* @param baseImage
* the base {@link Image} that should be decorated
* @param decorator
* the {@link Image} to decorate the base image
* @return {@link Image} The resulting decorated image
*/
public static Image decorateImage(Image baseImage, Image decorator) {
return decorateImage(baseImage, decorator, BOTTOM_RIGHT);
}
/**
* Returns an {@link Image} composed of a base image decorated by another image.
*
* @param baseImage
* the base {@link Image} that should be decorated
* @param decorator
* the {@link Image} to decorate the base image
* @param corner
* the corner to place decorator image
* @return the resulting decorated {@link Image}
*/
public static Image decorateImage(final Image baseImage, final Image decorator, final int corner) {
if (corner <= 0 || corner >= LAST_CORNER_KEY) {
throw new IllegalArgumentException("Wrong decorate corner");
}
Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[corner];
if (cornerDecoratedImageMap == null) {
cornerDecoratedImageMap = new HashMap<Image, Map<Image, Image>>();
m_decoratedImageMap[corner] = cornerDecoratedImageMap;
}
Map<Image, Image> decoratedMap = cornerDecoratedImageMap.get(baseImage);
if (decoratedMap == null) {
decoratedMap = new HashMap<Image, Image>();
cornerDecoratedImageMap.put(baseImage, decoratedMap);
}
//
Image result = decoratedMap.get(decorator);
if (result == null) {
Rectangle bib = baseImage.getBounds();
Rectangle dib = decorator.getBounds();
//
result = new Image(Display.getCurrent(), bib.width, bib.height);
//
GC gc = new GC(result);
gc.drawImage(baseImage, 0, 0);
if (corner == TOP_LEFT) {
gc.drawImage(decorator, 0, 0);
} else if (corner == TOP_RIGHT) {
gc.drawImage(decorator, bib.width - dib.width, 0);
} else if (corner == BOTTOM_LEFT) {
gc.drawImage(decorator, 0, bib.height - dib.height);
} else if (corner == BOTTOM_RIGHT) {
gc.drawImage(decorator, bib.width - dib.width, bib.height - dib.height);
}
gc.dispose();
//
decoratedMap.put(decorator, result);
}
return result;
}
/**
* Dispose all of the cached {@link Image}'s.
*/
public static void disposeImages() {
// dispose loaded images
{
for (Image image : m_imageMap.values()) {
image.dispose();
}
m_imageMap.clear();
}
// dispose decorated images
for (int i = 0; i < m_decoratedImageMap.length; i++) {
Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[i];
if (cornerDecoratedImageMap != null) {
for (Map<Image, Image> decoratedMap : cornerDecoratedImageMap.values()) {
for (Image image : decoratedMap.values()) {
image.dispose();
}
decoratedMap.clear();
}
cornerDecoratedImageMap.clear();
}
}
}
////////////////////////////////////////////////////////////////////////////
//
// Font
//
////////////////////////////////////////////////////////////////////////////
/**
* Maps font names to fonts.
*/
private static Map<String, Font> m_fontMap = new HashMap<String, Font>();
/**
* Maps fonts to their bold versions.
*/
private static Map<Font, Font> m_fontToBoldFontMap = new HashMap<Font, Font>();
/**
* Returns a {@link Font} based on its name, height and style.
*
* @param name
* the name of the font
* @param height
* the height of the font
* @param style
* the style of the font
* @return {@link Font} The font matching the name, height and style
*/
public static Font getFont(String name, int height, int style) {
return getFont(name, height, style, false, false);
}
/**
* Returns a {@link Font} based on its name, height and style. Windows-specific strikeout and underline
* flags are also supported.
*
* @param name
* the name of the font
* @param size
* the size of the font
* @param style
* the style of the font
* @param strikeout
* the strikeout flag (warning: Windows only)
* @param underline
* the underline flag (warning: Windows only)
* @return {@link Font} The font matching the name, height, style, strikeout and underline
*/
public static Font getFont(String name, int size, int style, boolean strikeout, boolean underline) {
String fontName = name + '|' + size + '|' + style + '|' + strikeout + '|' + underline;
Font font = m_fontMap.get(fontName);
if (font == null) {
FontData fontData = new FontData(name, size, style);
if (strikeout || underline) {
try {
Class<?> logFontClass = Class.forName("org.eclipse.swt.internal.win32.LOGFONT"); //$NON-NLS-1$
Object logFont = FontData.class.getField("data").get(fontData); //$NON-NLS-1$
if (logFont != null && logFontClass != null) {
if (strikeout) {
logFontClass.getField("lfStrikeOut").set(logFont, Byte.valueOf((byte) 1)); //$NON-NLS-1$
}
if (underline) {
logFontClass.getField("lfUnderline").set(logFont, Byte.valueOf((byte) 1)); //$NON-NLS-1$
}
}
} catch (Throwable e) {
System.err.println("Unable to set underline or strikeout" + " (probably on a non-Windows platform). " + e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
font = new Font(Display.getCurrent(), fontData);
m_fontMap.put(fontName, font);
}
return font;
}
/**
* Returns a bold version of the given {@link Font}.
*
* @param baseFont
* the {@link Font} for which a bold version is desired
* @return the bold version of the given {@link Font}
*/
public static Font getBoldFont(Font baseFont) {
Font font = m_fontToBoldFontMap.get(baseFont);
if (font == null) {
FontData fontDatas[] = baseFont.getFontData();
FontData data = fontDatas[0];
font = new Font(Display.getCurrent(), data.getName(), data.getHeight(), SWT.BOLD);
m_fontToBoldFontMap.put(baseFont, font);
}
return font;
}
/**
* Dispose all of the cached {@link Font}'s.
*/
public static void disposeFonts() {
// clear fonts
for (Font font : m_fontMap.values()) {
font.dispose();
}
m_fontMap.clear();
// clear bold fonts
for (Font font : m_fontToBoldFontMap.values()) {
font.dispose();
}
m_fontToBoldFontMap.clear();
}
////////////////////////////////////////////////////////////////////////////
//
// Cursor
//
////////////////////////////////////////////////////////////////////////////
/**
* Maps IDs to cursors.
*/
private static Map<Integer, Cursor> m_idToCursorMap = new HashMap<Integer, Cursor>();
/**
* Returns the system cursor matching the specific ID.
*
* @param id
* int The ID value for the cursor
* @return Cursor The system cursor matching the specific ID
*/
public static Cursor getCursor(int id) {
Integer key = Integer.valueOf(id);
Cursor cursor = m_idToCursorMap.get(key);
if (cursor == null) {
cursor = new Cursor(Display.getDefault(), id);
m_idToCursorMap.put(key, cursor);
}
return cursor;
}
/**
* Dispose all of the cached cursors.
*/
public static void disposeCursors() {
for (Cursor cursor : m_idToCursorMap.values()) {
cursor.dispose();
}
m_idToCursorMap.clear();
}
////////////////////////////////////////////////////////////////////////////
//
// General
//
////////////////////////////////////////////////////////////////////////////
/**
* Dispose of cached objects and their underlying OS resources. This should only be called when the cached
* objects are no longer needed (e.g. on application shutdown).
*/
public static void dispose() {
disposeColors();
disposeImages();
disposeFonts();
disposeCursors();
}
} | 14,585 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
XmlCombiner.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/xmlcombiner/XmlCombiner.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flashtool.xmlcombiner;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.google.common.base.Splitter;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
/**
* Combines two or more XML DOM trees.
*
* <p>
* The merging algorithm is as follows:<br/>
* First direct subelements of selected node are examined.
* The elements from both trees with matching keys are paired.
* Based on selected behavior the content of the paired elements is then merged.
* Finally the paired elements are recursively combined. Any not paired elements are appended.
* </p>
* <p>
* You can control merging behavior using {@link CombineSelf 'combine.self'}
* and {@link CombineChildren 'combine.children'} attributes.
* </p>
* <p>
* The merging algorithm was inspired by similar functionality in Plexus Utils.
* </p>
*
* @see <a href="http://www.sonatype.com/people/2011/01/maven-how-to-merging-plugin-configuration-in-complex-projects/">merging in Maven</a>
* @see <a href="http://plexus.codehaus.org/plexus-utils/apidocs/org/codehaus/plexus/util/xml/Xpp3DomUtils.html">Plexus utils implementation of merging</a>
*/
@Slf4j
public class XmlCombiner {
/**
* Allows to filter the result of the merging.
*/
public interface Filter {
/**
* Post process the matching elements after merging.
* @param recessive recessive element, can be null, should not be modified
* @param dominant dominant element, can be null, should not be modified
* @param result result element, will not be null, it can be freely modified
*/
void postProcess(Element recessive, Element dominant, Element result);
}
private final DocumentBuilder documentBuilder;
private final Document document;
private final List<String> defaultAttributeNames;
private static final Filter NULL_FILTER = new Filter() {
@Override
public void postProcess(Element recessive, Element dominant, Element result) {
}
};
private Filter filter = NULL_FILTER;
private final ChildContextsMapper childContextMapper = new KeyAttributesChildContextsMapper();
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException,
TransformerException {
List<Path> files = new ArrayList<>();
List<String> ids = new ArrayList<>();
boolean onlyFiles = false;
for (int i = 0; i < args.length; i++) {
if (!onlyFiles) {
switch (args[i]) {
case "--key":
ids.add(args[i+1]);
i++;
break;
case "--":
onlyFiles = true;
break;
default:
files.add(Paths.get(args[i]));
}
} else {
files.add(Paths.get(args[i]));
}
}
XmlCombiner xmlCombiner = new XmlCombiner(ids);
for (Path file : files) {
xmlCombiner.combine(file);
}
xmlCombiner.buildDocument(System.out);
}
/**
* Creates XML combiner using default {@link DocumentBuilder}.
* @throws ParserConfigurationException when {@link DocumentBuilder} creation fails
*/
public XmlCombiner() throws ParserConfigurationException {
this(DocumentBuilderFactory.newInstance().newDocumentBuilder());
}
public XmlCombiner(DocumentBuilder documentBuilder) {
this(documentBuilder, Lists.<String>newArrayList());
}
/**
* Creates XML combiner using given attribute as an id.
*/
public XmlCombiner(String idAttributeName) throws ParserConfigurationException {
this(Lists.newArrayList(idAttributeName));
}
public XmlCombiner(List<String> keyAttributeNames) throws ParserConfigurationException {
this(DocumentBuilderFactory.newInstance().newDocumentBuilder(), keyAttributeNames);
}
/**
* Creates XML combiner using given document builder and an id attribute name.
*/
public XmlCombiner(DocumentBuilder documentBuilder, String keyAttributeNames) {
this(documentBuilder, Lists.newArrayList(keyAttributeNames));
}
public XmlCombiner(DocumentBuilder documentBuilder, List<String> keyAttributeNames) {
this.documentBuilder = documentBuilder;
document = documentBuilder.newDocument();
this.defaultAttributeNames = keyAttributeNames;
}
/**
* Sets the filter.
*/
public void setFilter(Filter filter) {
if (filter == null) {
this.filter = NULL_FILTER;
return;
}
this.filter = filter;
}
/**
* Combine given file.
* @param file file to combine
*/
public void combine(Path file) throws SAXException, IOException {
combine(documentBuilder.parse(file.toFile()));
}
/**
* Combine given input stream.
* @param stream input stream to combine
*/
public void combine(InputStream stream) throws SAXException, IOException {
combine(documentBuilder.parse(stream));
}
/**
* Combine given document.
* @param document document to combine
*/
public void combine(Document document) {
combine(document.getDocumentElement());
}
/**
* Combine given element.
* @param element element to combine
*/
public void combine(Element element) {
Element parent = document.getDocumentElement();
if (parent != null) {
document.removeChild(parent);
}
Context result = combine(Context.fromElement(parent), Context.fromElement(element));
result.addAsChildTo(document);
}
/**
* Return the result of the merging process.
*/
public Document buildDocument() {
filterOutDefaults(Context.fromElement(document.getDocumentElement()));
filterOutCombines(document.getDocumentElement());
return document;
}
/**
* Stores the result of the merging process.
*/
public void buildDocument(OutputStream out) throws TransformerException {
Document result = buildDocument();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(out);
Source input = new DOMSource(result);
transformer.transform(input, output);
}
/**
* Stores the result of the merging process.
*/
public void buildDocument(Path path) throws TransformerException, FileNotFoundException {
buildDocument(new FileOutputStream(path.toFile()));
}
private Context combine(Context recessive, Context dominant) {
CombineSelf dominantCombineSelf = getCombineSelf(dominant.getElement());
CombineSelf recessiveCombineSelf = getCombineSelf(recessive.getElement());
if (dominantCombineSelf == CombineSelf.REMOVE) {
return null;
} else if (dominantCombineSelf == CombineSelf.OVERRIDE
|| (recessiveCombineSelf == CombineSelf.OVERRIDABLE)) {
Context result = copyRecursively(dominant);
result.getElement().removeAttribute(CombineSelf.ATTRIBUTE_NAME);
return result;
}
CombineChildren combineChildren = getCombineChildren(dominant.getElement());
if (combineChildren == null) {
combineChildren = getCombineChildren(recessive.getElement());
if (combineChildren == null) {
combineChildren = CombineChildren.MERGE;
}
}
if (combineChildren == CombineChildren.APPEND) {
if (recessive.getElement() != null) {
removeWhitespaceTail(recessive.getElement());
appendRecursively(dominant, recessive);
return recessive;
} else {
return copyRecursively(dominant);
}
}
Element resultElement = document.createElement(dominant.getElement().getTagName());
copyAttributes(recessive.getElement(), resultElement);
copyAttributes(dominant.getElement(), resultElement);
// when dominant combineSelf is null or DEFAULTS use combineSelf from recessive
CombineSelf combineSelf = dominantCombineSelf;
if ((combineSelf == null && recessiveCombineSelf != CombineSelf.DEFAULTS)) {
//|| (combineSelf == CombineSelf.DEFAULTS && recessive.getElement() != null)) {
combineSelf = recessiveCombineSelf;
}
if (combineSelf != null) {
resultElement.setAttribute(CombineSelf.ATTRIBUTE_NAME, combineSelf.name().toLowerCase());
} else {
resultElement.removeAttribute(CombineSelf.ATTRIBUTE_NAME);
}
List<String> keys = defaultAttributeNames;
if (recessive.getElement() != null) {
Attr keysNode = recessive.getElement().getAttributeNode(Context.KEYS_ATTRIBUTE_NAME);
if (keysNode != null) {
keys = Splitter.on(",").splitToList(keysNode.getValue());
}
}
if (dominant.getElement() != null) {
Attr keysNode = dominant.getElement().getAttributeNode(Context.KEYS_ATTRIBUTE_NAME);
if (keysNode != null) {
keys = Splitter.on(",").splitToList(keysNode.getValue());
}
}
ListMultimap<Key, Context> recessiveContexts = childContextMapper.mapChildContexts(recessive, keys);
ListMultimap<Key, Context> dominantContexts = childContextMapper.mapChildContexts(dominant, keys);
Set<String> tagNamesInDominant = getTagNames(dominantContexts);
// Execute only if there is at least one subelement in recessive
if (!recessiveContexts.isEmpty()) {
for (Entry<Key, Context> entry : recessiveContexts.entries()) {
Key key = entry.getKey();
Context recessiveContext = entry.getValue();
if (key == Key.BEFORE_END) {
continue;
}
if (getCombineSelf(recessiveContext.getElement()) == CombineSelf.OVERRIDABLE_BY_TAG) {
if (!tagNamesInDominant.contains(key.getName())) {
recessiveContext.addAsChildTo(resultElement);
filter.postProcess(recessiveContext.getElement(), null, recessiveContext.getElement());
}
continue;
}
if (dominantContexts.get(key).size() == 1 && recessiveContexts.get(key).size() == 1) {
Context dominantContext = dominantContexts.get(key).iterator().next();
Context combined = combine(recessiveContext, dominantContext);
if (combined != null) {
combined.addAsChildTo(resultElement);
}
} else {
recessiveContext.addAsChildTo(resultElement);
if (recessiveContext.getElement() != null) {
filter.postProcess(recessiveContext.getElement(), null, recessiveContext.getElement());
}
}
}
}
for (Entry<Key, Context> entry : dominantContexts.entries()) {
Key key = entry.getKey();
Context dominantContext = entry.getValue();
if (key == Key.BEFORE_END) {
dominantContext.addAsChildTo(resultElement, document);
if (dominantContext.getElement() != null) {
filter.postProcess(null, dominantContext.getElement(), dominantContext.getElement());
}
// break? this should be the last anyway...
continue;
}
List<Context> associatedRecessives = recessiveContexts.get(key);
if (dominantContexts.get(key).size() == 1 && associatedRecessives.size() == 1
&& getCombineSelf(associatedRecessives.get(0).getElement()) != CombineSelf.OVERRIDABLE_BY_TAG) {
// already added
} else {
Context combined = combine(Context.fromElement(null), dominantContext);
if (combined != null) {
combined.addAsChildTo(resultElement);
}
}
}
Context result = new Context();
result.setElement(resultElement);
appendNeighbours(dominant, result);
filter.postProcess(recessive.getElement(), dominant.getElement(), result.getElement());
return result;
}
/**
* Copy element recursively.
* @param context context to copy, it is assumed it is from unrelated document
* @return copied element in current document
*/
private Context copyRecursively(Context context) {
Context copy = new Context();
appendNeighbours(context, copy);
Element element = (Element) document.importNode(context.getElement(), false);
copy.setElement(element);
appendRecursively(context, copy);
return copy;
}
/**
* Append neighbors from source to destination
* @param source source element, it is assumed it is from unrelated document
* @param destination destination element
*/
private void appendNeighbours(Context source, Context destination) {
for (Node neighbour : source.getNeighbours()) {
destination.addNeighbour(document.importNode(neighbour, true));
}
}
/**
* Appends all attributes and subelements from source element do destination element.
* @param source source element, it is assumed it is from unrelated document
* @param destination destination element
*/
private void appendRecursively(Context source, Context destination) {
copyAttributes(source.getElement(), destination.getElement());
List<Context> contexts = source.groupChildContexts();
for (Context context : contexts) {
if (context.getElement() == null) {
context.addAsChildTo(destination.getElement(), document);
continue;
}
Context combined = combine(Context.fromElement(null), context);
if (combined != null) {
combined.addAsChildTo(destination.getElement());
}
}
}
/**
* Copies attributes from one {@link Element} to the other.
* @param source source element
* @param destination destination element
*/
private void copyAttributes(@Nullable Element source, Element destination) {
if (source == null) {
return;
}
NamedNodeMap attributes = source.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Attr attribute = (Attr) attributes.item(i);
Attr destAttribute = destination.getAttributeNodeNS(attribute.getNamespaceURI(), attribute.getName());
if (destAttribute == null) {
destination.setAttributeNodeNS((Attr) document.importNode(attribute, true));
} else {
destAttribute.setValue(attribute.getValue());
}
}
}
private static CombineSelf getCombineSelf(@Nullable Element element) {
CombineSelf combine = null;
if (element == null) {
return null;
}
Attr combineAttribute = element.getAttributeNode(CombineSelf.ATTRIBUTE_NAME);
if (combineAttribute != null) {
try {
combine = CombineSelf.valueOf(combineAttribute.getValue().toUpperCase());
} catch (IllegalArgumentException e) {
throw new RuntimeException("The attribute 'combine' of element '"
+ element.getTagName() + "' has invalid value '"
+ combineAttribute.getValue(), e);
}
}
return combine;
}
private static CombineChildren getCombineChildren(@Nullable Element element) {
CombineChildren combine = null;
if (element == null) {
return null;
}
Attr combineAttribute = element.getAttributeNode(CombineChildren.ATTRIBUTE_NAME);
if (combineAttribute != null) {
try {
combine = CombineChildren.valueOf(combineAttribute.getValue().toUpperCase());
} catch (IllegalArgumentException e) {
throw new RuntimeException("The attribute 'combine' of element '"
+ element.getTagName() + "' has invalid value '"
+ combineAttribute.getValue(), e);
}
}
return combine;
}
private static void removeWhitespaceTail(Element element) {
NodeList list = element.getChildNodes();
for (int i = list.getLength() - 1; i >= 0; i--) {
Node node = list.item(i);
if (node instanceof Element) {
break;
}
element.removeChild(node);
}
}
private static void filterOutDefaults(Context context) {
Element element = context.getElement();
List<Context> childContexts = context.groupChildContexts();
for (Context childContext : childContexts) {
if (childContext.getElement() == null) {
continue;
}
CombineSelf combineSelf = getCombineSelf(childContext.getElement());
if (combineSelf == CombineSelf.DEFAULTS) {
for (Node neighbour : childContext.getNeighbours()) {
element.removeChild(neighbour);
}
element.removeChild(childContext.getElement());
} else {
filterOutDefaults(childContext);
}
}
}
private static void filterOutCombines(Element element) {
element.removeAttribute(CombineSelf.ATTRIBUTE_NAME);
element.removeAttribute(CombineChildren.ATTRIBUTE_NAME);
element.removeAttribute(Context.KEYS_ATTRIBUTE_NAME);
element.removeAttribute(Context.ID_ATTRIBUTE_NAME);
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node item = childNodes.item(i);
if (item instanceof Element) {
filterOutCombines((Element) item);
}
}
}
private static Set<String> getTagNames(ListMultimap<Key, Context> dominantContexts) {
Set<String> names = new HashSet<>();
for (Key key : dominantContexts.keys()) {
names.add(key.getName());
}
return names;
}
}
| 17,461 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
ChildContextsMapper.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/xmlcombiner/ChildContextsMapper.java | package org.flashtool.xmlcombiner;
import java.util.List;
import com.google.common.collect.ListMultimap;
public interface ChildContextsMapper {
ListMultimap<Key, Context> mapChildContexts(Context parent, List<String> keyAttributeNames);
}
| 245 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
CombineSelf.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/xmlcombiner/CombineSelf.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flashtool.xmlcombiner;
/**
* Controls the behavior when merging two XML nodes.
*/
public enum CombineSelf {
/**
* Merge elements.
* <p>
* Attributes from dominant element override those from recessive element.
* Child elements are by default paired using their keys (tag name and selected attributes) and combined
* recursively. The exact behavior depends on {@link CombineChildren 'combine.children'} attribute value.
* </p>
* <p>
*
* Example:<br/>
* First:
* <pre>
* {@code
* <config>
* <service id="1">
* <parameter>parameter</parameter>
* </service>
* </config>
* }
* </pre>
* Second:
* <pre>
* {@code
* <config>
* <service id="1">
* <parameter2>parameter</parameter2>
* </service>
* </config>
* }
* </pre>
* Result:
* <pre>
* {@code
* <config>
* <service id="1">
* <parameter>parameter</parameter>
* <parameter2>parameter</parameter2>
* </service>
* </config>
* }
* </pre>
* </p>
*/
MERGE,
/**
* Remove entire element with attributes and children.
*
* <p>
* Example:<br/>
* First:
* <pre>
* {@code
* <config>
* <service id="1">
* <parameter>parameter</parameter>
* </service>
* </config>
* }
* </pre>
* Second:
* <pre>
* {@code
* <config>
* <service id="1" combine.self="REMOVE"/>
* </config>
* }
* </pre>
* Result:
* <pre>
* {@code
* <config>
* </config>
* }
* </pre>
* </p>
*/
REMOVE,
/**
* Behaves exactly like {@link #MERGE} if paired element exists in any subsequent dominant document.
* If paired element is not found in any dominant document behaves the same as {@link #REMOVE}
* <p>
* This behavior is specifically designed to allow specifying default values which are used only
* when given element exists in any subsequent document.
* </p>
* <p>
* Example:<br/>
* First:
* <pre>
* {@code
* <config>
* <service id="1" combine.self="DEFAULTS">
* <parameter>parameter</parameter>
* </service>
* <service id="2" combine.self="DEFAULTS"/>
* </config>
* }
* </pre>
* Second:
* <pre>
* {@code
* <config>
* <service id="1">
* </service>
* </config>
* }
* </pre>
* Result:
* <pre>
* {@code
* <config>
* <service id="1">
* <parameter>parameter</parameter>
* </service>
* </config>
* }
* </pre>
* </p>
*/
DEFAULTS,
/**
* Override element.
* <p>
* Completely ignores content from recessive document by overwriting it
* with element from dominant document.
* </p>
*
* <p>
* Example:<br/>
* First:
* <pre>
* {@code
* <config>
* <service id="1">
* <parameter>parameter</parameter>
* </service>
* </config>
* }
* </pre>
* Second:
* <pre>
* {@code
* <config>
* <service id="1" combine.self="override">
* <parameter2>parameter2</parameter2>
* </service>
* </config>
* }
* </pre>
* Result:
* <pre>
* {@code
* <config>
* <service id="1">
* <parameter2>parameter2</parameter2>
* </service>
* </config>
* }
* </pre>
* </p>
*/
OVERRIDE,
/**
* Override element.
* <p>
* Completely ignores content from recessive document by overwriting it
* with element from dominant document.
* </p>
* <p>
* The difference with {@link #OVERRIDE} is that OVERRIDABLE is specified on the tag in recessive document.
* </p>
* <p>
* Example:<br/>
* First:
* <pre>
* {@code
* <config>
* <service id="id1" combine.self="OVERRIDABLE">
* <test/>
* </service>
* </config>
* }
* </pre>
* Second:
* <pre>
* {@code
* <config>
* </config>
* }
* </pre>
* Result:
* <pre>
* {@code
* <config>
* <service id="id1" combine.self="OVERRIDABLE">
* <test/>
* </service>
* </config>
* }
* </pre>
* </p>
* <p>
* Example2:<br/>
* First:
* <pre>
* {@code
* <config>
* <service id="id1" combine.self="OVERRIDABLE">
* <test/>
* </service>
* </config>
* }
* </pre>
* Second:
* <pre>
* {@code
* <config>
* <service id="id1"/>
* </config>
* }
* </pre>
* Result:
* <pre>
* {@code
* <config>
* <service id="id1"/>
* </config>
* }
* </pre>
* </p>
*/
OVERRIDABLE,
/**
* Override element.
* <p>
* Completely ignores content from recessive document by overwriting it
* with element from dominant document.
* </p>
* <p>
* The difference with {@link #OVERRIDABLE} is that with OVERRIDABLE_BY_TAG recessive element is ignored
even when the id is different.
</p>
* <p>
* Example:<br/>
* First:
* <pre>
* {@code
* <config>
* <service id="id1" combine.self="OVERRIDABLE">
* <test/>
* </service>
* </config>
* }
* </pre>
* Second:
* <pre>
* {@code
* <config>
* <service id="id2"/>
* </config>
* }
* </pre>
* Result:
* <pre>
* {@code
* <config>
* <service id="id2"/>
* </config>
* }
* </pre>
* </p>
*/
OVERRIDABLE_BY_TAG;
public static final String ATTRIBUTE_NAME = "combine.self";
}
| 5,801 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
Key.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/xmlcombiner/Key.java | /*
* Copyright 2012 Atteo.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flashtool.xmlcombiner;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
/**
* Element name and the value of it's 'id' attribute if exists.
*/
@Slf4j
class Key {
public static final Key BEFORE_END = new Key("", null);
private final String name;
private final Map<String, String> keys;
public Key(String name, Map<String, String> keys) {
this.name = name;
this.keys = keys;
}
@Override
public int hashCode() {
int hash = 1;
if (name != null) {
hash += name.hashCode();
}
if (keys != null) {
hash = hash * 37 + keys.hashCode();
}
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Key other = (Key) obj;
if ((name == null) ? (other.getName() != null) : !name.equals(other.getName())) {
return false;
}
if ((keys == null) ? (other.getId() != null) : !keys.equals(other.getId())) {
return false;
}
return true;
}
public Map<String, String> getId() {
return keys;
}
public String getName() {
return name;
}
@Override
public String toString() {
if (keys != null) {
return name + "#" + keys;
} else {
return name;
}
}
}
| 1,825 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
CombineChildren.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/xmlcombiner/CombineChildren.java | /*
* Copyright 2012 Atteo.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flashtool.xmlcombiner;
/**
* Controls the behavior of merging child elements.
*/
public enum CombineChildren {
/**
* Merge subelements from both elements.
*
* <p>
* This is the default.
* Those subelements which can be uniquely paired between two documents using the key (tag+selected attributes)
* will be merged, those that cannot be paired will be appended.<br/>
* Example:<br/>
* First:
* <pre>
* {@code
* <config>
* <service id="1">
* <parameter>parameter</parameter>
* </service>
* </config>
* }
* </pre>
* Second:
* <pre>
* {@code
* <config>
* <service id="1"/>
* <parameter>other value</parameter>
* </service>
* </config>
* }
* </pre>
* Result:
* <pre>
* {@code
* <config>
* <service id="1"/>
* <parameter>other value</parameter>
* </service>
* </config>
* }
* </pre>
* </p>
*/
MERGE,
/**
* Always append child elements from both recessive and dominant elements.
*
* <p>
* Example:<br/>
* First:
* <pre>
* {@code
* <config>
* <service id="1" combine.children="append">
* <parameter>parameter</parameter>
* </service>
* </config>
* }
* </pre>
* Second:
* <pre>
* {@code
* <config>
* <service id="1">
* <parameter>parameter</parameter>
* </service>
* </config>
* }
* </pre>
* Result:
* <pre>
* {@code
* <config>
* <service id="1" combine.children="append">
* <parameter>parameter</parameter>
* <parameter>parameter</parameter>
* </service>
* </config>
* }
* </pre>
* </p>
*/
APPEND;
public static final String ATTRIBUTE_NAME = "combine.children";
}
| 2,334 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
Context.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/xmlcombiner/Context.java | /*
* Copyright 2012 Atteo.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flashtool.xmlcombiner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* DOM {@link Element} with any other non-element nodes which precede it.
*/
import lombok.extern.slf4j.Slf4j;
@Slf4j
class Context {
public static final String KEYS_ATTRIBUTE_NAME = "combine.keys";
public static final String ID_ATTRIBUTE_NAME = "combine.id";
private final List<Node> neighbours = new ArrayList<>();
private Element element;
public Context() {
}
public static Context fromElement(Element element) {
Context context = new Context();
context.setElement(element);
return context;
}
public void addNeighbour(Node node) {
neighbours.add(node);
}
public List<Node> getNeighbours() {
return neighbours;
}
public void setElement(Element element) {
this.element = element;
}
public Element getElement() {
return element;
}
public void addAsChildTo(Node node) {
for (Node neighbour : neighbours) {
node.appendChild(neighbour);
}
node.appendChild(element);
}
public void addAsChildTo(Node node, Document document) {
for (Node neighbour : neighbours) {
node.appendChild(document.importNode(neighbour, true));
}
if (element != null) {
node.appendChild(document.importNode(element, true));
}
}
public List<Context> groupChildContexts() {
if (element == null) {
return Collections.emptyList();
}
NodeList nodes = element.getChildNodes();
List<Context> contexts = new ArrayList<>(nodes.getLength());
Context context = new Context();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node instanceof Element) {
context.setElement((Element) node);
contexts.add(context);
context = new Context();
} else {
context.addNeighbour(node);
}
}
// add last with empty element
contexts.add(context);
return contexts;
}
@Override
public String toString() {
return "[" + neighbours + ", " + element + "]";
}
}
| 2,678 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
KeyAttributesChildContextsMapper.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/xmlcombiner/KeyAttributesChildContextsMapper.java | package org.flashtool.xmlcombiner;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.ListMultimap;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class KeyAttributesChildContextsMapper implements ChildContextsMapper {
@Override
public ListMultimap<Key, Context> mapChildContexts(Context parent,
List<String> keyAttributeNames) {
List<Context> contexts = parent.groupChildContexts();
ListMultimap<Key, Context> map = LinkedListMultimap.create();
for (Context context : contexts) {
Element contextElement = context.getElement();
if (contextElement != null) {
Map<String, String> keys = new HashMap<>();
for (String keyAttributeName : keyAttributeNames) {
Attr keyNode = contextElement.getAttributeNode(keyAttributeName);
if (keyNode != null) {
keys.put(keyAttributeName, keyNode.getValue());
}
}
{
Attr keyNode = contextElement.getAttributeNode(Context.ID_ATTRIBUTE_NAME);
if (keyNode != null) {
keys.put(Context.ID_ATTRIBUTE_NAME, keyNode.getValue());
}
}
Key key = new Key(contextElement.getTagName(), keys);
map.put(key, context);
} else {
map.put(Key.BEFORE_END, context);
}
}
return map;
}
}
| 1,365 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
LogProgress.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/logger/LogProgress.java | package org.flashtool.logger;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ProgressBar;
import org.flashtool.system.GlobalState;
public class LogProgress {
static ProgressBar _bar = null;
static long maxstepsconsole = 0;
static long currentstepconsole = 0;
public static void registerProgressBar(ProgressBar bar) {
_bar = bar;
}
public static ProgressBar getProgressBar() {
return _bar;
}
public static void initProgress(final long max) {
LogProgress.initProgress((int) max);
}
public static void initProgress(final int max) {
if (GlobalState.isGUI()) {
Display.getDefault().syncExec(new Runnable() {
public void run() {
_bar.setMinimum(0);
_bar.setMaximum((int)max);
_bar.setSelection(0);
}
});
}
else {
maxstepsconsole=max;
currentstepconsole=0;
}
}
public static void updateProgress() {
if (GlobalState.isGUI()) {
Display.getDefault().syncExec(new Runnable() {
public void run() {
_bar.setSelection(_bar.getSelection()+1);
}
});
}
else {
currentstepconsole++;
double result = (double)currentstepconsole/(double)maxstepsconsole*100.0;
LogProgress.printProgBar((int)result);
}
MyLogger.lastaction="progress";
}
public static void updateProgressValue(int value) {
if (GlobalState.isGUI()) {
Display.getDefault().syncExec(new Runnable() {
public void run() {
_bar.setSelection(value);
}
});
}
else {
currentstepconsole=value;
double result = (double)currentstepconsole/(double)maxstepsconsole*100.0;
LogProgress.printProgBar((int)result);
}
MyLogger.lastaction="progress";
}
public static void printProgBar(long percent){
if (percent <=100) {
StringBuilder bar = new StringBuilder("[");
for(int i = 0; i < 50; i++){
if( i < (percent/2)){
bar.append("=");
}else if( i == (percent/2)){
bar.append(">");
}else{
bar.append(" ");
}
}
bar.append("] " + percent + "% ");
System.out.print("\r" + bar.toString());
}
}
}
| 2,157 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
MyLogger.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/logger/MyLogger.java | package org.flashtool.logger;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.flashtool.system.OS;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.core.FlashtoolAppender;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MyLogger {
private static String logmode="CONSOLE";
public static String lastaction = "";
public static final String CONSOLE_MODE="CONSOLE";
public static final String GUI_MODE="GUI";
public static String writeFile() {
String fname = MyLogger.getTimeStamp();
FlashtoolAppender<?> fa = getAppender();
fa.writeFile(OS.getFolderUserFlashtool()+File.separator+"flashtool_"+fname+".log");
return fname;
}
public static FlashtoolAppender<?> getAppender() {
Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
FlashtoolAppender<?> sa = (FlashtoolAppender<?>)root.getAppender("Flashtool");
return sa;
}
public static void setMode(String mode) {
logmode=mode;
FlashtoolAppender<?> fa = getAppender();
fa.setMode(logmode);
}
public static String getMode() {
return logmode.toLowerCase();
}
public static void setLevel(String level) {
if (level.toLowerCase().equals("warn")) setLevel(Level.WARN);
if (level.toLowerCase().equals("error")) setLevel(Level.ERROR);
if (level.toLowerCase().equals("debug")) setLevel(Level.DEBUG);
if (level.toLowerCase().equals("info")) setLevel(Level.INFO);
}
public static Level getLevel() {
Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
return root.getLevel();
}
public static void setLevel(Level level) {
Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
root.setLevel(level);
if (level == Level.ERROR) {
log.error("<- This level is successfully initialized");
}
if (level == Level.WARN) {
log.warn("<- This level is successfully initialized");
}
if (level == Level.DEBUG) {
log.debug("<- This level is successfully initialized");
}
if (level == Level.INFO) {
log.info("<- This level is successfully initialized");
}
}
public static String getTimeStamp() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setTimeZone( TimeZone.getTimeZone("PST"));
String date = ( df.format(new Date()));
DateFormat df1 = new SimpleDateFormat("hh-mm-ss") ;
df1.setTimeZone( TimeZone.getDefault()) ;
String time = ( df1.format(new Date()));
return date+"_"+time;
}
} | 2,637 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
MyTreeSet.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/util/MyTreeSet.java | package org.flashtool.util;
import java.util.Iterator;
import java.util.TreeSet;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MyTreeSet<T> extends TreeSet<T> {
/**
*
*/
private static final long serialVersionUID = 1L;
public T get(String id) {
Iterator<T> i = this.iterator();
while (i.hasNext()) {
T o = i.next();
if (o.equals(id)) return o;
}
return null;
}
}
| 398 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
CircularObjectBuffer.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/util/CircularObjectBuffer.java | /*
* Circular Object Buffer
* Copyright (C) 2002-2010 Stephen Ostermiller
* http://ostermiller.org/contact.pl?regarding=Java+Utilities
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* See LICENSE.txt for details.
*/
package org.flashtool.util;
import lombok.extern.slf4j.Slf4j;
/**
* Implements the Circular Buffer producer/consumer model for Objects.
* More information about this class is available from <a target="_top" href=
* "http://ostermiller.org/utils/CircularObjectBuffer.html">ostermiller.org</a>.
* <p>
* This class is thread safe.
*
* @see CircularCharBuffer
* @see CircularByteBuffer
*
* @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
* @param <ElementType> Type of object allowed in this circular buffer
* @since ostermillerutils 1.00.00
*/
@Slf4j
public class CircularObjectBuffer <ElementType> {
/**
* The default size for a circular object buffer.
*
* @since ostermillerutils 1.00.00
*/
private final static int DEFAULT_SIZE = 1024;
/**
* A buffer that will grow as things are added.
*
* @since ostermillerutils 1.00.00
*/
public final static int INFINITE_SIZE = -1;
/**
* The circular buffer.
* <p>
* The actual capacity of the buffer is one less than the actual length
* of the buffer so that an empty and a full buffer can be
* distinguished. An empty buffer will have the readPostion and the
* writePosition equal to each other. A full buffer will have
* the writePosition one less than the readPostion.
* <p>
* There are two important indexes into the buffer:
* The readPosition, and the writePosition. The Objects
* available to be read go from the readPosition to the writePosition,
* wrapping around the end of the buffer. The space available for writing
* goes from the write position to one less than the readPosition,
* wrapping around the end of the buffer.
*
* @since ostermillerutils 1.00.00
*/
protected ElementType[] buffer;
/**
* Index of the first Object available to be read.
*
* @since ostermillerutils 1.00.00
*/
protected volatile int readPosition = 0;
/**
* Index of the first Object available to be written.
*
* @since ostermillerutils 1.00.00
*/
protected volatile int writePosition = 0;
/**
* If this buffer is infinite (should resize itself when full)
*
* @since ostermillerutils 1.00.00
*/
protected volatile boolean infinite = false;
/**
* True if a write to a full buffer should block until the buffer
* has room, false if the write method should throw an IOException
*
* @since ostermillerutils 1.00.00
*/
protected boolean blockingWrite = true;
/**
* True when no more input is coming into this buffer. At that
* point reading from the buffer may return null if the buffer
* is empty, otherwise a read will block until an Object is available.
*
* @since ostermillerutils 1.00.00
*/
protected boolean inputDone = false;
/**
* Make this buffer ready for reuse. The contents of the buffer
* will be cleared and the streams associated with this buffer
* will be reopened if they had been closed.
*
* @since ostermillerutils 1.00.00
*/
public void clear(){
synchronized (this){
readPosition = 0;
writePosition = 0;
inputDone = false;
}
}
/**
* Get number of Objects that are available to be read.
* <p>
* Note that the number of Objects available plus
* the number of Objects free may not add up to the
* capacity of this buffer, as the buffer may reserve some
* space for other purposes.
*
* @return the size in Objects of this buffer
*
* @since ostermillerutils 1.00.00
*/
public int getAvailable(){
synchronized (this){
return available();
}
}
/**
* Get the number of Objects this buffer has free for
* writing.
* <p>
* Note that the number of Objects available plus
* the number of Objects free may not add up to the
* capacity of this buffer, as the buffer may reserve some
* space for other purposes.
*
* @return the available space in Objects of this buffer
*
* @since ostermillerutils 1.00.00
*/
public int getSpaceLeft(){
synchronized (this){
return spaceLeft();
}
}
/**
* Get the capacity of this buffer.
* <p>
* Note that the number of Objects available plus
* the number of Objects free may not add up to the
* capacity of this buffer, as the buffer may reserve some
* space for other purposes.
*
* @return the size in Objects of this buffer
*
* @since ostermillerutils 1.00.00
*/
public int getSize(){
synchronized (this){
return buffer.length;
}
}
@SuppressWarnings("unchecked") private ElementType[] createArray(int size){
return (ElementType[]) new Object[size];
}
/**
* double the size of the buffer
*
* @since ostermillerutils 1.00.00
*/
private void resize(){
ElementType[] newBuffer = createArray(buffer.length * 2);
int available = available();
if (readPosition <= writePosition){
// any space between the read and
// the first write needs to be saved.
// In this case it is all in one piece.
int length = writePosition - readPosition;
System.arraycopy(buffer, readPosition, newBuffer, 0, length);
} else {
int length1 = buffer.length - readPosition;
System.arraycopy(buffer, readPosition, newBuffer, 0, length1);
int length2 = writePosition;
System.arraycopy(buffer, 0, newBuffer, length1, length2);
}
buffer = newBuffer;
readPosition = 0;
writePosition = available;
}
/**
* Space available in the buffer which can be written.
*
* @since ostermillerutils 1.00.00
*/
private int spaceLeft(){
if (writePosition < readPosition){
// any space between the first write and
// the read except one Object is available.
// In this case it is all in one piece.
return (readPosition - writePosition - 1);
}
// space at the beginning and end.
return ((buffer.length - 1) - (writePosition - readPosition));
}
/**
* Objects available for reading.
*
* @since ostermillerutils 1.00.00
*/
private int available(){
if (readPosition <= writePosition){
// any space between the first read and
// the first write is available. In this case i
// is all in one piece.
return (writePosition - readPosition);
}
// space at the beginning and end.
return (buffer.length - (readPosition - writePosition));
}
/**
* Create a new buffer with a default capacity.
* Writing to a full buffer will block until space
* is available rather than throw an exception.
*
* @since ostermillerutils 1.00.00
*/
public CircularObjectBuffer(){
this (DEFAULT_SIZE, true);
}
/**
* Create a new buffer with given capacity.
* Writing to a full buffer will block until space
* is available rather than throw an exception.
* <p>
* Note that the buffer may reserve some Objects for
* special purposes and capacity number of Objects may
* not be able to be written to the buffer.
* <p>
* Note that if the buffer is of INFINITE_SIZE it will
* neither block or throw exceptions, but rather grow
* without bound.
*
* @param size desired capacity of the buffer in Objects or CircularObjectBuffer.INFINITE_SIZE.
*
* @since ostermillerutils 1.00.00
*/
public CircularObjectBuffer(int size){
this (size, true);
}
/**
* Create a new buffer with a default capacity and
* given blocking behavior.
*
* @param blockingWrite true writing to a full buffer should block
* until space is available, false if an exception should
* be thrown instead.
*
* @since ostermillerutils 1.00.00
*/
public CircularObjectBuffer(boolean blockingWrite){
this (DEFAULT_SIZE, blockingWrite);
}
/**
* Create a new buffer with the given capacity and
* blocking behavior.
* <p>
* Note that the buffer may reserve some Objects for
* special purposes and capacity number of Objects may
* not be able to be written to the buffer.
* <p>
* Note that if the buffer is of INFINITE_SIZE it will
* neither block or throw exceptions, but rather grow
* without bound.
*
* @param size desired capacity of the buffer in Objects or CircularObjectBuffer.INFINITE_SIZE.
* @param blockingWrite true writing to a full buffer should block
* until space is available, false if an exception should
* be thrown instead.
*
* @since ostermillerutils 1.00.00
*/
public CircularObjectBuffer(int size, boolean blockingWrite){
if (size == INFINITE_SIZE){
buffer = createArray(DEFAULT_SIZE);
infinite = true;
} else {
buffer = createArray(size);
infinite = false;
}
this.blockingWrite = blockingWrite;
}
/**
* Get a single Object from this buffer. This method should be called
* by the consumer.
* This method will block until a Object is available or no more
* objects are available.
*
* @return The Object read, or null if there are no more objects
* @throws InterruptedException if the thread is interrupted while waiting.
*
* @since ostermillerutils 1.00.00
*/
public ElementType read() throws InterruptedException {
while (true){
synchronized (this){
int available = available();
if (available > 0){
ElementType result = buffer[readPosition];
readPosition++;
if (readPosition == buffer.length){
readPosition = 0;
}
return result;
} else if (inputDone){
return null;
}
}
Thread.sleep(100);
}
}
/**
* Get Objects into an array from this buffer. This method should
* be called by the consumer.
* This method will block until some input is available,
* or there is no more input.
*
* @param buf Destination buffer.
* @return The number of Objects read, or -1 there will
* be no more objects available.
* @throws InterruptedException if the thread is interrupted while waiting.
*
* @since ostermillerutils 1.00.00
*/
public int read(ElementType[] buf) throws InterruptedException {
return read(buf, 0, buf.length);
}
/**
* Get Objects into a portion of an array from this buffer. This
* method should be called by the consumer.
* This method will block until some input is available,
* an I/O error occurs, or the end of the stream is reached.
*
* @param buf Destination buffer.
* @param off Offset at which to start storing Objects.
* @param len Maximum number of Objects to read.
* @return The number of Objects read, or -1 there will
* be no more objects available.
* @throws InterruptedException if the thread is interrupted while waiting.
*
* @since ostermillerutils 1.00.00
*/
public int read(ElementType[] buf, int off, int len) throws InterruptedException {
while (true){
synchronized (this){
int available = available();
if (available > 0){
int length = Math.min(len, available);
int firstLen = Math.min(length, buffer.length - readPosition);
int secondLen = length - firstLen;
System.arraycopy(buffer, readPosition, buf, off, firstLen);
if (secondLen > 0){
System.arraycopy(buffer, 0, buf, off+firstLen, secondLen);
readPosition = secondLen;
} else {
readPosition += length;
}
if (readPosition == buffer.length) {
readPosition = 0;
}
return length;
} else if (inputDone){
return -1;
}
}
Thread.sleep(100);
}
}
/**
* Skip Objects. This method should be used by the consumer
* when it does not care to examine some number of Objects.
* This method will block until some Objects are available,
* or there will be no more Objects available.
*
* @param n The number of Objects to skip
* @return The number of Objects actually skipped
* @throws IllegalArgumentException if n is negative.
* @throws InterruptedException if the thread is interrupted while waiting.
*
* @since ostermillerutils 1.00.00
*/
public long skip(long n) throws InterruptedException, IllegalArgumentException {
while (true){
synchronized (this){
int available = available();
if (available > 0){
int length = Math.min((int)n, available);
int firstLen = Math.min(length, buffer.length - readPosition);
int secondLen = length - firstLen;
if (secondLen > 0){
readPosition = secondLen;
} else {
readPosition += length;
}
if (readPosition == buffer.length) {
readPosition = 0;
}
return length;
} else if (inputDone){
return 0;
}
}
Thread.sleep(100);
}
}
/**
* This method should be used by the producer to signal to the consumer
* that the producer is done producing objects and that the consumer
* should stop asking for objects once it has used up buffered objects.
* <p>
* Once the producer has signaled that it is done, further write() invocations
* will cause an IllegalStateException to be thrown. Calling done() multiple times,
* however, has no effect.
*
* @since ostermillerutils 1.00.00
*/
public void done(){
synchronized (this){
inputDone = true;
}
}
/**
* Fill this buffer with array of Objects. This method should be called
* by the producer.
* If the buffer allows blocking writes, this method will block until
* all the data has been written rather than throw a BufferOverflowException.
*
* @param buf Array of Objects to be written
* @throws BufferOverflowException if buffer does not allow blocking writes
* and the buffer is full. If the exception is thrown, no data
* will have been written since the buffer was set to be non-blocking.
* @throws IllegalStateException if done() has been called.
* @throws InterruptedException if the write is interrupted.
*
* @since ostermillerutils 1.00.00
*/
public void write(ElementType[] buf) throws BufferOverflowException, IllegalStateException, InterruptedException {
write(buf, 0, buf.length);
}
/**
* Fill this buffer with a portion of an array of Objects.
* This method should be called by the producer.
* If the buffer allows blocking writes, this method will block until
* all the data has been written rather than throw an IOException.
*
* @param buf Array of Objects
* @param off Offset from which to start writing Objects
* @param len - Number of Objects to write
* @throws BufferOverflowException if buffer does not allow blocking writes
* and the buffer is full. If the exception is thrown, no data
* will have been written since the buffer was set to be non-blocking.
* @throws IllegalStateException if done() has been called.
* @throws InterruptedException if the write is interrupted.
*
* @since ostermillerutils 1.00.00
*/
public void write(ElementType[] buf, int off, int len) throws BufferOverflowException, IllegalStateException, InterruptedException {
while (len > 0){
synchronized (CircularObjectBuffer.this){
if (inputDone) throw new IllegalStateException("CircularObjectBuffer.done() has been called, CircularObjectBuffer.write() failed.");
int spaceLeft = spaceLeft();
while (infinite && spaceLeft < len){
resize();
spaceLeft = spaceLeft();
}
if (!blockingWrite && spaceLeft < len) throw new BufferOverflowException("CircularObjectBuffer is full; cannot write " + len + " Objects");
int realLen = Math.min(len, spaceLeft);
int firstLen = Math.min(realLen, buffer.length - writePosition);
int secondLen = Math.min(realLen - firstLen, buffer.length - readPosition - 1);
int written = firstLen + secondLen;
if (firstLen > 0){
System.arraycopy(buf, off, buffer, writePosition, firstLen);
}
if (secondLen > 0){
System.arraycopy(buf, off+firstLen, buffer, 0, secondLen);
writePosition = secondLen;
} else {
writePosition += written;
}
if (writePosition == buffer.length) {
writePosition = 0;
}
off += written;
len -= written;
}
if (len > 0){
Thread.sleep(100);
}
}
}
/**
* Add a single Object to this buffer. This method should be
* called by the producer.
* If the buffer allows blocking writes, this method will block until
* all the data has been written rather than throw an IOException.
*
* @param o Object to be written.
* @throws BufferOverflowException if buffer does not allow blocking writes
* and the buffer is full. If the exception is thrown, no data
* will have been written since the buffer was set to be non-blocking.
* @throws IllegalStateException if done() has been called.
* @throws InterruptedException if the write is interrupted.
*
* @since ostermillerutils 1.00.00
*/
public void write(ElementType o) throws BufferOverflowException, IllegalStateException, InterruptedException {
boolean written = false;
while (!written){
synchronized (CircularObjectBuffer.this){
if (inputDone) throw new IllegalStateException("CircularObjectBuffer.done() has been called, CircularObjectBuffer.write() failed.");
int spaceLeft = spaceLeft();
while (infinite && spaceLeft < 1){
resize();
spaceLeft = spaceLeft();
}
if (!blockingWrite && spaceLeft < 1) throw new BufferOverflowException("CircularObjectBuffer is full; cannot write 1 Object");
if (spaceLeft > 0){
buffer[writePosition] = o;
writePosition++;
if (writePosition == buffer.length) {
writePosition = 0;
}
written = true;
}
}
if (!written){
Thread.sleep(100);
}
}
}
} | 20,799 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
BufferOverflowException.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/util/BufferOverflowException.java | /*
* Buffer Overflow Exception
* Copyright (C) 2002-2010 Stephen Ostermiller
* http://ostermiller.org/contact.pl?regarding=Java+Utilities
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* See LICENSE.txt for details.
*/
package org.flashtool.util;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
/**
* An indication that there was a buffer overflow.
*
* @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
* @since ostermillerutils 1.00.00
*/
@Slf4j
public class BufferOverflowException extends IOException {
/**
* Serial version ID
*/
private static final long serialVersionUID = -322401823167626048L;
/**
* Create a new Exception
*
* @since ostermillerutils 1.00.00
*/
public BufferOverflowException(){
super();
}
/**
* Create a new Exception with the given message.
*
* @param msg Error message.
*
* @since ostermillerutils 1.00.00
*/
public BufferOverflowException(String msg){
super(msg);
}
} | 1,534 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
CircularByteBuffer.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/util/CircularByteBuffer.java | /*
* Circular Byte Buffer
* Copyright (C) 2002-2010 Stephen Ostermiller
* http://ostermiller.org/contact.pl?regarding=Java+Utilities
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* See LICENSE.txt for details.
*/
package org.flashtool.util;
import java.io.*;
import lombok.extern.slf4j.Slf4j;
/**
* Implements the Circular Buffer producer/consumer model for bytes.
* More information about this class is available from <a target="_top" href=
* "http://ostermiller.org/utils/CircularByteBuffer.html">ostermiller.org</a>.
* <p>
* Using this class is a simpler alternative to using a PipedInputStream
* and a PipedOutputStream. PipedInputStreams and PipedOutputStreams don't support the
* mark operation, don't allow you to control buffer sizes that they use,
* and have a more complicated API that requires instantiating two
* classes and connecting them.
* <p>
* This class is thread safe.
*
* @see CircularCharBuffer
* @see CircularObjectBuffer
*
* @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
* @since ostermillerutils 1.00.00
*/
@Slf4j
public class CircularByteBuffer {
/**
* The default size for a circular byte buffer.
*
* @since ostermillerutils 1.00.00
*/
private final static int DEFAULT_SIZE = 1024;
/**
* A buffer that will grow as things are added.
*
* @since ostermillerutils 1.00.00
*/
public final static int INFINITE_SIZE = -1;
/**
* The circular buffer.
* <p>
* The actual capacity of the buffer is one less than the actual length
* of the buffer so that an empty and a full buffer can be
* distinguished. An empty buffer will have the markPostion and the
* writePosition equal to each other. A full buffer will have
* the writePosition one less than the markPostion.
* <p>
* There are three important indexes into the buffer:
* The readPosition, the writePosition, and the markPosition.
* If the InputStream has never been marked, the readPosition and
* the markPosition should always be the same. The bytes
* available to be read go from the readPosition to the writePosition,
* wrapping around the end of the buffer. The space available for writing
* goes from the write position to one less than the markPosition,
* wrapping around the end of the buffer. The bytes that have
* been saved to support a reset() of the InputStream go from markPosition
* to readPosition, wrapping around the end of the buffer.
*
* @since ostermillerutils 1.00.00
*/
protected byte[] buffer;
/**
* Index of the first byte available to be read.
*
* @since ostermillerutils 1.00.00
*/
protected volatile int readPosition = 0;
/**
* Index of the first byte available to be written.
*
* @since ostermillerutils 1.00.00
*/
protected volatile int writePosition = 0;
/**
* Index of the first saved byte. (To support stream marking.)
*
* @since ostermillerutils 1.00.00
*/
protected volatile int markPosition = 0;
/**
* Number of bytes that have to be saved
* to support mark() and reset() on the InputStream.
*
* @since ostermillerutils 1.00.00
*/
protected volatile int markSize = 0;
/**
* If this buffer is infinite (should resize itself when full)
*
* @since ostermillerutils 1.00.00
*/
protected volatile boolean infinite = false;
/**
* True if a write to a full buffer should block until the buffer
* has room, false if the write method should throw an IOException
*
* @since ostermillerutils 1.00.00
*/
protected boolean blockingWrite = true;
/**
* The InputStream that can empty this buffer.
*
* @since ostermillerutils 1.00.00
*/
protected InputStream in = new CircularByteBufferInputStream();
/**
* true if the close() method has been called on the InputStream
*
* @since ostermillerutils 1.00.00
*/
protected boolean inputStreamClosed = false;
/**
* The OutputStream that can fill this buffer.
*
* @since ostermillerutils 1.00.00
*/
protected OutputStream out = new CircularByteBufferOutputStream();
/**
* true if the close() method has been called on the OutputStream
*
* @since ostermillerutils 1.00.00
*/
protected boolean outputStreamClosed = false;
/**
* Make this buffer ready for reuse. The contents of the buffer
* will be cleared and the streams associated with this buffer
* will be reopened if they had been closed.
*
* @since ostermillerutils 1.00.00
*/
public void clear(){
synchronized (this){
readPosition = 0;
writePosition = 0;
markPosition = 0;
outputStreamClosed = false;
inputStreamClosed = false;
}
}
/**
* Retrieve a OutputStream that can be used to fill
* this buffer.
* <p>
* Write methods may throw a BufferOverflowException if
* the buffer is not large enough. A large enough buffer
* size must be chosen so that this does not happen or
* the caller must be prepared to catch the exception and
* try again once part of the buffer has been consumed.
*
*
* @return the producer for this buffer.
*
* @since ostermillerutils 1.00.00
*/
public OutputStream getOutputStream(){
return out;
}
/**
* Retrieve a InputStream that can be used to empty
* this buffer.
* <p>
* This InputStream supports marks at the expense
* of the buffer size.
*
* @return the consumer for this buffer.
*
* @since ostermillerutils 1.00.00
*/
public InputStream getInputStream(){
return in;
}
/**
* Get number of bytes that are available to be read.
* <p>
* Note that the number of bytes available plus
* the number of bytes free may not add up to the
* capacity of this buffer, as the buffer may reserve some
* space for other purposes.
*
* @return the size in bytes of this buffer
*
* @since ostermillerutils 1.00.00
*/
public int getAvailable(){
synchronized (this){
return available();
}
}
/**
* Get the number of bytes this buffer has free for
* writing.
* <p>
* Note that the number of bytes available plus
* the number of bytes free may not add up to the
* capacity of this buffer, as the buffer may reserve some
* space for other purposes.
*
* @return the available space in bytes of this buffer
*
* @since ostermillerutils 1.00.00
*/
public int getSpaceLeft(){
synchronized (this){
return spaceLeft();
}
}
/**
* Get the capacity of this buffer.
* <p>
* Note that the number of bytes available plus
* the number of bytes free may not add up to the
* capacity of this buffer, as the buffer may reserve some
* space for other purposes.
*
* @return the size in bytes of this buffer
*
* @since ostermillerutils 1.00.00
*/
public int getSize(){
synchronized (this){
return buffer.length;
}
}
/**
* double the size of the buffer
*
* @since ostermillerutils 1.00.00
*/
private void resize(){
byte[] newBuffer = new byte[buffer.length * 2];
int marked = marked();
int available = available();
if (markPosition <= writePosition){
// any space between the mark and
// the first write needs to be saved.
// In this case it is all in one piece.
int length = writePosition - markPosition;
System.arraycopy(buffer, markPosition, newBuffer, 0, length);
} else {
int length1 = buffer.length - markPosition;
System.arraycopy(buffer, markPosition, newBuffer, 0, length1);
int length2 = writePosition;
System.arraycopy(buffer, 0, newBuffer, length1, length2);
}
buffer = newBuffer;
markPosition = 0;
readPosition = marked;
writePosition = marked + available;
}
/**
* Space available in the buffer which can be written.
*
* @since ostermillerutils 1.00.00
*/
private int spaceLeft(){
if (writePosition < markPosition){
// any space between the first write and
// the mark except one byte is available.
// In this case it is all in one piece.
return (markPosition - writePosition - 1);
}
// space at the beginning and end.
return ((buffer.length - 1) - (writePosition - markPosition));
}
/**
* Bytes available for reading.
*
* @since ostermillerutils 1.00.00
*/
private int available(){
if (readPosition <= writePosition){
// any space between the first read and
// the first write is available. In this case i
// is all in one piece.
return (writePosition - readPosition);
}
// space at the beginning and end.
return (buffer.length - (readPosition - writePosition));
}
/**
* Bytes saved for supporting marks.
*
* @since ostermillerutils 1.00.00
*/
private int marked(){
if (markPosition <= readPosition){
// any space between the markPosition and
// the first write is marked. In this case i
// is all in one piece.
return (readPosition - markPosition);
}
// space at the beginning and end.
return (buffer.length - (markPosition - readPosition));
}
/**
* If we have passed the markSize reset the
* mark so that the space can be used.
*
* @since ostermillerutils 1.00.00
*/
private void ensureMark(){
if (marked() > markSize){
markPosition = readPosition;
markSize = 0;
}
}
/**
* Create a new buffer with a default capacity.
* Writing to a full buffer will block until space
* is available rather than throw an exception.
*
* @since ostermillerutils 1.00.00
*/
public CircularByteBuffer(){
this (DEFAULT_SIZE, true);
}
/**
* Create a new buffer with given capacity.
* Writing to a full buffer will block until space
* is available rather than throw an exception.
* <p>
* Note that the buffer may reserve some bytes for
* special purposes and capacity number of bytes may
* not be able to be written to the buffer.
* <p>
* Note that if the buffer is of INFINITE_SIZE it will
* neither block or throw exceptions, but rather grow
* without bound.
*
* @param size desired capacity of the buffer in bytes or CircularByteBuffer.INFINITE_SIZE.
*
* @since ostermillerutils 1.00.00
*/
public CircularByteBuffer(int size){
this (size, true);
}
/**
* Create a new buffer with a default capacity and
* given blocking behavior.
*
* @param blockingWrite true writing to a full buffer should block
* until space is available, false if an exception should
* be thrown instead.
*
* @since ostermillerutils 1.00.00
*/
public CircularByteBuffer(boolean blockingWrite){
this (DEFAULT_SIZE, blockingWrite);
}
/**
* Create a new buffer with the given capacity and
* blocking behavior.
* <p>
* Note that the buffer may reserve some bytes for
* special purposes and capacity number of bytes may
* not be able to be written to the buffer.
* <p>
* Note that if the buffer is of INFINITE_SIZE it will
* neither block or throw exceptions, but rather grow
* without bound.
*
* @param size desired capacity of the buffer in bytes or CircularByteBuffer.INFINITE_SIZE.
* @param blockingWrite true writing to a full buffer should block
* until space is available, false if an exception should
* be thrown instead.
*
* @since ostermillerutils 1.00.00
*/
public CircularByteBuffer(int size, boolean blockingWrite){
if (size == INFINITE_SIZE){
buffer = new byte[DEFAULT_SIZE];
infinite = true;
} else {
buffer = new byte[size];
infinite = false;
}
this.blockingWrite = blockingWrite;
}
/**
* Class for reading from a circular byte buffer.
*
* @since ostermillerutils 1.00.00
*/
protected class CircularByteBufferInputStream extends InputStream {
/**
* Returns the number of bytes that can be read (or skipped over) from this
* input stream without blocking by the next caller of a method for this input
* stream. The next caller might be the same thread or or another thread.
*
* @return the number of bytes that can be read from this input stream without blocking.
* @throws IOException if the stream is closed.
*
* @since ostermillerutils 1.00.00
*/
@Override public int available() throws IOException {
synchronized (CircularByteBuffer.this){
if (inputStreamClosed) throw new IOException("InputStream has been closed, it is not ready.");
return (CircularByteBuffer.this.available());
}
}
/**
* Close the stream. Once a stream has been closed, further read(), available(),
* mark(), or reset() invocations will throw an IOException. Closing a
* previously-closed stream, however, has no effect.
*
* @throws IOException never.
*
* @since ostermillerutils 1.00.00
*/
@Override public void close() throws IOException {
synchronized (CircularByteBuffer.this){
inputStreamClosed = true;
}
}
/**
* Mark the present position in the stream. Subsequent calls to reset() will
* attempt to reposition the stream to this point.
* <p>
* The readAheadLimit must be less than the size of circular buffer, otherwise
* this method has no effect.
*
* @param readAheadLimit Limit on the number of bytes that may be read while
* still preserving the mark. After reading this many bytes, attempting to
* reset the stream will fail.
*
* @since ostermillerutils 1.00.00
*/
@Override public void mark(int readAheadLimit) {
synchronized (CircularByteBuffer.this){
//if (inputStreamClosed) throw new IOException("InputStream has been closed; cannot mark a closed InputStream.");
if (buffer.length - 1 > readAheadLimit) {
markSize = readAheadLimit;
markPosition = readPosition;
}
}
}
/**
* Tell whether this stream supports the mark() operation.
*
* @return true, mark is supported.
*
* @since ostermillerutils 1.00.00
*/
@Override public boolean markSupported() {
return true;
}
/**
* Read a single byte.
* This method will block until a byte is available, an I/O error occurs,
* or the end of the stream is reached.
*
* @return The byte read, as an integer in the range 0 to 255 (0x00-0xff),
* or -1 if the end of the stream has been reached
* @throws IOException if the stream is closed.
*
* @since ostermillerutils 1.00.00
*/
@Override public int read() throws IOException {
while (true){
synchronized (CircularByteBuffer.this){
if (inputStreamClosed) throw new IOException("InputStream has been closed; cannot read from a closed InputStream.");
int available = CircularByteBuffer.this.available();
if (available > 0){
int result = buffer[readPosition] & 0xff;
readPosition++;
if (readPosition == buffer.length){
readPosition = 0;
}
ensureMark();
return result;
} else if (outputStreamClosed){
return -1;
}
}
try {
Thread.sleep(100);
} catch(Exception x){
throw new IOException("Blocking read operation interrupted.");
}
}
}
/**
* Read bytes into an array.
* This method will block until some input is available,
* an I/O error occurs, or the end of the stream is reached.
*
* @param cbuf Destination buffer.
* @return The number of bytes read, or -1 if the end of
* the stream has been reached
* @throws IOException if the stream is closed.
*
* @since ostermillerutils 1.00.00
*/
@Override public int read(byte[] cbuf) throws IOException {
return read(cbuf, 0, cbuf.length);
}
/**
* Read bytes into a portion of an array.
* This method will block until some input is available,
* an I/O error occurs, or the end of the stream is reached.
*
* @param cbuf Destination buffer.
* @param off Offset at which to start storing bytes.
* @param len Maximum number of bytes to read.
* @return The number of bytes read, or -1 if the end of
* the stream has been reached
* @throws IOException if the stream is closed.
*
* @since ostermillerutils 1.00.00
*/
@Override public int read(byte[] cbuf, int off, int len) throws IOException {
while (true){
synchronized (CircularByteBuffer.this){
if (inputStreamClosed) throw new IOException("InputStream has been closed; cannot read from a closed InputStream.");
int available = CircularByteBuffer.this.available();
if (available > 0){
int length = Math.min(len, available);
int firstLen = Math.min(length, buffer.length - readPosition);
int secondLen = length - firstLen;
System.arraycopy(buffer, readPosition, cbuf, off, firstLen);
if (secondLen > 0){
System.arraycopy(buffer, 0, cbuf, off+firstLen, secondLen);
readPosition = secondLen;
} else {
readPosition += length;
}
if (readPosition == buffer.length) {
readPosition = 0;
}
ensureMark();
return length;
} else if (outputStreamClosed){
return -1;
}
}
try {
Thread.sleep(100);
} catch(Exception x){
throw new IOException("Blocking read operation interrupted.");
}
}
}
/**
* Reset the stream.
* If the stream has been marked, then attempt to reposition i
* at the mark. If the stream has not been marked, or more bytes
* than the readAheadLimit have been read, this method has no effect.
*
* @throws IOException if the stream is closed.
*
* @since ostermillerutils 1.00.00
*/
@Override public void reset() throws IOException {
synchronized (CircularByteBuffer.this){
if (inputStreamClosed) throw new IOException("InputStream has been closed; cannot reset a closed InputStream.");
readPosition = markPosition;
}
}
/**
* Skip bytes.
* This method will block until some bytes are available,
* an I/O error occurs, or the end of the stream is reached.
*
* @param n The number of bytes to skip
* @return The number of bytes actually skipped
* @throws IllegalArgumentException if n is negative.
* @throws IOException if the stream is closed.
*
* @since ostermillerutils 1.00.00
*/
@Override public long skip(long n) throws IOException, IllegalArgumentException {
while (true){
synchronized (CircularByteBuffer.this){
if (inputStreamClosed) throw new IOException("InputStream has been closed; cannot skip bytes on a closed InputStream.");
int available = CircularByteBuffer.this.available();
if (available > 0){
int length = Math.min((int)n, available);
int firstLen = Math.min(length, buffer.length - readPosition);
int secondLen = length - firstLen;
if (secondLen > 0){
readPosition = secondLen;
} else {
readPosition += length;
}
if (readPosition == buffer.length) {
readPosition = 0;
}
ensureMark();
return length;
} else if (outputStreamClosed){
return 0;
}
}
try {
Thread.sleep(100);
} catch(Exception x){
throw new IOException("Blocking read operation interrupted.");
}
}
}
}
/**
* Class for writing to a circular byte buffer.
* If the buffer is full, the writes will either block
* until there is some space available or throw an IOException
* based on the CircularByteBuffer's preference.
*
* @since ostermillerutils 1.00.00
*/
protected class CircularByteBufferOutputStream extends OutputStream {
/**
* Close the stream, flushing it first.
* This will cause the InputStream associated with this circular buffer
* to read its last bytes once it empties the buffer.
* Once a stream has been closed, further write() or flush() invocations
* will cause an IOException to be thrown. Closing a previously-closed stream,
* however, has no effect.
*
* @throws IOException never.
*
* @since ostermillerutils 1.00.00
*/
@Override public void close() throws IOException {
synchronized (CircularByteBuffer.this){
if (!outputStreamClosed){
flush();
}
outputStreamClosed = true;
}
}
/**
* Flush the stream.
*
* @throws IOException if the stream is closed.
*
* @since ostermillerutils 1.00.00
*/
@Override public void flush() throws IOException {
synchronized (CircularByteBuffer.this){
if (outputStreamClosed) throw new IOException("OutputStream has been closed; cannot flush a closed OutputStream.");
if (inputStreamClosed) throw new IOException("Buffer closed by inputStream; cannot flush.");
}
// this method needs to do nothing
}
/**
* Write an array of bytes.
* If the buffer allows blocking writes, this method will block until
* all the data has been written rather than throw an IOException.
*
* @param cbuf Array of bytes to be written
* @throws BufferOverflowException if buffer does not allow blocking writes
* and the buffer is full. If the exception is thrown, no data
* will have been written since the buffer was set to be non-blocking.
* @throws IOException if the stream is closed, or the write is interrupted.
*
* @since ostermillerutils 1.00.00
*/
@Override public void write(byte[] cbuf) throws IOException {
write(cbuf, 0, cbuf.length);
}
/**
* Write a portion of an array of bytes.
* If the buffer allows blocking writes, this method will block until
* all the data has been written rather than throw an IOException.
*
* @param cbuf Array of bytes
* @param off Offset from which to start writing bytes
* @param len - Number of bytes to write
* @throws BufferOverflowException if buffer does not allow blocking writes
* and the buffer is full. If the exception is thrown, no data
* will have been written since the buffer was set to be non-blocking.
* @throws IOException if the stream is closed, or the write is interrupted.
*
* @since ostermillerutils 1.00.00
*/
@Override public void write(byte[] cbuf, int off, int len) throws IOException {
while (len > 0){
synchronized (CircularByteBuffer.this){
if (outputStreamClosed) throw new IOException("OutputStream has been closed; cannot write to a closed OutputStream.");
if (inputStreamClosed) throw new IOException("Buffer closed by InputStream; cannot write to a closed buffer.");
int spaceLeft = spaceLeft();
while (infinite && spaceLeft < len){
resize();
spaceLeft = spaceLeft();
}
if (!blockingWrite && spaceLeft < len) throw new BufferOverflowException("CircularByteBuffer is full; cannot write " + len + " bytes");
int realLen = Math.min(len, spaceLeft);
int firstLen = Math.min(realLen, buffer.length - writePosition);
int secondLen = Math.min(realLen - firstLen, buffer.length - markPosition - 1);
int written = firstLen + secondLen;
if (firstLen > 0){
System.arraycopy(cbuf, off, buffer, writePosition, firstLen);
}
if (secondLen > 0){
System.arraycopy(cbuf, off+firstLen, buffer, 0, secondLen);
writePosition = secondLen;
} else {
writePosition += written;
}
if (writePosition == buffer.length) {
writePosition = 0;
}
off += written;
len -= written;
}
if (len > 0){
try {
Thread.sleep(100);
} catch(Exception x){
throw new IOException("Waiting for available space in buffer interrupted.");
}
}
}
}
/**
* Write a single byte.
* The byte to be written is contained in the 8 low-order bits of the
* given integer value; the 24 high-order bits are ignored.
* If the buffer allows blocking writes, this method will block until
* all the data has been written rather than throw an IOException.
*
* @param c number of bytes to be written
* @throws BufferOverflowException if buffer does not allow blocking writes
* and the buffer is full.
* @throws IOException if the stream is closed, or the write is interrupted.
*
* @since ostermillerutils 1.00.00
*/
@Override public void write(int c) throws IOException {
boolean written = false;
while (!written){
synchronized (CircularByteBuffer.this){
if (outputStreamClosed) throw new IOException("OutputStream has been closed; cannot write to a closed OutputStream.");
if (inputStreamClosed) throw new IOException("Buffer closed by InputStream; cannot write to a closed buffer.");
int spaceLeft = spaceLeft();
while (infinite && spaceLeft < 1){
resize();
spaceLeft = spaceLeft();
}
if (!blockingWrite && spaceLeft < 1) throw new BufferOverflowException("CircularByteBuffer is full; cannot write 1 byte");
if (spaceLeft > 0){
buffer[writePosition] = (byte)(c & 0xff);
writePosition++;
if (writePosition == buffer.length) {
writePosition = 0;
}
written = true;
}
}
if (!written){
try {
Thread.sleep(100);
} catch(Exception x){
throw new IOException("Waiting for available space in buffer interrupted.");
}
}
}
}
}
} | 30,418 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
HexDump.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/util/HexDump.java | package org.flashtool.util;
import java.io.*;
import java.text.DecimalFormat;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class HexDump
{
private HexDump()
{
}
public static synchronized void dump(byte data[], long offset, OutputStream stream, int index, int length)
throws IOException, ArrayIndexOutOfBoundsException, IllegalArgumentException
{
if(index < 0 || index >= data.length)
throw new ArrayIndexOutOfBoundsException((new StringBuilder("illegal index: ")).append(index).append(" into array of length ").append(data.length).toString());
if(stream == null)
throw new IllegalArgumentException("cannot write to nullstream");
long display_offset = offset + (long)index;
StringBuffer buffer = new StringBuffer(74);
int data_length = Math.min(data.length, index + length);
for(int j = index; j < data_length; j += 16)
{
int chars_read = data_length - j;
if(chars_read > 16)
chars_read = 16;
buffer.append(dump(display_offset)).append(' ');
for(int k = 0; k < 16; k++)
{
if(k < chars_read)
buffer.append(dump(data[k + j]));
else
buffer.append(" ");
buffer.append(' ');
}
for(int k = 0; k < chars_read; k++)
if(data[k + j] >= 32 && data[k + j] < 127)
buffer.append((char)data[k + j]);
else
buffer.append('.');
buffer.append(EOL);
stream.write(buffer.toString().getBytes());
stream.flush();
buffer.setLength(0);
display_offset += chars_read;
}
}
public static synchronized void dump(byte data[], long offset, OutputStream stream, int index)
throws IOException, ArrayIndexOutOfBoundsException, IllegalArgumentException
{
dump(data, offset, stream, index, data.length - index);
}
public static String dump(byte data[], long offset, int index)
{
if(index < 0 || index >= data.length)
throw new ArrayIndexOutOfBoundsException((new StringBuilder("illegal index: ")).append(index).append(" into array of length ").append(data.length).toString());
long display_offset = offset + (long)index;
StringBuffer buffer = new StringBuffer(74);
for(int j = index; j < data.length; j += 16)
{
int chars_read = data.length - j;
if(chars_read > 16)
chars_read = 16;
buffer.append(dump(display_offset)).append(' ');
for(int k = 0; k < 16; k++)
{
if(k < chars_read)
buffer.append(dump(data[k + j]));
else
buffer.append(" ");
buffer.append(' ');
}
for(int k = 0; k < chars_read; k++)
if(data[k + j] >= 32 && data[k + j] < 127)
buffer.append((char)data[k + j]);
else
buffer.append('.');
buffer.append(EOL);
display_offset += chars_read;
}
return buffer.toString();
}
private static String dump(long value)
{
StringBuffer buf = new StringBuffer();
buf.setLength(0);
for(int j = 0; j < 8; j++)
buf.append(_hexcodes[(int)(value >> _shifts[(j + _shifts.length) - 8]) & 0xf]);
return buf.toString();
}
private static String dump(byte value)
{
StringBuffer buf = new StringBuffer();
buf.setLength(0);
for(int j = 0; j < 2; j++)
buf.append(_hexcodes[value >> _shifts[j + 6] & 0xf]);
return buf.toString();
}
public static String toHex(byte value[])
{
if (value==null) return "";
if (value.length==0) return "";
StringBuffer retVal = new StringBuffer();
for(int x = 0; x < value.length; x++)
{
retVal.append(toHex(value[x]));
if (x<value.length-1)
retVal.append(" ");
}
return retVal.toString();
}
public static String toHex(byte value[], int bytesPerLine)
{
int digits = (int)Math.round(Math.log(value.length) / Math.log(10D) + 0.5D);
StringBuffer formatString = new StringBuffer();
for(int i = 0; i < digits; i++)
formatString.append('0');
formatString.append(": ");
DecimalFormat format = new DecimalFormat(formatString.toString());
StringBuffer retVal = new StringBuffer();
retVal.append(format.format(0L));
int i = -1;
for(int x = 0; x < value.length; x++)
{
if(++i == bytesPerLine)
{
retVal.append('\n');
retVal.append(format.format(x));
i = 0;
}
retVal.append(toHex(value[x]));
retVal.append(", ");
}
return retVal.toString();
}
public static String toHex(short value)
{
return toHex(value, 4);
}
public static String toHex(byte value)
{
return toHex(value, 2);
}
public static String toHex(int value)
{
return toHex(value, 8);
}
public static String toHex(long value)
{
return toHex(value, 16);
}
private static String toHex(long value, int digits)
{
StringBuffer result = new StringBuffer(digits);
for(int j = 0; j < digits; j++)
result.append(_hexcodes[(int)(value >> _shifts[j + (16 - digits)] & 15L)]);
return result.toString();
}
public static void dump(InputStream in, PrintStream out, int start, int bytesToDump)
throws IOException
{
ByteArrayOutputStream buf = new ByteArrayOutputStream();
if(bytesToDump == -1)
{
for(int c = in.read(); c != -1; c = in.read())
buf.write(c);
} else
{
for(int bytesRemaining = bytesToDump; bytesRemaining-- > 0;)
{
int c = in.read();
if(c == -1)
break;
buf.write(c);
}
}
byte data[] = buf.toByteArray();
dump(data, 0L, ((OutputStream) (out)), start, data.length);
}
public static final String EOL = System.getProperty("line.separator");
private static final char _hexcodes[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'
};
private static final int _shifts[] = {
60, 56, 52, 48, 44, 40, 36, 32, 28, 24,
20, 16, 12, 8, 4, 0
};
}
| 6,786 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
XperiFirm.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/util/XperiFirm.java | package org.flashtool.util;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.flashtool.flashsystem.Bundle;
import org.flashtool.flashsystem.BundleEntry;
import org.flashtool.flashsystem.BundleMetaData;
import org.flashtool.flashsystem.SeusSinTool;
import org.flashtool.gui.tools.WidgetTask;
import org.flashtool.system.DeviceEntry;
import org.flashtool.system.Devices;
import org.flashtool.system.OS;
import org.flashtool.system.ProcessBuilderWrapper;
import org.flashtool.system.TextFile;
import org.flashtool.system.XMLFwInfo;
import org.flashtool.xmlcombiner.XmlCombiner;
import org.jdom2.JDOMException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class XperiFirm {
static Shell _parent;
public static void run(Shell parent) throws IOException,JDOMException {
_parent = parent;
TextFile tf=null;
String version = null;
String downloadurl=null;
try {
File f = new File(OS.getFolderUserFlashtool()+File.separator+"XperiFirm.exe.config");
if (f.exists()) f.delete();
version = IOUtils.toString(new URL("http://www.iagucool.com/xperifirm/version"),Charset.forName("UTF-8"));
version = version.substring(0,version.indexOf("|"));
downloadurl = IOUtils.toString(new URL("http://www.iagucool.com/xperifirm/download"),Charset.forName("UTF-8"));
tf = new TextFile(OS.getFolderUserFlashtool()+File.separator+"XperiFirm.version","ISO8859-15");
tf.readLines();
if (!version.equals(tf.getLines().iterator().next())) {
tf.open(false);
log.info("Downloading latest XperiFirm");
OS.unpackArchive(new URL(downloadurl), new File(OS.getFolderUserFlashtool()));
tf.write(version);
tf.close();
}
} catch (Exception fne) {
if (tf!=null) {
tf.open(false);
log.info("Downloading latest XperiFirm");
OS.unpackArchive(new URL(downloadurl), new File(OS.getFolderUserFlashtool())); tf.write(version);
tf.write(version);
tf.close();
}
}
ProcessBuilderWrapper command=null;
try {
List<String> cmdargs = new ArrayList<String>();
if (OS.getName().equals("windows")) {
cmdargs.add(OS.getPathXperiFirm());
cmdargs.add("-o");
cmdargs.add("\""+OS.getFolderFirmwaresDownloaded()+"\"");
}
else {
cmdargs.add("sh");
cmdargs.add(OS.getPathXperiFirmWrapper());
cmdargs.add(OS.getPathXperiFirm());
cmdargs.add(OS.getFolderFirmwaresDownloaded());
}
command = new ProcessBuilderWrapper(cmdargs);
}
catch (Exception e) {
log.warn(command.getStdOut()+" / "+command.getStdErr());
}
String[] downloaded = new File(OS.getFolderFirmwaresDownloaded()).list();
for (int i = 0; i<downloaded.length;i++) {
log.info(downloaded[i]);
File bundled = new File(OS.getFolderFirmwaresDownloaded()+File.separator+downloaded[i]+File.separator+"bundled");
if (bundled.exists()) continue;
File fwinfo = new File(OS.getFolderFirmwaresDownloaded()+File.separator+downloaded[i]+File.separator+"fwinfo.xml");
if (fwinfo.exists()) {
XMLFwInfo info = null;
try {
info = new XMLFwInfo(fwinfo);
} catch (Exception e) {}
if (info!=null) {
log.info("Creating bundle for "+info.getProduct()+" "+info.getOperator()+" "+info.getVersion());
try {
info.setOperator(info.getOperator().replaceAll("/", "-"));
createBundle(OS.getFolderFirmwaresDownloaded()+File.separator+downloaded[i],info);
} catch (Exception e) {
log.error(e.getMessage());
}
}
}
}
}
public static void createBundle(String sourcefolder,XMLFwInfo info) throws Exception {
BundleMetaData meta = new BundleMetaData();
meta.clear();
File srcdir = new File(sourcefolder);
File[] chld = srcdir.listFiles();
boolean xperifirmdecrypted=true;
String decryptfolder="";
String updatexml="";
for(int i = 0; i < chld.length; i++) {
if (chld[i].getName().toUpperCase().startsWith("FILE")) {
decryptfolder=chld[i].getParentFile().getAbsolutePath()+File.separator+"decrypted";
SeusSinTool.decryptAndExtract(chld[i].getAbsolutePath());
xperifirmdecrypted=false;
}
}
if (!xperifirmdecrypted) {
File update = new File(decryptfolder+File.separator+"update.xml");
File update1 = new File(decryptfolder+File.separator+"update1.xml");
File newupdate = new File(decryptfolder+File.separator+"update2.xml");
if (update.exists() && update1.exists()) {
XmlCombiner combiner = new XmlCombiner();
FileInputStream fi1 = new FileInputStream(update);
combiner.combine(fi1);
FileInputStream fi2 = new FileInputStream(update1);
combiner.combine(fi2);
FileOutputStream fo = new FileOutputStream(newupdate);
combiner.buildDocument(fo);
fi1.close();
fi2.close();
fo.close();
update.delete();
update1.delete();
newupdate.renameTo(update);
}
}
if (!xperifirmdecrypted) {
srcdir = new File(sourcefolder+File.separator+"decrypted");
chld = srcdir.listFiles();
}
for(int i = 0; i < chld.length; i++) {
if (chld[i].getName().toUpperCase().endsWith("FSC") || chld[i].getName().toUpperCase().endsWith("SIN") || (chld[i].getName().toUpperCase().endsWith("TA") && !chld[i].getName().toUpperCase().contains("SIMLOCK")) || (chld[i].getName().toUpperCase().endsWith("XML") && (!chld[i].getName().toUpperCase().contains("UPDATE") && !chld[i].getName().toUpperCase().contains("FWINFO")))) {
meta.process(new BundleEntry(chld[i]));
}
if (chld[i].getName().toUpperCase().contains("UPDATE")) {
updatexml=chld[i].getAbsolutePath();
}
}
File srcbootdir = new File(srcdir.getAbsolutePath()+File.separator+"boot");
if (srcbootdir.exists()) {
chld = srcbootdir.listFiles();
for(int i = 0; i < chld.length; i++) {
if (chld[i].getName().toUpperCase().endsWith("XML")) {
meta.process(new BundleEntry(chld[i]));
}
}
}
File srcpartzip = new File(srcdir.getAbsolutePath()+File.separator+"partition.zip");
if (srcpartzip.exists()) {
ZipFile zip = new ZipFile(srcpartzip);
log.info("Extracting "+zip.getName());
String subfolder = srcdir.getAbsolutePath()+File.separator+"partition";
new File(subfolder).mkdirs();
File xmlpartition = new File(subfolder+File.separator+"partition_delivery.xml");
PrintWriter fw = new PrintWriter(xmlpartition);
fw.println("<PARTITION_DELIVERY FORMAT=\"1\">");
fw.println(" <PARTITION_IMAGES>");
Enumeration<? extends ZipEntry> entries = zip.entries();
while ( entries.hasMoreElements() ) {
ZipEntry entry = entries.nextElement();
fw.println(" <FILE PATH=\""+entry.getName()+"\"/>");
InputStream entryStream = zip.getInputStream(entry);
File out = new File(subfolder+File.separator+entry.getName());
OS.writeToFile(entryStream, out);
entryStream.close();
}
fw.println(" </PARTITION_IMAGES>");
fw.println("</PARTITION_DELIVERY>");
fw.flush();
fw.close();
zip.close();
srcpartzip.delete();
}
File srcpartdir = new File(srcdir.getAbsolutePath()+File.separator+"partition");
if (srcpartdir.exists()) {
chld = srcpartdir.listFiles();
for(int i = 0; i < chld.length; i++) {
if (chld[i].getName().toUpperCase().endsWith("XML")) {
meta.process(new BundleEntry(chld[i]));
}
}
}
Bundle b = new Bundle();
b.setMeta(meta);
b.setNoErase(updatexml);
b.setDevice(info.getModel());
b.setVersion(info.getVersion());
b.setBranding(info.getOperator());
b.setCDA(info.getCDA());
b.setRevision(info.getRevision());
b.setCmd25("false");
if (!b.hasFsc()) {
DeviceEntry dev = Devices.getDeviceFromVariant(info.getModel());
if (dev!=null) {
String fscpath = dev.getFlashScript(info.getVersion(),info.getModel());
File fsc = new File(fscpath);
if (fsc.exists()) {
String result = WidgetTask.openYESNOBox(_parent, "A FSC script is found : "+fsc.getName()+". Do you want to add it ?");
if (Integer.parseInt(result)==SWT.YES) {
b.setFsc(fsc);
}
}
}
}
b.createFTF();
TextFile tf = new TextFile(sourcefolder+File.separator+"bundled","ISO8859-15");
tf.open(true);
tf.close();
}
} | 8,572 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
BytesUtil.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/util/BytesUtil.java | package org.flashtool.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.Arrays;
import java.lang.Byte;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class BytesUtil {
private static long pivot[];
static final String HEXES = "0123456789ABCDEF";
public static byte[] getBytesWord(int paramInt1, int paramInt2)
{
// int m = 256;
int i = paramInt2;
if ((paramInt2 < 1) || (paramInt2 > 4))
i = 4;
byte[] arrayOfByte = new byte[i];
int j = 0;
int k;
k = i - 1;
do
{
arrayOfByte[k] = (byte)(paramInt1 >> j & 0xFF);
j += 8;
k--;
}
while (k >= 0);
return arrayOfByte;
}
public static byte[] getBytesWord(long paramLong, int paramInt)
{
//int m = 256;
int i = paramInt;
if ((paramInt < 1) || (paramInt > 8))
i = 8;
byte[] arrayOfByte1 = new byte[8];
arrayOfByte1[0] = (byte)(int)(paramLong >>> 56);
arrayOfByte1[1] = (byte)(int)(paramLong >>> 48);
arrayOfByte1[2] = (byte)(int)(paramLong >>> 40);
arrayOfByte1[3] = (byte)(int)(paramLong >>> 32);
arrayOfByte1[4] = (byte)(int)(paramLong >>> 24);
arrayOfByte1[5] = (byte)(int)(paramLong >>> 16);
arrayOfByte1[6] = (byte)(int)(paramLong >>> 8);
arrayOfByte1[7] = (byte)(int)(paramLong >>> 0);
byte[] localObject = new byte[i];
int j = 8 - i;
int k = 0;
do
{
localObject[k] = arrayOfByte1[j];
j++;
k++;
}
while (k < i);
return localObject;
}
public static byte[] bytesconcat(byte[] paramArrayOfByte1, byte[] paramArrayOfByte2)
{
byte[] arrayOfByte = (byte[])null;
if ((paramArrayOfByte1 == null) && (paramArrayOfByte2 != null))
{
arrayOfByte = new byte[paramArrayOfByte2.length];
System.arraycopy(paramArrayOfByte2, 0, arrayOfByte, 0, paramArrayOfByte2.length);
}
else if ((paramArrayOfByte1 != null) && (paramArrayOfByte2 == null))
{
arrayOfByte = new byte[paramArrayOfByte1.length];
System.arraycopy(paramArrayOfByte1, 0, arrayOfByte, 0, paramArrayOfByte1.length);
}
else if ((paramArrayOfByte1 != null) && (paramArrayOfByte2 != null))
{
arrayOfByte = new byte[paramArrayOfByte1.length + paramArrayOfByte2.length];
System.arraycopy(paramArrayOfByte1, 0, arrayOfByte, 0, paramArrayOfByte1.length);
System.arraycopy(paramArrayOfByte2, 0, arrayOfByte, paramArrayOfByte1.length, paramArrayOfByte2.length);
}
return arrayOfByte;
}
public static int getInt(byte[] paramArrayOfByte)
{
if (paramArrayOfByte == null)
return 0;
byte[] arrayOfByte = paramArrayOfByte;
int i = arrayOfByte.length;
if (i < 4)
arrayOfByte = bytesconcat(new byte[4 - i], arrayOfByte);
return new BigInteger(arrayOfByte).intValue();
}
public static long getLong(byte[] paramArrayOfByte)
{
if (paramArrayOfByte == null)
return 0;
byte[] arrayOfByte = paramArrayOfByte;
int i = arrayOfByte.length;
if (i < 4)
arrayOfByte = bytesconcat(new byte[4 - i], arrayOfByte);
return new BigInteger(arrayOfByte).longValue();
}
public static byte[] getCRC32(byte[] paramArrayOfByte) {
long result = 0L;
for(int i = 0; i < paramArrayOfByte.length; i++) {
long l = 255L & (long)paramArrayOfByte[i] & 0xffffffffL;
long l1 = (result ^ l) & 0xffffffffL;
result = (result >> 8 & 0xffffffffL ^ pivot[(int)(l1 & 255L)]) & 0xffffffffL;
}
return getBytesWord(result & 0xffffffffL,4);
}
public static String getHex( byte [] raw ) {
if ( raw == null ) {
return null;
}
final StringBuilder hex = new StringBuilder( 2 * raw.length );
for ( final byte b : raw ) {
hex.append(HEXES.charAt((b & 0xF0) >> 4))
.append(HEXES.charAt((b & 0x0F)));
}
return hex.toString();
}
public static byte[] getBytes(String hexString) {
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
+ Character.digit(hexString.charAt(i+1), 16));
}
return data;
}
public static byte[] concatAll(byte[] first, byte[]... rest) {
int totalLength = first.length;
for (byte[] array : rest) {
totalLength += array.length;
}
byte[] result = Arrays.copyOf(first, totalLength);
int offset = first.length;
for (byte[] array : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
public static <T> T[] concatAll(T[] first, T[]... rest) {
int totalLength = first.length;
for (T[] array : rest) {
totalLength += array.length;
}
T[] result = Arrays.copyOf(first, totalLength);
int offset = first.length;
for (T[] array : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
public static byte[] getReply(byte[] reply, int nbread) {
if (reply.length==nbread) return reply;
byte[] newreply=null;
if (nbread > 0) {
newreply = new byte[nbread];
System.arraycopy(reply, 0, newreply, 0, nbread);
}
return newreply;
}
static
{
pivot = new long[256];
for(int i = 0; i < 256; i++)
{
long l1 = i;
for(int j = 0; j < 8; j++)
{
if(l1 % 2L == 0L)
l1 = l1 >> 1 & 0xffffffffL;
else
l1 = (l1 >> 1 ^ 0xedb88320L) & 0xffffffffL;
pivot[i] = l1;
}
}
}
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
throw new IOException("File too large for this operation");
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
public static byte[] revert(byte[] array) {
for (int i = 0, j = array.length - 1; i < j; i++, j--)
{
byte b = array[i];
array[i] = array[j];
array[j] = b;
}
return array;
}
public static int indexOf(byte[] source, byte[] match) {
for (int i = 0; i < source.length; i++) {
if (startsWith(source, i, match)) {
return i;
}
}
return -1;
}
public static boolean startsWith(byte[] source, byte[] match) {
return startsWith(source, 0, match);
}
/**
* Does this byte array begin with match array content?
*
* @param source
* Byte array to examine
* @param offset
* An offset into the <code>source</code> array
* @param match
* Byte array to locate in <code>source</code>
* @return true If the starting bytes are equal
*/
public static boolean startsWith(byte[] source, int offset, byte[] match) {
if (match.length > (source.length - offset)) {
return false;
}
for (int i = 0; i < match.length; i++) {
if (source[offset + i] != match[i]) {
return false;
}
}
return true;
}
public static byte[] intToBytes(int paramInt1, int paramInt2, boolean paramBoolean)
{
int i = paramInt2;
if ((paramInt2 < 1) || (paramInt2 > 4)) {
i = 4;
}
byte[] arrayOfByte = new byte[i];
int j = 0;
int k;
if (paramBoolean) {
for (k = 0; k < i; k++)
{
arrayOfByte[k] = ((byte)(paramInt1 >> j & 0xFF));
j += 8;
}
} else {
for (k = i - 1; k >= 0; k--)
{
arrayOfByte[k] = ((byte)(paramInt1 >> j & 0xFF));
j += 8;
}
}
return arrayOfByte;
}
} | 8,673 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
StreamSearcher.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/util/StreamSearcher.java | package org.flashtool.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
/**
* An efficient stream searching class based on the Knuth-Morris-Pratt algorithm.
* For more on the algorithm works see: http://www.inf.fh-flensburg.de/lang/algorithmen/pattern/kmpen.htm.
*/
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class StreamSearcher {
protected byte[] pattern_;
protected int[] borders_;
// An upper bound on pattern length for searching. Throws exception on longer patterns
public static final int MAX_PATTERN_LENGTH = 1024;
public StreamSearcher(byte[] pattern) {
setPattern(pattern);
}
/**
* Sets a new pattern for this StreamSearcher to use.
* @param pattern
* the pattern the StreamSearcher will look for in future calls to search(...)
*/
public void setPattern(byte[] pattern) {
if (pattern.length > MAX_PATTERN_LENGTH) {
throw new IllegalArgumentException("The maximum pattern length is " + MAX_PATTERN_LENGTH);
}
pattern_ = Arrays.copyOf(pattern, pattern.length);
borders_ = new int[pattern_.length + 1];
preProcess();
}
/**
* Searches for the next occurrence of the pattern in the stream, starting from the current stream position. Note
* that the position of the stream is changed. If a match is found, the stream points to the end of the match -- i.e. the
* byte AFTER the pattern. Else, the stream is entirely consumed. The latter is because InputStream semantics make it difficult to have
* another reasonable default, i.e. leave the stream unchanged.
*
* @return bytes consumed if found, -1 otherwise.
* @throws IOException
*/
public long search(InputStream stream) throws IOException {
long bytesRead = 0;
int b;
int j = 0;
while ((b = stream.read()) != -1) {
bytesRead++;
while (j >= 0 && (byte)b != pattern_[j]) {
j = borders_[j];
}
// Move to the next character in the pattern.
++j;
// If we've matched up to the full pattern length, we found it. Return,
// which will automatically save our position in the InputStream at the point immediately
// following the pattern match.
if (j == pattern_.length) {
return bytesRead-pattern_.length;
}
}
// No dice, Note that the stream is now completely consumed.
return -1;
}
/**
* Builds up a table of longest "borders" for each prefix of the pattern to find. This table is stored internally
* and aids in implementation of the Knuth-Moore-Pratt string search.
* <p>
* For more information, see: http://www.inf.fh-flensburg.de/lang/algorithmen/pattern/kmpen.htm.
*/
protected void preProcess() {
int i = 0;
int j = -1;
borders_[i] = j;
while (i < pattern_.length) {
while (j >= 0 && pattern_[i] != pattern_[j]) {
j = borders_[j];
}
borders_[++i] = ++j;
}
}
} | 2,945 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
SeusSinTool.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/SeusSinTool.java | package org.flashtool.flashsystem;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Enumeration;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.crypto.NoSuchPaddingException;
import org.flashtool.parsers.sin.SinFileException;
import org.flashtool.parsers.ta.TAFileParseException;
import org.flashtool.parsers.ta.TAFileParser;
import org.flashtool.system.AESInputStream;
import org.flashtool.system.OS;
import org.flashtool.system.RC4InputStream;
import org.flashtool.system.RC4OutputStream;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SeusSinTool {
public static void decryptAndExtract(String FILESET) throws Exception,FileNotFoundException,IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException {
File enc= new File(FILESET);
File dec = new File(enc.getParent()+File.separator+"decrypted_"+enc.getName());
if (!decrypt(enc,dec)) throw new Exception("Unable to decrypt "+FILESET);
String folder = enc.getParentFile().getAbsolutePath()+File.separator+"decrypted";
new File(folder).mkdirs();
log.info("Identifying fileset content");
ZipFile file=null;
try {
file = new ZipFile(dec.getAbsolutePath());
log.info("Found zip file. Extracting content");
Enumeration<? extends ZipEntry> entries = file.entries();
while ( entries.hasMoreElements() ) {
ZipEntry entry = entries.nextElement();
InputStream entryStream = file.getInputStream(entry);
File out = getFile(new File(folder+File.separator+entry.getName()));
OS.writeToFile(entryStream, out);
entryStream.close();
try {
if (!out.getName().toUpperCase().endsWith("SIN")) {
ZipFile subzip = new ZipFile(out);
log.info("Extracting "+out.getName());
String subfolder = folder + File.separator+entry.getName().substring(0,entry.getName().lastIndexOf("."));
new File(subfolder).mkdirs();
PrintWriter pw = null;
if (out.getName().equals("partition.zip")) {
pw = new PrintWriter(new File(subfolder+File.separator+"partition_delivery.xml"));
pw.println("<PARTITION_DELIVERY FORMAT=\"1\">");
pw.println(" <PARTITION_IMAGES>");
}
Enumeration<? extends ZipEntry> subentries = subzip.entries();
while ( subentries.hasMoreElements() ) {
ZipEntry subentry = subentries.nextElement();
if (pw!=null)
pw.println(" <FILE PATH=\""+subentry.getName()+"\"/>");
File subout = getFile(new File(subfolder+File.separator+subentry.getName()));
entryStream=subzip.getInputStream(subentry);
OS.writeToFile(entryStream, subout);
entryStream.close();
}
if (pw!=null) {
pw.println(" </PARTITION_IMAGES>");
pw.println("</PARTITION_DELIVERY>");
pw.flush();
pw.close();
}
subzip.close();
out.delete();
}
} catch (Exception e1) {}
}
file.close();
} catch (Exception e) {
try {
file.close();
} catch (Exception ex) {}
try {
org.flashtool.parsers.sin.SinFile sf = new org.flashtool.parsers.sin.SinFile(new File(dec.getAbsolutePath()));
if (sf.getType().equals("LOADER")) {
log.info("Found sin loader. Moving file to loader.sin");
dec.renameTo(getFile(new File(folder+File.separator+"loader.sin")));
}
if (sf.getType().equals("BOOT")) {
log.info("Found sin boot. Moving file to boot.sin");
dec.renameTo(getFile(new File(folder+File.separator+"boot.sin")));
}
} catch (SinFileException sine) {
try {
TAFileParser ta = new TAFileParser(new FileInputStream(dec.getAbsolutePath()));
log.info("Found ta file. Moving file to preset.ta");
dec.renameTo(getFile(new File(folder+File.separator+"preset.ta")));
} catch(TAFileParseException tae) {
log.error(dec.getAbsolutePath() + " is unrecognizable");
}
}
}
dec.delete();
}
public static boolean decrypt(File enc, File dec) {
if (decryptGzipped(enc,dec)) return true;
if (decryptAES(enc,dec)) return true;
if (decryptRC4(enc,dec)) return true;
return decryptAsIs(enc,dec);
}
public static boolean decryptAsIs(File enc, File dec) {
FileInputStream localFileInputStream=null;
try {
localFileInputStream = new FileInputStream(enc);
OS.writeToFile(localFileInputStream, dec);
localFileInputStream.close();
return true;
} catch (Exception e) {
try {
localFileInputStream.close();
dec.delete();
} catch (Exception e1) {}
return false;
}
}
public static boolean decryptGzipped(File enc, File dec) {
GZIPInputStream localGZIPInputStream=null;
try {
localGZIPInputStream = new GZIPInputStream(new FileInputStream(enc));
OS.writeToFile(localGZIPInputStream, dec);
localGZIPInputStream.close();
return true;
} catch (Exception e) {
try {
localGZIPInputStream.close();
dec.delete();
} catch (Exception e1) {}
return false;
}
}
public static boolean decryptAES(File enc, File dec) {
GZIPInputStream localEncodedStream = null;
try {
localEncodedStream = new GZIPInputStream(new AESInputStream(new FileInputStream(enc)));
OS.writeToFile(localEncodedStream, dec);
localEncodedStream.close();
return true;
} catch (Exception e) {
try {
localEncodedStream.close();
dec.delete();
} catch (Exception e1) {}
return false;
}
}
public static boolean decryptRC4(File enc, File dec) {
GZIPInputStream localEncodedStream = null;
try {
localEncodedStream = new GZIPInputStream(new RC4InputStream(new FileInputStream(enc)));
OS.writeToFile(localEncodedStream, dec);
localEncodedStream.close();
return true;
} catch (Exception e) {
try {
localEncodedStream.close();
dec.delete();
} catch (Exception e1) {}
return false;
}
}
public static void encryptRC4(String tgzfile) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
byte[] buf = new byte[1024];
try {
String outname = tgzfile.replaceAll(".tgz", ".sin");
FileInputStream in = new FileInputStream(tgzfile);
RC4OutputStream out = new RC4OutputStream(new FileOutputStream(outname));
int len;
while((len = in.read(buf)) >= 0) {
if (len > 0)
out.write(buf, 0, len);
}
out.flush();
out.close();
in.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public static File getFile(File file) {
if (file.exists()) {
int i=1;
String folder = file.getParent();
int point = file.getName().lastIndexOf(".");
if (point==-1) return file;
String name = file.getName().substring(0,point);
String ext = file.getName().substring(point+1);
while (new File(folder+File.separator+name+i+"."+ext).exists()) {
i++;
}
return new File(folder+File.separator+name+i+"."+ext);
}
else return file;
}
} | 7,655 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
S1Command.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/S1Command.java | package org.flashtool.flashsystem;
import java.io.IOException;
import org.flashtool.flashsystem.io.USBFlash;
import org.flashtool.logger.LogProgress;
import org.flashtool.logger.MyLogger;
import ch.qos.logback.classic.Level;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class S1Command {
private boolean _simulate;
private S1Packet reply;
public static final byte[] TA_FLASH_STARTUP_SHUTDOWN_RESULT_ONGOING = {
0x00, 0x00, 0x27, 0x74, 0x00, 0x00, 0x00, 0x01, 0x01};
public static final byte[] TA_FLASH_STARTUP_SHUTDOWN_RESULT_FINISHED = {
0x00, 0x00, 0x27, 0x74, 0x00, 0x00, 0x00, 0x01, 0x00};
public static final byte[] TA_MODEL = {
(byte)0x00, (byte)0x00, (byte)0x08, (byte)0xA2
};
public static final byte[] TA_SERIAL = {
(byte)0x00, (byte)0x00, (byte)0x13, (byte)0x24
};
public static final byte[] TA_DEVID3 = {
(byte)0x00, (byte)0x00, (byte)0x08, (byte)0x9D
};
public static final byte[] TA_DEVID4 = {
(byte)0x00, (byte)0x00, (byte)0x08, (byte)0x9A
};
public static final byte[] TA_DEVID5 = {
(byte)0x00, (byte)0x00, (byte)0x08, (byte)0x9E
};
static final int CMD01 = 1;
static final int CMD04 = 4;
static final int CMD05 = 5;
static final int CMD06 = 6;
static final int CMD07 = 7;
static final int CMD09 = 9;
static final int CMD10 = 10;
static final int CMD12 = 12;
static final int CMD13 = 13;
static final int CMD18 = 18;
static final int CMD25 = 25;
static final byte[] VALNULL = new byte[0];
static final byte[] VAL1 = new byte[] {1};
static final byte[] VAL2 = new byte[] {2};
public S1Command(boolean simulate) {
_simulate = simulate;
}
public S1Packet getLastReply() {
return reply;
}
private S1Packet writeCommand(int command, byte data[], boolean ongoing) throws X10FlashException, IOException {
S1Packet reply=null;
if (!_simulate) {
if (MyLogger.getLevel()==Level.DEBUG) {
try {
Thread.sleep(125);
}catch (Exception e) {}
}
S1Packet p = new S1Packet(command,data,ongoing);
try {
reply = USBFlash.writeS1(p);
}
catch (X10FlashException xe) {
xe.printStackTrace();
p.release();
throw new X10FlashException(xe.getMessage());
}
catch (IOException ioe) {
ioe.printStackTrace();
p.release();
throw new IOException(ioe.getMessage());
}
}
return reply;
}
public void send(int cmd, byte data[], boolean ongoing) throws X10FlashException, IOException
{
reply = writeCommand(cmd, data, ongoing);
if (reply.hasErrors()) {
reply = writeCommand(S1Command.CMD07, S1Command.VALNULL, false);
throw new X10FlashException(reply.getDataString());
}
while(reply.isMultiPacket()) {
S1Packet subreply = writeCommand(cmd, data, ongoing);
if (subreply.hasErrors()) {
writeCommand(S1Command.CMD07, S1Command.VALNULL, false);
throw new X10FlashException(reply.getDataString());
}
reply.mergeWith(subreply);
}
LogProgress.updateProgress();
}
} | 3,108 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
BootDeliveryException.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/BootDeliveryException.java | package org.flashtool.flashsystem;
public class BootDeliveryException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public BootDeliveryException(String msg){
super(msg);
}
public BootDeliveryException(String msg, Throwable t){
super(msg,t);
}
} | 314 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
Flasher.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/Flasher.java | package org.flashtool.flashsystem;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.flashtool.parsers.sin.SinFileException;
import org.flashtool.parsers.ta.TAUnit;
public interface Flasher {
public boolean flashmode();
public boolean open(boolean simulate);
public boolean open();
public void flash() throws X10FlashException, IOException;
public void close();
public String getPhoneProperty(String property);
public Bundle getBundle();
public TAUnit readTA(int partition, int unit) throws X10FlashException, IOException;
public void writeTA(int partition, TAUnit unit) throws X10FlashException, IOException;
public void sendLoader() throws FileNotFoundException, IOException, X10FlashException, SinFileException ;
public void backupTA();
public String getCurrentDevice();
public String getSerial();
public String getIMEI();
public String getRootingStatus();
public void setFlashState(boolean ongoing) throws IOException,X10FlashException ;
} | 1,020 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
S1Flasher.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/S1Flasher.java | package org.flashtool.flashsystem;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.io.IOException;
import org.bouncycastle.util.io.Streams;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.flashtool.flashsystem.io.USBFlash;
import org.flashtool.gui.tools.WidgetTask;
import org.flashtool.gui.tools.XMLBootConfig;
import org.flashtool.gui.tools.XMLBootDelivery;
import org.flashtool.logger.LogProgress;
import org.flashtool.parsers.sin.SinFile;
import org.flashtool.parsers.sin.SinFileException;
import org.flashtool.parsers.ta.TAFileParseException;
import org.flashtool.parsers.ta.TAFileParser;
import org.flashtool.parsers.ta.TAUnit;
import org.flashtool.system.DeviceEntry;
import org.flashtool.system.Devices;
import org.flashtool.system.OS;
import org.flashtool.system.TextFile;
import org.flashtool.util.BytesUtil;
import org.flashtool.util.HexDump;
import org.jdom2.JDOMException;
import com.google.common.primitives.Bytes;
import lombok.extern.slf4j.Slf4j;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
@Slf4j
public class S1Flasher implements Flasher {
private Bundle _bundle;
private S1Command cmd;
private LoaderInfo phoneprops = null;
private String firstRead = "";
private String cmd01string = "";
private boolean taopen = false;
private boolean modded_loader=false;
private String currentdevice = "";
private int maxS1packetsize = 0;
private String serial = "";
private Shell _curshell;
private HashMap<Long,TAUnit> TaPartition2 = new HashMap<Long,TAUnit>();
int loaderConfig = 0;
private XMLBootConfig bc=null;
public S1Flasher(Bundle bundle, Shell shell) {
_bundle=bundle;
_curshell = shell;
}
public String getCurrentDevice() {
if (!_bundle.simulate())
return currentdevice;
return _bundle.getDevice();
}
public void enableFinalVerification() throws X10FlashException,IOException {
loaderConfig &= 0xFFFFFFFE;
log.info("Enabling final verification");
setLoaderConfiguration();
}
public void disableFinalVerification() throws X10FlashException,IOException {
loaderConfig |= 0x1;
log.info("Disabling final verification");
setLoaderConfiguration();
}
public void enableEraseBeforeWrite() throws X10FlashException,IOException {
loaderConfig &= 0xFFFFFFFD;
log.info("Enabling erase before write");
setLoaderConfiguration();
}
public void disableEraseBeforeWrite() throws X10FlashException,IOException {
loaderConfig |= 0x2;
log.info("Disabling erase before write");
setLoaderConfiguration();
}
public void setLoaderConfiguration() throws X10FlashException,IOException {
byte[] data = BytesUtil.concatAll(BytesUtil.intToBytes(1, 2, false), BytesUtil.intToBytes(loaderConfig, 4, false));
if (!_bundle.simulate()) {
cmd.send(S1Command.CMD25,data,false);
}
}
public void setLoaderConfiguration(String param) throws X10FlashException,IOException {
String[] bytes = param.split(",");
if (bytes.length==1) bytes = param.split(" ");
byte[] data = new byte[bytes.length];
for (int i=0;i<bytes.length;i++) {
data[i]=(byte)Integer.parseInt(bytes[i],16);
}
log.info("Set loader configuration : ["+HexDump.toHex(data)+"]");
if (!_bundle.simulate()) {
cmd.send(S1Command.CMD25,data,false);
}
}
public void setFlashTimestamp() throws IOException,X10FlashException {
String result = ZonedDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
TAUnit tau = new TAUnit(0x00002725, BytesUtil.concatAll(result.getBytes(), new byte[] {0x00}));
sendTAUnit(tau);
}
public void setFlashState(boolean ongoing) throws IOException,X10FlashException
{
if (ongoing) {
openTA(2);
TAUnit ent = new TAUnit(0x00002774, new byte[] {0x01});
sendTAUnit(ent);
closeTA();
}
else {
openTA(2);
String result = ZonedDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
TAUnit tau = new TAUnit(0x00002725, BytesUtil.concatAll(result.getBytes(), new byte[] {0x00}));
sendTAUnit(tau);
TAUnit ent = new TAUnit(0x00002774, new byte[] {0x00});
sendTAUnit(ent);
closeTA();
}
}
public void setFlashStat(byte state) throws IOException,X10FlashException {
TAUnit ent = new TAUnit(0x00002774, new byte[] {state});
sendTAUnit(ent);
}
private void sendTA(TAFileParser ta) throws FileNotFoundException, IOException,X10FlashException {
log.info("Flashing "+ta.getName()+" to partition "+ta.getPartition());
Vector<TAUnit> entries = ta.entries();
for (int i=0;i<entries.size();i++) {
sendTAUnit(entries.get(i));
}
}
public void sendTAUnit(TAUnit ta) throws X10FlashException, IOException {
if (ta.getUnitHex().equals("000007DA")) {
String result = WidgetTask.openYESNOBox(_curshell, "This unit ("+ta.getUnitHex() + ") is very sensitive and can brick the device. Do you really want to flash it ?");
if (Integer.parseInt(result)==SWT.NO) {
log.warn("HWConfig unit skipped : "+ta.getUnitHex());
return;
}
}
log.info("Writing TA unit "+ta.getUnitHex()+". Value : "+HexDump.toHex(ta.getUnitData()));
if (!_bundle.simulate()) {
cmd.send(S1Command.CMD13, ta.getFlashBytes(),false);
}
}
public TAUnit readTA(int unit) throws IOException, X10FlashException
{
String sunit = HexDump.toHex(BytesUtil.getBytesWord(unit, 4));
log.info("Start Reading unit "+sunit);
log.debug((new StringBuilder("%%% read TA property id=")).append(unit).toString());
cmd.send(S1Command.CMD12, BytesUtil.getBytesWord(unit, 4),false);
log.info("Reading TA finished.");
if (cmd.getLastReply().getDataLength()>0) {
TAUnit ta = new TAUnit(unit, cmd.getLastReply().getDataArray());
return ta;
}
return null;
}
public void backupTA() {
log.info("Making a TA backup");
String timeStamp = OS.getTimeStamp();
try {
BackupTA(1, timeStamp);
} catch (Exception e) {
}
try {
BackupTA(2, timeStamp);
} catch (Exception e) {
e.printStackTrace();
}
}
public void BackupTA(int partition, String timeStamp) throws IOException, X10FlashException {
openTA(partition);
String folder = OS.getFolderRegisteredDevices()+File.separator+getPhoneProperty("MSN")+File.separator+"s1ta"+File.separator+timeStamp;
new File(folder).mkdirs();
TextFile tazone = new TextFile(folder+File.separator+partition+".ta","ISO8859-1");
tazone.open(false);
try {
tazone.writeln(HexDump.toHex((byte)partition));
try {
log.info("Start Dumping TA partition "+partition);
cmd.send(S1Command.CMD18, S1Command.VALNULL, false);
if (cmd.getLastReply().getDataLength()>0) {
log.info("Finished Dumping TA partition "+partition);
ByteArrayInputStream inputStream = new ByteArrayInputStream(cmd.getLastReply().getDataArray());
TreeMap<Integer, byte[]> treeMap = new TreeMap<Integer, byte[]>();
int i = 0;
while(i == 0) {
int j = inputStream.read();
if (j == -1) {
i = 1;
}
else {
byte[] buff = new byte[3];
if(Streams.readFully(inputStream, buff)!=3){
throw new X10FlashException("Not enough data to read Uint32 when decoding command");
}
byte[] unitbuff = Bytes.concat(new byte[] { (byte)j }, buff);
long unit = ByteBuffer.wrap(unitbuff).getInt() & 0xFFFFFFFF;
long unitdatalen = decodeUint32(inputStream);
if (unitdatalen > 1000000L) {
throw new X10FlashException("Maximum unit size exceeded, application will handle units of a maximum size of 0x"
+ Long.toHexString(1000000L) + ". Got a unit of size 0x" + Long.toHexString(unitdatalen) + ".");
}
byte[] databuff = new byte[(int)unitdatalen];
if (Streams.readFully(inputStream, databuff) != unitdatalen) {
throw new X10FlashException("Not enough data to read unit data decoding command");
}
treeMap.put((int)unit, databuff);
}
}
for (Map.Entry<Integer, byte[]> entry : treeMap.entrySet())
{
TAUnit tau = new TAUnit(entry.getKey(), entry.getValue());
if (tau.getUnitNumber()>0)
tazone.write(tau.toString());
if (treeMap.lastEntry().getKey()!=entry.getKey()) tazone.write("\n");
}
tazone.close();
log.info("TA partition "+partition+" saved to "+folder+File.separator+partition+".ta");
} else {
log.warn("This partition is not readable");
}
closeTA();
} catch (X10FlashException e) {
closeTA();
throw e;
}
}
catch (Exception ioe) {
tazone.close();
closeTA();
log.error(ioe.getMessage());
log.error("Error dumping TA. Aborted");
}
}
private long decodeUint32(InputStream inputStream) throws IOException, X10FlashException {
byte[] buff = new byte[4];
if (Streams.readFully(inputStream, buff) != 4)
{
throw new X10FlashException("Not enough data to read Uint32 when decoding command");
}
long longval = ByteBuffer.wrap(buff).getInt();
return longval & 0xFFFFFFFF;
}
private void processHeader(SinFile sin) throws X10FlashException {
try {
log.info(" Checking header");
if (!_bundle.simulate()) {
cmd.send(S1Command.CMD05, sin.getHeader(), false);
}
}
catch (IOException ioe) {
throw new X10FlashException("Error in processHeader : "+ioe.getMessage());
}
}
private void uploadImage(SinFile sin) throws X10FlashException {
try {
log.info("Processing "+sin.getName());
processHeader(sin);
log.info(" Flashing data");
log.debug("Number of parts to send : "+sin.getNbChunks()+" / Part size : "+sin.getChunkSize());
sin.openForSending();
int nbparts=1;
while (sin.hasData()) {
log.debug("Sending part "+nbparts+" of "+sin.getNbChunks());
byte[] part = sin.getNextChunk();
if (!_bundle.simulate()) {
cmd.send(S1Command.CMD06, part, sin.hasData());
}
nbparts++;
}
sin.closeFromSending();
//log.info("Processing of "+sin.getShortFileName()+" finished.");
}
catch (Exception e) {
log.error("Processing of "+sin.getName()+" finished with errors.");
sin.closeFromSending();
e.printStackTrace();
throw new X10FlashException (e.getMessage());
}
}
private String getDefaultLoader() {
DeviceEntry ent = Devices.getDeviceFromVariant(getCurrentDevice());
String loader = "";
if (ent!=null) {
if (modded_loader)
loader=ent.getLoaderUnlocked();
else
loader=ent.getLoader();
}
if (modded_loader)
log.info("Using an unofficial loader");
if (loader.length()==0) {
String device = WidgetTask.openDeviceSelector(_curshell);
if (device.length()>0) {
ent = new DeviceEntry(device);
loader = ent.getLoader();
}
}
return loader;
}
public void sendLoader() throws FileNotFoundException, IOException, X10FlashException, SinFileException {
if (!_bundle.hasLoader() || modded_loader) {
if (modded_loader)
log.info("Searching for a modded loader");
else
log.info("No loader in the bundle. Searching for one");
String loader = getDefaultLoader();
if (new File(loader).exists()) {
_bundle.setLoader(new File(loader));
}
else log.info("No matching loader found");
}
if (_bundle.hasLoader()) {
SinFile sin = new SinFile(new File(_bundle.getLoader().getAbsolutePath()));
if (sin.getVersion()>=2)
sin.setChunkSize(0x10000);
else
sin.setChunkSize(0x1000);
uploadImage(sin);
if (!_bundle.simulate()) {
USBFlash.readS1Reply();
}
}
else log.warn("No loader found or set manually. Skipping loader");
if (!_bundle.simulate()) {
hookDevice(true);
maxS1packetsize=Integer.parseInt(phoneprops.getProperty("MAX_PKT_SZ"),16);
}
else
maxS1packetsize=0x080000;
if ((maxS1packetsize/1024)<1024)
log.info("Max packet size set to "+maxS1packetsize/1024+"K");
else
log.info("Max packet size set to "+maxS1packetsize/1024/1024+"M");
if (_bundle.getMaxBuffer()==0) {
USBFlash.setUSBBufferSize(maxS1packetsize);
if ((maxS1packetsize/1024)<1024)
log.info("USB buffer size set to "+maxS1packetsize/1024+"K");
else
log.info("USB buffer size set to "+maxS1packetsize/1024/1024+"M");
}
if (_bundle.getMaxBuffer()==1) {
USBFlash.setUSBBufferSize(2048*1024);
log.info("USB buffer size set to 2048K");
}
if (_bundle.getMaxBuffer()==2) {
USBFlash.setUSBBufferSize(1024*1024);
log.info("USB buffer size set to 1024K");
}
if (_bundle.getMaxBuffer()==3) {
USBFlash.setUSBBufferSize(512*1024);
log.info("USB buffer size set to 512K");
}
if (_bundle.getMaxBuffer()==4) {
USBFlash.setUSBBufferSize(256*1024);
log.info("USB buffer size set to 256K");
}
if (_bundle.getMaxBuffer()==5) {
USBFlash.setUSBBufferSize(128*1024);
log.info("USB buffer size set to 128K");
}
if (_bundle.getMaxBuffer()==6) {
USBFlash.setUSBBufferSize(64*1024);
log.info("USB buffer size set to 64K");
}
if (_bundle.getMaxBuffer()==7) {
USBFlash.setUSBBufferSize(32*1024);
log.info("USB buffer size set to 32K");
}
LogProgress.initProgress(_bundle.getMaxProgress(maxS1packetsize));
}
public String getPhoneProperty(String property) {
return phoneprops.getProperty(property);
}
public void openTA(int partition) throws X10FlashException, IOException{
if (!taopen) {
log.info("Opening TA partition "+partition);
if (!_bundle.simulate())
cmd.send(S1Command.CMD09, BytesUtil.getBytesWord(partition, 1), false);
}
taopen = true;
}
public void closeTA() throws X10FlashException, IOException{
if (taopen) {
log.info("Closing TA partition");
if (!_bundle.simulate())
cmd.send(S1Command.CMD10, S1Command.VALNULL, false);
}
taopen = false;
}
public XMLBootConfig getBootConfig() throws FileNotFoundException, IOException,X10FlashException, JDOMException, TAFileParseException, BootDeliveryException {
if (!_bundle.hasBootDelivery()) return null;
log.info("Parsing boot delivery");
XMLBootDelivery xml = _bundle.getXMLBootDelivery();
Vector<XMLBootConfig> found = new Vector<XMLBootConfig>();
if (!_bundle.simulate()) {
Enumeration<XMLBootConfig> e = xml.getBootConfigs();
while (e.hasMoreElements()) {
// We get matching bootconfig from all configs
XMLBootConfig bc=e.nextElement();
if (bc.matches(phoneprops.getProperty("OTP_LOCK_STATUS_1"), phoneprops.getProperty("OTP_DATA_1"), phoneprops.getProperty("IDCODE_1"), phoneprops.getProperty("PLF_ROOT_1")))
found.add(bc);
}
}
else {
Enumeration<XMLBootConfig> e = xml.getBootConfigs();
while (e.hasMoreElements()) {
// We get matching bootconfig from all configs
XMLBootConfig bc=e.nextElement();
if (bc.getName().startsWith("COMMERCIAL")) {
found.add(bc);
break;
}
}
}
if (found.size()==0)
throw new BootDeliveryException ("Found no matching config. Skipping boot delivery");
// if found more thant 1 config
boolean same = true;
if (found.size()>1) {
// Check if all found configs have the same fileset
Iterator<XMLBootConfig> masterlist = found.iterator();
while (masterlist.hasNext()) {
XMLBootConfig masterconfig = masterlist.next();
Iterator<XMLBootConfig> slavelist = found.iterator();
while (slavelist.hasNext()) {
XMLBootConfig slaveconfig = slavelist.next();
if (slaveconfig.compare(masterconfig)==2)
throw new BootDeliveryException ("Cannot decide among found configurations. Skipping boot delivery");
}
}
}
found.get(found.size()-1).setFolder(_bundle.getBootDelivery().getFolder());
return found.get(found.size()-1);
}
public void sendBootDelivery() throws FileNotFoundException, IOException,X10FlashException, JDOMException, TAFileParseException, SinFileException {
try {
if (bc!=null) {
XMLBootDelivery xmlboot = _bundle.getXMLBootDelivery();
if (!_bundle.simulate())
if (!xmlboot.mustUpdate(phoneprops.getProperty("BOOTVER"))) throw new BootDeliveryException("Boot delivery up to date. Nothing to do");
log.info("Going to flash boot delivery");
if (!bc.isComplete()) throw new BootDeliveryException ("Some files are missing from your boot delivery");
TAFileParser taf = new TAFileParser(new File(bc.getTA()));
if (bc.hasAppsBootFile()) {
openTA(2);
SinFile sin = new SinFile(new File(bc.getAppsBootFile()));
sin.setChunkSize(maxS1packetsize);
uploadImage(sin);
closeTA();
}
openTA(2);
sendTA(taf);
closeTA();
openTA(2);
Iterator<String> otherfiles = bc.getOtherFiles().iterator();
while (otherfiles.hasNext()) {
SinFile sin1 = new SinFile(new File(otherfiles.next()));
sin1.setChunkSize(maxS1packetsize);
uploadImage(sin1);
}
closeTA();
_bundle.setBootDeliveryFlashed(true);
}
} catch (BootDeliveryException e) {
log.info(e.getMessage());
}
}
public void loadTAFiles() throws FileNotFoundException, IOException,X10FlashException {
Iterator<Category> entries = _bundle.getMeta().getTAEntries(true).iterator();
while (entries.hasNext()) {
Category categ = entries.next();
Iterator<BundleEntry> icateg = categ.getEntries().iterator();
while (icateg.hasNext()) {
BundleEntry bent = icateg.next();
if (bent.getName().toUpperCase().endsWith(".TA")) {
if (!bent.getName().toUpperCase().contains("SIM"))
try {
TAFileParser ta = new TAFileParser(new File(bent.getAbsolutePath()));
Iterator<TAUnit> i = ta.entries().iterator();
while (i.hasNext()) {
TAUnit ent = i.next();
TaPartition2.put(ent.getUnitNumber(),ent);
}
}
catch (TAFileParseException tae) {
log.error("Error parsing TA file. Skipping");
}
else {
log.warn("File "+bent.getName()+" is ignored");
}
}
}
}
try {
if (bc!=null) {
TAFileParser taf = new TAFileParser(new File(bc.getTA()));
Iterator<TAUnit> i = taf.entries().iterator();
while (i.hasNext()) {
TAUnit ent = i.next();
TaPartition2.put(ent.getUnitNumber(),ent);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void getDevInfo() throws IOException, X10FlashException {
openTA(2);
cmd.send(S1Command.CMD12, S1Command.TA_MODEL, false);
currentdevice = cmd.getLastReply().getDataString();
String info = "Current device : "+getCurrentDevice();
cmd.send(S1Command.CMD12, S1Command.TA_SERIAL, false);
serial = cmd.getLastReply().getDataString();
info = info + " - "+serial;
cmd.send(S1Command.CMD12, S1Command.TA_DEVID3, false);
info = info + " - "+cmd.getLastReply().getDataString();
cmd.send(S1Command.CMD12, S1Command.TA_DEVID4, false);
info = info + " - "+cmd.getLastReply().getDataString();
cmd.send(S1Command.CMD12, S1Command.TA_DEVID5, false);
info = info + " - "+cmd.getLastReply().getDataString();
log.info(info);
closeTA();
}
public boolean checkScript() {
try {
Vector<String> ignored = new Vector<String>();
FlashScript flashscript = new FlashScript(getFlashScript());
flashscript.setBootConfig(bc);
Iterator<Category> icategs = _bundle.getMeta().getAllEntries(true).iterator();
while (icategs.hasNext()) {
Category cat = icategs.next();
if (!flashscript.hasCategory(cat)) ignored.add(cat.getId());
}
if (ignored.size()>0) {
Enumeration eignored = ignored.elements();
String dynmsg = "";
while (eignored.hasMoreElements()) {
dynmsg=dynmsg+eignored.nextElement();
if (eignored.hasMoreElements()) dynmsg = dynmsg + ",";
}
String result = WidgetTask.openYESNOBox(_curshell, "Those data are not in the FSC script and will be skipped : \n"+dynmsg+".\n Do you want to continue ?");
if (Integer.parseInt(result) == SWT.YES) {
return true;
}
return false;
}
return true;
} catch (Exception e) {
return false;
}
}
public String getFlashScript() {
try {
if (_bundle.hasFsc()) {
return _bundle.getFsc().getAbsolutePath();
}
} catch (Exception e) {
}
DeviceEntry dev = Devices.getDeviceFromVariant(getCurrentDevice());
return dev.getFlashScript(_bundle.getVersion(), getCurrentDevice());
}
public void runScript() {
try {
TextFile tf = new TextFile(getFlashScript(),"ISO8859-1");
log.info("Found a template session. Using it : "+tf.getFileName());
Map<Integer,String> map = tf.getMap();
Iterator<Integer> keys = map.keySet().iterator();
while (keys.hasNext()) {
String param="";
String line = map.get(keys.next());
String[] parsed = line.split(":");
String action = parsed[0];
if (parsed.length>1)
param = parsed[1];
if (action.equals("openTA")) {
this.openTA(Integer.parseInt(param));
}
else if (action.equals("closeTA")) {
this.closeTA();
}
else if (action.equals("setFlashState")) {
this.setFlashStat((byte)Integer.parseInt(param));
}
else if (action.equals("setLoaderConfig")) {
this.setLoaderConfiguration(param);
}
else if (action.equals("uploadImage")) {
BundleEntry b = _bundle.searchEntry(param);
if (b==null && param.toUpperCase().equals("PARTITION")) {
b = _bundle.searchEntry("partition-image");
}
if (b!=null) {
SinFile sin =new SinFile(new File(b.getAbsolutePath()));
sin.setChunkSize(maxS1packetsize);
this.uploadImage(sin);
}
else {
if (bc!=null) {
String file = bc.getMatchingFile(param);
if (file!=null) {
SinFile sin =new SinFile(new File(file));
sin.setChunkSize(maxS1packetsize);
this.uploadImage(sin);
}
else {
log.warn(param + " is excluded from bundle");
}
}
else {
log.warn(param + " is excluded from bundle");
}
}
}
else if (action.equals("writeTA")) {
TAUnit unit = TaPartition2.get(Long.parseLong(param));
if (unit != null)
this.sendTAUnit(unit);
else log.warn("Unit "+param+" not found in bundle");
}
else if (action.equals("setFlashTimestamp")) {
this.setFlashTimestamp();
}
else if (action.equals("End flashing")) {
this.endSession();
}
}
} catch (Exception e) {e.printStackTrace();}
}
public boolean hasScript() {
File fsc=null;
try {
fsc=new File(getFlashScript());
}
catch (Exception e) {
fsc=null;
}
if (fsc!=null) {
if (fsc.exists()) {
if (_bundle.hasFsc()) return true;
String result = WidgetTask.openYESNOBox(_curshell, "A FSC script is found : "+fsc.getName()+". Do you want to use it ?");
return Integer.parseInt(result)==SWT.YES;
}
else return false;
}
return false;
}
public void flash() throws X10FlashException, IOException {
try {
log.info("Start Flashing");
sendLoader();
bc = getBootConfig();
loadTAFiles();
if (hasScript()) {
if (checkScript())
runScript();
}
else {
DeviceEntry dev = Devices.getDeviceFromVariant(getCurrentDevice());
if (!dev.isFlashScriptMandatory()) {
log.info("No flash script found. Using 0.9.18 flash engine");
oldFlashEngine();
}
else {
log.info("No flash script found.");
log.info("Flash script is mandatory. Closing session");
closeDevice(0x01);
}
}
log.info("Flashing finished.");
log.info("Please unplug and start your phone");
log.info("For flashtool, Unknown Sources and Debugging must be checked in phone settings");
LogProgress.initProgress(0);
}
catch (Exception ioe) {
ioe.printStackTrace();
close();
log.error(ioe.getMessage());
log.error("Error flashing. Aborted");
LogProgress.initProgress(0);
}
}
public void sendPartition() throws FileNotFoundException, IOException, X10FlashException, SinFileException {
Iterator<Category> e = _bundle.getMeta().getAllEntries(true).iterator();
while (e.hasNext()) {
Category c = e.next();
if (c.isPartition()) {
BundleEntry entry = c.getEntries().iterator().next();
SinFile sin = new SinFile(new File(entry.getAbsolutePath()));
sin.setChunkSize(maxS1packetsize);
uploadImage(sin);
}
}
}
public void sendBoot() throws FileNotFoundException, IOException, X10FlashException, SinFileException {
openTA(2);
Iterator<Category> e = _bundle.getMeta().getAllEntries(true).iterator();
while (e.hasNext()) {
Category c = e.next();
if (c.isSoftware()) {
BundleEntry entry = c.getEntries().iterator().next();
if (isBoot(entry.getAbsolutePath())) {
SinFile sin = new SinFile(new File(entry.getAbsolutePath()));
sin.setChunkSize(maxS1packetsize);
uploadImage(sin);
}
}
}
closeTA();
}
public void sendSecro() throws X10FlashException, IOException, SinFileException {
BundleEntry preload = null;
BundleEntry secro = null;
Iterator<Category> e = _bundle.getMeta().getAllEntries(true).iterator();
while (e.hasNext()) {
Category c = e.next();
if (c.isPreload()) preload = c.getEntries().iterator().next();
if (c.isSecro()) secro = c.getEntries().iterator().next();
}
if (preload!=null && secro!=null) {
setLoaderConfiguration("00,01,00,00,00,01");
setLoaderConfiguration("00,01,00,00,00,03");
SinFile sinpreload = new SinFile(new File(preload.getAbsolutePath()));
sinpreload.setChunkSize(maxS1packetsize);
uploadImage(sinpreload);
setLoaderConfiguration("00,01,00,00,00,01");
SinFile sinsecro = new SinFile(new File(secro.getAbsolutePath()));
sinsecro.setChunkSize(maxS1packetsize);
uploadImage(sinsecro);
setLoaderConfiguration("00,01,00,00,00,00");
}
}
public boolean isBoot(String sinfile) throws SinFileException {
org.flashtool.parsers.sin.SinFile sin = new org.flashtool.parsers.sin.SinFile(new File(sinfile));
if (sin.getName().toUpperCase().contains("BOOT")) return true;
return sin.getType()=="BOOT";
}
public void sendSoftware() throws FileNotFoundException, IOException, X10FlashException, SinFileException {
openTA(2);
Iterator<Category> e = _bundle.getMeta().getAllEntries(true).iterator();
while (e.hasNext()) {
Category c = e.next();
if (c.isSoftware()) {
BundleEntry entry = c.getEntries().iterator().next();
if (isBoot(entry.getAbsolutePath())) continue;
SinFile sin = new SinFile(new File(entry.getAbsolutePath()));
sin.setChunkSize(maxS1packetsize);
uploadImage(sin);
}
}
closeTA();
}
public void sendElabel() throws FileNotFoundException, IOException, X10FlashException, SinFileException {
openTA(2);
Iterator<Category> e = _bundle.getMeta().getAllEntries(true).iterator();
while (e.hasNext()) {
Category c = e.next();
if (c.isElabel()) {
BundleEntry entry = c.getEntries().iterator().next();
if (isBoot(entry.getAbsolutePath())) continue;
SinFile sin = new SinFile(new File(entry.getAbsolutePath()));
sin.setChunkSize(maxS1packetsize);
uploadImage(sin);
}
}
closeTA();
}
public void sendSystem() throws FileNotFoundException, IOException, X10FlashException, SinFileException {
openTA(2);
Iterator<Category> e = _bundle.getMeta().getAllEntries(true).iterator();
while (e.hasNext()) {
Category c = e.next();
if (c.isSystem()) {
BundleEntry entry = c.getEntries().iterator().next();
if (isBoot(entry.getAbsolutePath())) continue;
SinFile sin = new SinFile(new File(entry.getAbsolutePath()));
sin.setChunkSize(maxS1packetsize);
uploadImage(sin);
}
}
closeTA();
}
public void sendTAFiles() throws FileNotFoundException, IOException, X10FlashException, TAFileParseException {
openTA(2);
Iterator<Category> e = _bundle.getMeta().getAllEntries(true).iterator();
while (e.hasNext()) {
Category c = e.next();
if (c.isTa()) {
BundleEntry entry = c.getEntries().iterator().next();
TAFileParser taf = new TAFileParser(new File(entry.getAbsolutePath()));
sendTA(taf);
}
}
closeTA();
}
public void oldFlashEngine() {
try {
if (_bundle.hasCmd25()) {
log.info("Disabling final data verification check");
this.disableFinalVerification();
}
setFlashState(true);
sendPartition();
sendSecro();
sendBootDelivery();
sendBoot();
sendSoftware();
sendSystem();
sendTAFiles();
sendElabel();
setFlashState(false);
closeDevice(0x01);
}
catch (Exception ioe) {
ioe.printStackTrace();
close();
log.error(ioe.getMessage());
log.error("Error flashing. Aborted");
LogProgress.initProgress(0);
}
}
public Bundle getBundle() {
return _bundle;
}
public boolean open() {
return open(_bundle.simulate());
}
public boolean flashmode() {
boolean found = false;
try {
Thread.sleep(500);
found = Devices.getLastConnected(false).getPid().equals("ADDE");
}
catch (Exception e) {
found = false;
}
return found;
}
public void endSession() throws X10FlashException,IOException {
log.info("Ending flash session");
if (!_bundle.simulate())
cmd.send(S1Command.CMD04,S1Command.VALNULL,false);
}
public void endSession(int param) throws X10FlashException,IOException {
log.info("Ending flash session");
cmd.send(S1Command.CMD04,BytesUtil.getBytesWord(param, 1),false);
}
public void close() {
try {
endSession();
}
catch (Exception e) {}
USBFlash.close();
}
public void closeDevice(int par) {
try {
endSession(par);
}
catch (Exception e) {}
USBFlash.close();
}
public void hookDevice(boolean printProps) throws X10FlashException,IOException {
if (printProps && _bundle.hasLoader()) {
cmd.send(S1Command.CMD01, S1Command.VALNULL, false);
cmd01string = cmd.getLastReply().getDataString();
log.debug(cmd01string);
phoneprops.update(cmd01string);
if (getPhoneProperty("ROOTING_STATUS")==null) phoneprops.setProperty("ROOTING_STATUS", "UNROOTABLE");
if (phoneprops.getProperty("VER").startsWith("r"))
phoneprops.setProperty("ROOTING_STATUS", "ROOTED");
}
if (printProps) {
log.debug("After loader command reply (hook) : "+cmd01string);
log.info("Loader : "+phoneprops.getProperty("LOADER_ROOT")+" - Version : "+phoneprops.getProperty("VER")+" / Boot version : "+phoneprops.getProperty("BOOTVER")+" / Bootloader status : "+phoneprops.getProperty("ROOTING_STATUS"));
}
else
log.debug("First command reply (hook) : "+cmd01string);
}
public TAUnit readTA(int partition, int unit) throws X10FlashException, IOException {
TAUnit u = null;
this.openTA(partition);
try {
u = this.readTA(unit);
}
catch (X10FlashException x10e) {
log.warn(x10e.getMessage());
u=null;
}
this.closeTA();
return u;
}
public void writeTA(int partition, TAUnit unit) throws X10FlashException, IOException {
this.openTA(partition);
this.sendTAUnit(unit);
this.closeTA();
}
public boolean open(boolean simulate) {
if (simulate) return true;
LogProgress.initProgress(_bundle.getMaxLoaderProgress());
boolean found=false;
try {
USBFlash.open("ADDE");
try {
log.info("Reading device information");
;
firstRead = new String (USBFlash.readS1Reply().getDataArray());
phoneprops = new LoaderInfo(firstRead);
phoneprops.setProperty("BOOTVER", phoneprops.getProperty("VER"));
if (phoneprops.getProperty("VER").startsWith("r"))
modded_loader=true;
log.debug(firstRead);
}
catch (Exception e) {
e.printStackTrace();
log.info("Unable to read from phone after having opened it.");
log.info("trying to continue anyway");
}
cmd = new S1Command(_bundle.simulate());
hookDevice(false);
log.info("Phone ready for flashmode operations.");
getDevInfo();
if (_bundle.getDevice()!=null) {
if (_bundle.getDevice().length()>0 && !currentdevice.equals(_bundle.getDevice())) {
log.error("The bundle does not match the connected device");
close();
found = false;
}
else found=true;
}
else
found = true;
}
catch (Exception e){
e.printStackTrace();
found=false;
}
return found;
}
public String getSerial() {
return serial;
}
public String getIMEI() {
return phoneprops.getProperty("IMEI");
}
public String getRootingStatus() {
return phoneprops.getProperty("ROOTING_STATUS");
}
} | 34,550 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
X10FlashException.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/X10FlashException.java | package org.flashtool.flashsystem;
public class X10FlashException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public X10FlashException(String msg){
super(msg);
}
public X10FlashException(String msg, Throwable t){
super(msg,t);
}
} | 302 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
Bundle.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/Bundle.java | package org.flashtool.flashsystem;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.Deflater;
import org.flashtool.gui.tools.FirmwareFileFilter;
import org.flashtool.gui.tools.XMLBootDelivery;
import org.flashtool.gui.tools.XMLPartitionDelivery;
import org.flashtool.logger.LogProgress;
import org.flashtool.parsers.sin.SinFile;
import org.flashtool.system.Devices;
import org.flashtool.system.OS;
import org.flashtool.system.XMLUpdate;
import com.turn.ttorrent.common.Torrent;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public final class Bundle {
private JarFile _firmware;
private boolean _simulate=false;
//private Properties bundleList=new Properties();
private String _version;
private String _branding;
private String _device;
private String _cda="";
private String _revision="";
private String _cmd25;
private String _resetCust;
private int maxbuffer;
public final static int JARTYPE=1;
public final static int FOLDERTYPE=2;
private BundleMetaData _meta;
private boolean bootdeliveryflashed=false;
private XMLBootDelivery xmlb;
private XMLPartitionDelivery xmlp;
public String getJarName() {
return _firmware.getName();
}
public Bundle() {
_meta = new BundleMetaData();
}
public Bundle(String path, int type) throws Exception {
feed(path,type);
}
public void setMeta(BundleMetaData meta) throws Exception {
_meta = meta;
feedFromMeta();
}
public Bundle(String path, int type, BundleMetaData meta) throws Exception {
_meta = meta;
feed(path,type);
}
private void feed(String path, int type) throws Exception {
if (type==JARTYPE) feedFromJar(path);
if (type==FOLDERTYPE) feedFromFolder(path);
}
private void feedFromJar(String path) {
try {
_firmware = new JarFile(path);
_meta = new BundleMetaData();
_meta.setNoErase(_firmware.getManifest().getMainAttributes().getValue("noerase"));
log.debug("Creating bundle from ftf file : "+_firmware.getName());
_device = _firmware.getManifest().getMainAttributes().getValue("device");
_version = _firmware.getManifest().getMainAttributes().getValue("version");
_branding = _firmware.getManifest().getMainAttributes().getValue("branding");
_cda = _firmware.getManifest().getMainAttributes().getValue("cda");
_cmd25 = _firmware.getManifest().getMainAttributes().getValue("cmd25");
Enumeration<JarEntry> e = _firmware.entries();
while (e.hasMoreElements()) {
BundleEntry entry = new BundleEntry(_firmware,e.nextElement());
if (!entry.getName().toUpperCase().startsWith("BOOT/") && !entry.getName().toUpperCase().startsWith("PARTITION/")) {
if (entry.getName().toUpperCase().endsWith("FSC") || entry.getName().toUpperCase().endsWith("SIN") || entry.getName().toUpperCase().endsWith("TA") || entry.getName().toUpperCase().endsWith("XML")) {
try {
_meta.process(entry);
}
catch (Exception e1) {e1.printStackTrace();
}
log.debug("Added this entry to the bundle list : "+entry.getName());
}
}
}
}
catch (IOException ioe) {
log.error("Cannot open the file "+path);
}
}
private void feedFromFolder(String path) throws Exception {
File[] list = (new File(path)).listFiles(new FirmwareFileFilter());
for (int i=0;i<list.length;i++) {
BundleEntry entry = new BundleEntry(list[i]);
_meta.process(entry);
log.debug("Added this entry to the bundle list : "+entry.getName());
}
}
private void feedFromMeta() throws Exception {
Iterator<Category> all = _meta.getAllEntries(true).iterator();
while (all.hasNext()) {
Category cat = all.next();
Iterator<BundleEntry> icat = cat.getEntries().iterator();
while (icat.hasNext()) {
BundleEntry f = icat.next();
_meta.process(f);
log.debug("Added this entry to the bundle list : "+f.getName());
}
}
}
public void setLoader(File loader) {
if (loader.exists()) {
BundleEntry entry = new BundleEntry(loader);
try {
if (_meta!=null)
_meta.setLoader(entry);
}
catch (Exception e) {
}
}
}
public void setFsc(File fsc) {
BundleEntry entry = new BundleEntry(fsc);
try {
if (_meta!=null)
_meta.setFsc(entry);
}
catch (Exception e) {
}
}
public void setSimulate(boolean simulate) {
_simulate = simulate;
}
public BundleEntry getEntry(String name) {
Category c = _meta.get(Category.getCategoryFromName(name));
return c.getEntries().iterator().next();
}
public BundleEntry searchEntry(String name) {
Vector<BundleEntry> v = new Vector<BundleEntry>();
Category c = _meta.get(Category.getCategoryFromName(name));
if (c!=null && c.isEnabled()) return c.getEntries().iterator().next();
return null;
}
public Enumeration <BundleEntry> allEntries() {
Iterator<Category> icateg = _meta.getAllEntries(false).iterator();
Vector<BundleEntry> v = new Vector<BundleEntry>();
while (icateg.hasNext()) {
Category c = icateg.next();
Iterator<BundleEntry> ibentry = c.getEntries().iterator();
while (ibentry.hasNext()) {
v.add(ibentry.next());
}
}
return v.elements();
}
public boolean isBootDeliveryFlashed() {
return bootdeliveryflashed;
}
public void setBootDeliveryFlashed(boolean flashed) {
bootdeliveryflashed=flashed;
}
public boolean hasLoader() {
return _meta.getLoader()!=null;
}
public boolean hasFsc() {
return _meta.getFsc()!=null;
}
public void setNoErase(String file) {
try {
XMLUpdate upd = new XMLUpdate(new File(file));
_meta.setNoErase(upd.getNoErase());
} catch (Exception e) {
}
}
public BundleEntry getLoader() throws IOException, FileNotFoundException {
if (hasLoader())
return _meta.getLoader().getEntries().iterator().next();
return null;
}
public BundleEntry getFsc() throws IOException, FileNotFoundException {
return _meta.getFsc().getEntries().iterator().next();
}
public boolean hasBootDelivery() {
Category bl = _meta.get("BOOT_DELIVERY");
if (bl==null) return false;
if (bl.isEnabled()) return true;
return false;
}
public boolean hasPartitionDelivery() {
Category bl = _meta.get("PARTITION_DELIVERY");
if (bl==null) return false;
if (bl.isEnabled()) return true;
return false;
}
public BundleEntry getBootDelivery() throws IOException, FileNotFoundException {
if (hasBootDelivery())
return _meta.get("BOOT_DELIVERY").getEntries().iterator().next();
return null;
}
public BundleEntry getPartitionDelivery() throws IOException, FileNotFoundException {
if (hasPartitionDelivery())
return _meta.get("PARTITION_DELIVERY").getEntries().iterator().next();
return null;
}
public boolean simulate() {
return _simulate;
}
public void setVersion(String version) {
_version=version;
}
public void setBranding(String branding) {
_branding=branding;
}
public void setDevice(String device) {
_device=device;
}
public void setCDA(String cda) {
_cda = cda;
}
public void setRevision(String revision) {
_revision = revision;
}
public void setCmd25(String value) {
_cmd25 = value;
if (_cmd25==null) _cmd25="false";
}
public boolean hasCmd25() {
try {
return _cmd25.equals("true");
}
catch (Exception e) {
return false;
}
}
public void setResetStats(String value) {
_resetCust = value;
if (_resetCust==null) _resetCust="false";
}
public boolean hasResetStats() {
try {
return _resetCust.equals("true");
}
catch (Exception e) {
return false;
}
}
public void createFTF() throws Exception {
File ftf = new File(OS.getFolderFirmwares()+File.separator+_device+"_"+_version+"_"+(_cda.length()>0?_cda:_branding)+(_revision.length()>0?("_"+_revision):"")+".ftf");
if (ftf.exists()) throw new Exception("Bundle already exists");
byte buffer[] = new byte[10240];
StringBuffer sbuf = new StringBuffer();
sbuf.append("Manifest-Version: 1.0\n");
sbuf.append("Created-By: FlashTool\n");
sbuf.append("version: "+_version+"\n");
sbuf.append("branding: "+_branding+"\n");
sbuf.append("cda: "+_cda+"\n");
sbuf.append("revision: "+_revision+"\n");
sbuf.append("device: "+_device+"\n");
sbuf.append("cmd25: "+_cmd25+"\n");
sbuf.append("noerase: "+this.getMeta().getNoEraseAsString()+"\n");
Manifest manifest = new Manifest(new ByteArrayInputStream(sbuf.toString().getBytes("UTF-8")));
FileOutputStream stream = new FileOutputStream(ftf);
JarOutputStream out = new JarOutputStream(stream, manifest);
out.setLevel(Deflater.BEST_SPEED);
long size = 0L;
Enumeration<BundleEntry> esize = allEntries();
while (esize.hasMoreElements()) {
size += esize.nextElement().getSize();
}
LogProgress.initProgress(size/10240+(size%10240>0?1:0));
if (hasLoader()) {
BundleEntry ldr = getLoader();
log.info("Adding "+ldr.getName()+" to the bundle as "+ldr.getInternal());
JarEntry jarAddLdr = new JarEntry(ldr.getInternal());
out.putNextEntry(jarAddLdr);
InputStream inLdr = ldr.getInputStream();
while (true) {
int nRead = inLdr.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
}
inLdr.close();
}
if (hasFsc()) {
BundleEntry fsc = getFsc();
if (fsc!=null) {
log.info("Adding "+fsc.getName()+" to the bundle as "+fsc.getInternal());
JarEntry jarAddFsc = new JarEntry(fsc.getInternal());
out.putNextEntry(jarAddFsc);
InputStream inFsc = fsc.getInputStream();
while (true) {
int nRead = inFsc.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
}
inFsc.close();
}
}
Enumeration<BundleEntry> e = allEntries();
while (e.hasMoreElements()) {
BundleEntry entry = e.nextElement();
log.info("Adding "+entry.getName()+" to the bundle as "+entry.getInternal());
JarEntry jarAdd = new JarEntry(entry.getInternal());
out.putNextEntry(jarAdd);
InputStream in = entry.getInputStream();
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
LogProgress.updateProgress();
}
in.close();
if (new File(entry.getAbsolutePath()).getParentFile().getName().toUpperCase().equals("BOOT")) {
String folder = new File(entry.getAbsolutePath()).getParentFile().getAbsolutePath();
XMLBootDelivery xml = new XMLBootDelivery(new File(entry.getAbsolutePath()));
Enumeration files = xml.getFiles();
while (files.hasMoreElements()) {
String bootname = (String)files.nextElement();
log.info("Adding "+bootname+" to the bundle");
jarAdd = new JarEntry("boot/"+bootname);
out.putNextEntry(jarAdd);
InputStream bin = new FileInputStream(new File(folder+File.separator+bootname));
while (true) {
int nRead = bin.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
LogProgress.updateProgress();
}
bin.close();
}
}
if (new File(entry.getAbsolutePath()).getParentFile().getName().toUpperCase().equals("PARTITION")) {
String folder = new File(entry.getAbsolutePath()).getParentFile().getAbsolutePath();
XMLPartitionDelivery xml = new XMLPartitionDelivery(new File(entry.getAbsolutePath()));
Enumeration files = xml.getFiles();
while (files.hasMoreElements()) {
String partitionname = (String)files.nextElement();
log.info("Adding "+partitionname+" to the bundle");
jarAdd = new JarEntry("partition/"+partitionname);
out.putNextEntry(jarAdd);
InputStream bin = new FileInputStream(new File(folder+File.separator+partitionname));
while (true) {
int nRead = bin.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
LogProgress.updateProgress();
}
bin.close();
}
}
}
out.close();
stream.close();
log.info("Creating torrent file : "+ftf.getAbsolutePath()+".torrent");
List<URI> l1 = new ArrayList<URI>();
List<URI> l2 = new ArrayList<URI>();
List<URI> l3 = new ArrayList<URI>();
l1.add(new URI("udp://tracker.openbittorrent.com:80/announce"));
l2.add(new URI("udp://tracker.publicbt.com:80/announce"));
l3.add(new URI("udp://tracker.ccc.de:80/announce"));
List<List<URI>> parent = new ArrayList<List<URI>>();
parent.add(l1);
parent.add(l2);
parent.add(l3);
Torrent torrent = Torrent.create(ftf, null, new URI("udp://tracker.openbittorrent.com:80/announce"), "FlashTool");
FileOutputStream fout =new FileOutputStream(new File(ftf.getAbsolutePath()+".torrent"));
torrent.save(fout);
fout.flush();
fout.close();
log.info("Torrent file creation finished");
LogProgress.initProgress(0);
}
public long getMaxLoaderProgress() {
int maxdatasize=0;
int maxloadersize=0;
try {
if (hasLoader()) {
SinFile loader = new SinFile(new File(getLoader().getAbsolutePath()));
if (loader.getVersion()>=2) {
maxloadersize=0x10000;
}
else {
maxloadersize=0x1000;
}
} else maxloadersize=0x1000;
}
catch (Exception e) {
maxloadersize=0x1000;
}
Iterator<Category> e = getMeta().getAllEntries(true).iterator();
long totalsize = 8;
while (e.hasNext()) {
Category cat = e.next();
Iterator<BundleEntry> icat = cat.getEntries().iterator();
while (icat.hasNext()) {
BundleEntry entry = getEntry(icat.next().getName());
try {
if (!entry.getName().toUpperCase().endsWith(".TA")) {
long filecount = 0;
SinFile s = null;
if (entry.getName().contains("loader")) {
s = new SinFile(new File(entry.getAbsolutePath()));
s.setChunkSize(maxloadersize);
filecount++;
}
filecount = filecount + s.getNbChunks()+1;
totalsize += filecount;
}
} catch (Exception ex) {}
}
}
return totalsize;
}
public long getMaxProgress(int chunksize) {
Iterator<Category> e = getMeta().getAllEntries(true).iterator();
long totalsize = 15;
while (e.hasNext()) {
Category cat = e.next();
Iterator<BundleEntry> icat = cat.getEntries().iterator();
while (icat.hasNext()) {
BundleEntry entry = icat.next();
try {
if (!entry.getName().toUpperCase().endsWith(".TA")) {
if (!entry.getName().toUpperCase().contains("LOADER")) {
if (entry.getName().toUpperCase().endsWith("SIN")) {
long filecount = 0;
SinFile s = new SinFile(new File(entry.getAbsolutePath()));
s.setChunkSize(chunksize);
filecount = filecount + s.getNbChunks()+1;
totalsize += filecount;
}
}
}
} catch (Exception ex) {}
}
}
if (hasCmd25()) totalsize = totalsize + 1;
return totalsize;
}
public boolean open() {
try {
log.info("Preparing files for flashing");
OS.deleteDirectory(new File(OS.getFolderFirmwaresPrepared()));
File f = new File(OS.getFolderFirmwaresPrepared());
f.mkdir();
log.debug("Created the "+f.getName()+" folder");
LogProgress.initProgress(_meta.getAllEntries(true).size());
Iterator<Category> entries = _meta.getAllEntries(true).iterator();
while (entries.hasNext()) {
LogProgress.updateProgress();
Category categ = entries.next();
Iterator<BundleEntry> icateg = categ.getEntries().iterator();
while (icateg.hasNext()) {
BundleEntry bf = icateg.next();
bf.saveTo(OS.getFolderFirmwaresPrepared());
if (bf.getCategory().equals("BOOT_DELIVERY")) {
xmlb = new XMLBootDelivery(new File(bf.getAbsolutePath()));
Enumeration files = xmlb.getFiles();
while (files.hasMoreElements()) {
String file = (String)files.nextElement();
try {
JarEntry j = _firmware.getJarEntry("boot/"+file);
BundleEntry bent = new BundleEntry(_firmware,j);
bent.saveTo(OS.getFolderFirmwaresPrepared());
} catch (NullPointerException npe) {
JarEntry j = _firmware.getJarEntry("boot/"+file+"b");
BundleEntry bent = new BundleEntry(_firmware,j);
bent.saveTo(OS.getFolderFirmwaresPrepared());
}
}
}
if (bf.getCategory().equals("PARTITION_DELIVERY")) {
xmlp = new XMLPartitionDelivery(new File(bf.getAbsolutePath()));
Enumeration files = xmlp.getFiles();
while (files.hasMoreElements()) {
String file = (String)files.nextElement();
JarEntry j = _firmware.getJarEntry("partition/"+file);
BundleEntry bent = new BundleEntry(_firmware,j);
bent.saveTo(OS.getFolderFirmwaresPrepared());
}
}
}
}
if (hasLoader())
getLoader().saveTo(OS.getFolderFirmwaresPrepared());
if (hasFsc()) {
getFsc().saveTo(OS.getFolderFirmwaresPrepared());
}
LogProgress.initProgress(0);
return true;
}
catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
LogProgress.initProgress(0);
return false;
}
}
public void close() {
if (_firmware !=null) {
File f=null;
Enumeration<JarEntry> e=_firmware.entries();
while (e.hasMoreElements()) {
JarEntry entry = e.nextElement();
String outname = OS.getFolderFirmwaresPrepared()+File.separator+entry.getName();
if (entry.getName().toUpperCase().endsWith(".SINB") || entry.getName().toUpperCase().endsWith(".TAB")) {
outname = outname.replace(".sinb", ".sin").replace(".tab", ".ta");
}
f = new File(outname);
if (f.exists())
f.delete();
}
f = new File(OS.getFolderFirmwaresPrepared()+File.separator+"boot");
if (f.exists())
f.delete();
f = new File(OS.getFolderFirmwaresPrepared());
if (f.exists())
f.delete();
try {
_firmware.close();
}
catch (IOException ioe) {ioe.printStackTrace();}
}
}
public BundleMetaData getMeta() {
return _meta;
}
public String getDevice() {
return _device;
}
public String getVersion() {
return _version;
}
public String toString() {
return "Bundle for " + Devices.getVariantName(_device) + ". FW release : " + _version + ". Customization : " + _branding;
}
public XMLBootDelivery getXMLBootDelivery() {
return xmlb;
}
public XMLPartitionDelivery getXMLPartitionDelivery() {
return xmlp;
}
public void setMaxBuffer(int value) {
maxbuffer=value;
}
public int getMaxBuffer() {
return maxbuffer;
}
} | 19,317 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
BundleException.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/BundleException.java | package org.flashtool.flashsystem;
public class BundleException extends Exception{
/**
*
*/
private static final long serialVersionUID = 1L;
public BundleException(String msg){
super(msg);
}
public BundleException(String msg, Throwable t){
super(msg,t);
}
}
| 297 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
LoaderInfo.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/LoaderInfo.java | package org.flashtool.flashsystem;
import java.util.Properties;
public class LoaderInfo extends Properties {
/**
*
*/
private static final long serialVersionUID = 1L;
public LoaderInfo(String phoneloader) {
update(phoneloader);
}
public void update(String ident) {
String[] result = ident.split(";");
for (int i=0;i<result.length;i++) {
try {
String key = result[i].split("=")[0];
String value = result[i].split("=")[1].replaceAll("\"", "");
if (key.equals("S1_ROOT")) {
if (value.split(",").length>1)
setProperty("LOADER_ROOT",value.split(",")[0]);
else
setProperty("LOADER_ROOT",value);
}
else
setProperty(key, value);
}
catch (Exception e) {}
}
}
} | 735 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
BundleMetaData.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/BundleMetaData.java | package org.flashtool.flashsystem;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
import org.flashtool.parsers.sin.SinFile;
import org.flashtool.util.MyTreeSet;
public class BundleMetaData {
MyTreeSet<Category> _categwipe = new MyTreeSet<Category>();
MyTreeSet<Category> _categex = new MyTreeSet<Category>();
Category loader=null;
Category fsc=null;
Vector<String> noerase = new Vector<String>();
public BundleMetaData() {
}
public String getNoEraseAsString() {
return noerase.toString().replace("[", "").replace("]", "").replace(" ", "");
}
public void setNoErase(String noerase) {
if (noerase!=null) {
if (noerase.toUpperCase().equals(noerase)) {
String tovect[] = noerase.split(",");
for (int i=0;i<tovect.length;i++)
this.noerase.addElement(tovect[i]);
}
else {
String noerasecateg="";
String lnoerase[]=noerase.split(",");
for (int i=0;i<lnoerase.length;i++) {
this.noerase.addElement(SinFile.getShortName(lnoerase[i]).toUpperCase());
}
}
}
if (this.noerase.size()==0) {
this.noerase.addElement("APPS_LOG");
this.noerase.addElement("USERDATA");
this.noerase.addElement("SSD");
this.noerase.addElement("DIAG");
this.noerase.addElement("B2B");
}
this.noerase.addElement("SIMLOCK");
}
public Category getLoader() {
return loader;
}
public Category getFsc() {
return fsc;
}
public Set<Category> getWipe() {
return _categwipe;
}
public Set<Category> getExclude() {
return _categex;
}
public Set<Category> getAllEntries(boolean checked) {
MyTreeSet<Category> _categ = new MyTreeSet<Category>();
Iterator<Category> i = getExclude().iterator();
while (i.hasNext()) {
Category c = i.next();
if (checked) {
if (c.isEnabled()) _categ.add(c);
}
else _categ.add(c);
}
i = getWipe().iterator();
while (i.hasNext()) {
Category c = i.next();
if (checked) {
if (c.isEnabled()) _categ.add(c);
}
else _categ.add(c);
}
return _categ;
}
public Set<Category> getTAEntries(boolean checked) {
MyTreeSet<Category> _categ = new MyTreeSet<Category>();
Iterator<Category> i = getExclude().iterator();
while (i.hasNext()) {
Category c = i.next();
if (checked) {
if (c.isEnabled()) _categ.add(c);
}
else _categ.add(c);
}
i = getWipe().iterator();
while (i.hasNext()) {
Category c = i.next();
if (checked) {
if (c.isEnabled()) _categ.add(c);
}
else _categ.add(c);
}
return _categ;
}
public void setLoader(BundleEntry f) throws Exception {
Category cat = new Category();
cat.setId(f.getCategory());
cat.addEntry(f);
loader=cat;
}
public void setFsc(BundleEntry f) throws Exception {
Category cat = new Category();
cat.setId(f.getCategory());
cat.addEntry(f);
fsc=cat;
}
public void process(BundleEntry f) throws Exception {
if (f.getName().equals("fwinfo.xml")) return;
Category cat = new Category();
cat.setId(f.getCategory());
cat.addEntry(f);
if (cat.getId().equals("LOADER")) {
loader=cat;
return;
}
if (cat.getId().equals("FSC")) {
fsc=cat;
return;
}
if (noerase.contains(cat.getId())){
cat.setEnabled(false);
_categwipe.add(cat);
}
else {
cat.setEnabled(true);
_categex.add(cat);
}
}
public void setCategEnabled(String categ, boolean enabled) {
Category c = _categex.get(categ);
if (c==null) c = _categwipe.get(categ);
if (c!=null) c.setEnabled(enabled);
}
public void remove(BundleEntry f) {
if (f.getCategory().equals("LOADER")) {
loader=null;
return;
}
if (f.getCategory().equals("FSC")) {
fsc=null;
return;
}
try {
_categex.remove(get(f.getCategory()));
} catch (Exception e) {}
try {
_categwipe.remove(get(f.getCategory()));
} catch (Exception e) {}
}
public Category get(String categ) {
Category c = _categex.get(categ);
if (c==null) c = _categwipe.get(categ);
return c;
}
public void clear() {
_categex.clear();
_categwipe.clear();
}
} | 4,006 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
CommandFlasher.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/CommandFlasher.java | package org.flashtool.flashsystem;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.flashtool.flashsystem.io.USBFlash;
import org.flashtool.gui.tools.WidgetTask;
import org.flashtool.gui.tools.XMLBootConfig;
import org.flashtool.gui.tools.XMLBootDelivery;
import org.flashtool.gui.tools.XMLPartitionDelivery;
import org.flashtool.logger.LogProgress;
import org.flashtool.parsers.sin.SinFile;
import org.flashtool.parsers.sin.SinFileException;
import org.flashtool.parsers.ta.TAFileParseException;
import org.flashtool.parsers.ta.TAFileParser;
import org.flashtool.parsers.ta.TAUnit;
import org.flashtool.system.DeviceEntry;
import org.flashtool.system.Devices;
import org.flashtool.system.OS;
import org.flashtool.system.TextFile;
import org.flashtool.util.BytesUtil;
import org.flashtool.util.CircularByteBuffer;
import org.flashtool.util.HexDump;
import org.rauschig.jarchivelib.IOUtils;
import com.igormaznitsa.jbbp.JBBPParser;
import com.igormaznitsa.jbbp.io.JBBPBitInputStream;
import com.igormaznitsa.jbbp.io.JBBPByteOrder;
import com.igormaznitsa.jbbp.mapper.Bin;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CommandFlasher implements Flasher {
String version = "v2";
public class Lun {
@Bin public byte lunlength;
@Bin public byte reserved1;
@Bin public byte lunid;
@Bin public byte[] reserved2;
@Bin public int length;
@Bin public byte [] lundata;
}
public class UfsInfos {
@Bin public byte headerlen;
@Bin public byte[] ufs_header;
@Bin public Lun [] luns;
long sectorSize=0;
public void setSectorSize(long sectorsize) {
sectorSize=sectorsize;
}
public long getLunSize(int lun) {
return (long)luns[lun].length*sectorSize/1024L;
}
public Object newInstance(Class<?> klazz){
return klazz == Lun.class ? new Lun() : null;
}
}
public class EmmcInfos {
@Bin public byte[] not_used;
@Bin public byte[] crc;
@Bin public byte[] ecc;
@Bin public byte[] file_format;
@Bin public byte[] tmp_write_protect;
@Bin public byte[] perm_write_protect;
@Bin public byte[] copy;
@Bin public byte[] file_format_group;
@Bin public byte[] content_prop_app;
@Bin public byte[] reserved1;
@Bin public byte[] write_bl_partial;
@Bin public byte[] write_bl_length;
@Bin public byte[] r2w_factor;
@Bin public byte[] default_ecc;
@Bin public byte[] wp_grp_enable;
@Bin public byte[] wp_grp_size;
@Bin public byte[] erase_grp_mult;
@Bin public byte[] erase_grp_size;
@Bin public byte[] c_size_mult;
@Bin public byte[] wdd_w_curr_max;
@Bin public byte[] wdd_w_curr_min;
@Bin public byte[] wdd_r_curr_max;
@Bin public byte[] wdd_r_curr_min;
@Bin public byte[] c_size;
@Bin public byte[] reserved2;
@Bin public byte[] dsr_imp;
@Bin public byte[] read_blk_misalign;
@Bin public byte[] write_blk_misalign;
@Bin public byte[] read_blk_partial;
@Bin public byte[] read_bl_length;
@Bin public byte[] ccc;
@Bin public byte[] tran_speed;
@Bin public byte[] nsac;
@Bin public byte[] taac;
@Bin public byte[] reserved3;
@Bin public byte[] spec_vers;
@Bin public byte[] csd_structure;
@Bin public byte[] reserved4;
@Bin public byte[] sec_bad_blk_mgmnt;
@Bin public byte[] reserved5;
@Bin public byte[] enh_start_addr;
@Bin public byte[] enh_size_mult;
@Bin public byte[] gp_size_mult;
@Bin public byte[] PARTITION_SETTING_COMPLETED;
@Bin public byte[] PARTITIONS_ATTRIBUTE;
@Bin public byte[] MAX_ENH_SIZE_MULT;
@Bin public byte[] PARTITIONING_SUPPORT;
@Bin public byte[] HPI_MGMT;
@Bin public byte[] RST_n_FUNCTION;
@Bin public byte[] BKOPS_EN;
@Bin public byte[] BKOPS_START;
@Bin public byte[] RESERVED6;
@Bin public byte[] WR_REL_PARAM;
@Bin public byte[] WR_REL_SET;
@Bin public byte[] RPMB_SIZE_MULT;
@Bin public byte[] FW_CONFIG;
@Bin public byte[] RESERVED7;
@Bin public byte[] USER_WP;
@Bin public byte[] RESERVED8;
@Bin public byte[] BOOT_WP;
@Bin public byte[] ERASE_GROUP_DEF;
@Bin public byte[] RESERVED9;
@Bin public byte[] BOOT_BUS_WIDTH;
@Bin public byte[] BOOT_CONFIG_PROT;
@Bin public byte[] PARTITION_CONFIG;
@Bin public byte[] RESERVED10;
@Bin public byte[] ERASED_MEM_CONT;
@Bin public byte[] RESERVED11;
@Bin public byte[] BUS_WIDTH;
@Bin public byte[] RESERVED12;
@Bin public byte[] HS_TIMING;
@Bin public byte[] RESERVED13;
@Bin public byte[] POWER_CLASS;
@Bin public byte[] RESERVED14;
@Bin public byte[] CMD_SET_REV;
@Bin public byte[] RESERVED15;
@Bin public byte[] CMD_SET;
@Bin public byte[] RESERVED16;
@Bin public byte[] EXT_CSD_REV;
@Bin public byte[] RESERVED17;
@Bin public byte[] CSD_STRUCTURE1;
@Bin public byte[] RESERVED18;
@Bin public byte[] CARD_TYPE;
@Bin public byte[] RESERVED19;
@Bin public byte[] OUT_OF_INTERRUPT_TIME;
@Bin public byte[] PARTITION_SWITCH_TIME;
@Bin public byte[] PWR_CL_52_195;
@Bin public byte[] PWR_CL_26_195;
@Bin public byte[] PWR_CL_52_360;
@Bin public byte[] PWR_CL_26_360;
@Bin public byte[] RESERVED20;
@Bin public byte[] MIN_PERF_R_4_26;
@Bin public byte[] MIN_PERF_W_4_26;
@Bin public byte[] MIN_PERF_R_8_26_4_52;
@Bin public byte[] MIN_PERF_W_8_26_4_52;
@Bin public byte[] MIN_PERF_R_8_52;
@Bin public byte[] MIN_PERF_W_8_52;
@Bin public byte[] RESERVED21;
@Bin public int SEC_COUNT;
@Bin public byte[] RESERVED22;
@Bin public byte[] S_A_TIMEOUT;
@Bin public byte[] RESERVED23;
@Bin public byte[] S_C_VCCQ;
@Bin public byte[] S_C_VCC;
@Bin public byte[] HC_WP_GRP_SIZE;
@Bin public byte[] REL_WR_SEC_C;
@Bin public byte[] ERASE_TIMEOUT_MULT;
@Bin public byte[] HC_ERASE_GRP_SIZE;
@Bin public byte[] ACC_SIZE;
@Bin public byte[] BOOT_SIZE_MULT;
@Bin public byte[] RESERVED24;
@Bin public byte[] BOOT_INFO;
@Bin public byte[] SEC_TRIM_MULT;
@Bin public byte[] SEC_ERASE_MULT;
@Bin public byte[] SEC_FEATURE_SUPPORT;
@Bin public byte[] TRIM_MULT;
@Bin public byte[] RESERVED25;
@Bin public byte[] MIN_PERF_DDR_R_8_52;
@Bin public byte[] MIN_PERF_DDR_W_8_52;
@Bin public byte[] RESERVED26;
@Bin public byte[] PWR_CL_DDR_52_195;
@Bin public byte[] PWR_CL_DDR_52_360;
@Bin public byte[] RESERVED27;
@Bin public byte[] INI_TIMEOUT_AP;
@Bin public byte[] CORRECTLY_PRG_SECTORS_NUM;
@Bin public byte[] BKOPS_STATUS;
@Bin public byte[] RESERVED28;
@Bin public byte[] BKOPS_SUPPORT;
@Bin public byte[] HPI_FEATURES;
@Bin public byte[] S_CMD_SET;
@Bin public byte[] RESERVED29;
long sectorSize=0;
public void setSectorSize(long sectorsize) {
sectorSize=sectorsize;
}
public long getDiskSize() {
return (long)SEC_COUNT*sectorSize/1024L;
}
public Object newInstance(Class<?> klazz){
return klazz == Lun.class ? new Lun() : null;
}
}
private Bundle _bundle;
private String currentdevice = "";
private String serial = "";
private Shell _curshell;
private HashMap<Long,TAUnit> TaPartition2 = new HashMap<Long,TAUnit>();
private XMLBootConfig bc=null;
private XMLPartitionDelivery pd=null;
private Properties phoneprops = null;
private UfsInfos ufs_infos = null;
private EmmcInfos emmc_infos = null;
public CommandFlasher(Bundle bundle, Shell shell) {
_bundle=bundle;
_curshell = shell;
}
public boolean flashmode() {
boolean found = false;
try {
Thread.sleep(500);
found = Devices.getLastConnected(false).getPid().equals("B00B");
}
catch (Exception e) {
found = false;
}
return found;
}
public void loadProperties() {
log.info("Reading phone properties");
phoneprops = new Properties();
try {
getVar("product");
phoneprops.setProperty("swrelease", new String(readTA(2, 2202).getUnitData()));
phoneprops.setProperty("customization", new String(readTA(2, 2205).getUnitData()));
phoneprops.setProperty("model",new String(readTA(2, 2210).getUnitData()));
phoneprops.setProperty("serial", new String(readTA(2, 4900).getUnitData()));
phoneprops.setProperty("lastflashdate",new String(readTA(2, 10021).getUnitData()));
getRootKeyHash();
} catch (Exception e) {
}
}
public boolean open(boolean simulate) {
USBFlash.setUSBBufferSize(512*1024);
if (_bundle.getMaxBuffer()==0) {
USBFlash.setUSBBufferSize(4096*1024);
log.info("USB buffer size set to 4096K");
}
if (_bundle.getMaxBuffer()==1) {
USBFlash.setUSBBufferSize(2048*1024);
log.info("USB buffer size set to 2048K");
}
if (_bundle.getMaxBuffer()==2) {
USBFlash.setUSBBufferSize(1024*1024);
log.info("USB buffer size set to 1024K");
}
if (_bundle.getMaxBuffer()==3) {
USBFlash.setUSBBufferSize(512*1024);
log.info("USB buffer size set to 512K");
}
if (_bundle.getMaxBuffer()==4) {
USBFlash.setUSBBufferSize(256*1024);
log.info("USB buffer size set to 256K");
}
if (_bundle.getMaxBuffer()==5) {
USBFlash.setUSBBufferSize(128*1024);
log.info("USB buffer size set to 128K");
}
if (_bundle.getMaxBuffer()==6) {
USBFlash.setUSBBufferSize(64*1024);
log.info("USB buffer size set to 64K");
}
if (_bundle.getMaxBuffer()==7) {
USBFlash.setUSBBufferSize(32*1024);
log.info("USB buffer size set to 32K");
}
boolean found=false;
try {
USBFlash.open("B00B");
try {
log.info("Reading device information");
loadProperties();
currentdevice=getPhoneProperty("product");
log.info("Connected device : "+currentdevice+" / SW release "+phoneprops.getProperty("swrelease")+" / Customization "+phoneprops.getProperty("customization"));
log.info("Last flash date : "+phoneprops.getProperty("lastflashdate"));
}
catch (Exception e) {
log.info(e.getMessage());
log.info("Unable to read from phone after having opened it.");
log.info("trying to continue anyway");
}
log.info("Phone ready for flashmode operations.");
if (_bundle.getDevice()!=null) {
if (_bundle.getDevice().length()>0 && !currentdevice.equals(_bundle.getDevice())) {
log.error("The bundle does not match the connected device");
close();
found = false;
}
else found=true;
}
else
found = true;
}
catch (Exception e){
e.printStackTrace();
found=false;
}
return found;
}
public boolean open() {
return open(_bundle.simulate());
}
public String getFlashScript() {
try {
if (_bundle.hasFsc()) {
return _bundle.getFsc().getAbsolutePath();
}
} catch (Exception e) {
}
DeviceEntry dev = Devices.getDeviceFromVariant(getCurrentDevice());
return dev.getFlashScript(_bundle.getVersion(), getCurrentDevice());
}
public boolean checkScript() {
try {
Vector<String> ignored = new Vector<String>();
FlashScript flashscript = new FlashScript(getFlashScript());
flashscript.setBootConfig(bc);
flashscript.setPartitionDelivery(pd);
Iterator<Category> icategs = _bundle.getMeta().getAllEntries(true).iterator();
while (icategs.hasNext()) {
Category cat = icategs.next();
if (!flashscript.hasCategory(cat)) {
if (!cat.getId().equals("FSCONFIG") ) {
ignored.add(cat.getId());
}
}
}
if (ignored.size()>0) {
Enumeration eignored = ignored.elements();
String dynmsg = "";
while (eignored.hasMoreElements()) {
dynmsg=dynmsg+eignored.nextElement();
if (eignored.hasMoreElements()) dynmsg = dynmsg + ",";
}
String result = WidgetTask.openYESNOBox(_curshell, "Those data are not in the FSC script and will be skipped : \n"+dynmsg+".\n Do you want to continue ?");
if (Integer.parseInt(result) == SWT.YES) {
return true;
}
return false;
}
return true;
} catch (Exception e) {
return false;
}
}
public boolean hasScript() {
File fsc=null;
try {
fsc=new File(getFlashScript());
}
catch (Exception e) {
fsc=null;
}
if (fsc!=null) {
if (fsc.exists()) {
if (_bundle.hasFsc()) return true;
String result = WidgetTask.openYESNOBox(_curshell, "A FSC script is found : "+fsc.getName()+". Do you want to use it ?");
return Integer.parseInt(result)==SWT.YES;
}
else return false;
}
return false;
}
public void runScript() {
try {
TextFile tf = new TextFile(getFlashScript(),"ISO8859-1");
log.info("Found a template session. Using it : "+tf.getFileName());
Map<Integer,String> map = tf.getMap();
Iterator<Integer> keys = map.keySet().iterator();
setFlashState(true);
while (keys.hasNext()) {
String param1="";
String param2="";
String line = map.get(keys.next());
String[] parsed = line.split(":");
String action = parsed[0];
if (parsed.length>1)
param1 = parsed[1];
if (parsed.length>2)
param2 = parsed[2];
if (action.equals("flash")) {
BundleEntry b = _bundle.searchEntry(param2);
if (b!=null) {
SinFile sin =new SinFile(new File(b.getAbsolutePath()));
flashImage(sin,param1);
}
else {
if (bc!=null) {
String file = bc.getMatchingFile(param2);
if (file!=null) {
SinFile sin =new SinFile(new File(file));
flashImage(sin,param1);
}
else {
log.warn(param2 + " is excluded from bundle");
}
}
else {
log.warn(param2 + " is excluded from bundle");
}
}
}
else if (action.equals("Repartition")) {
if (pd!=null) {
String file = pd.getMatchingFile(SinFile.getShortName(param2), _curshell);
if (file!=null) {
SinFile sin =new SinFile(new File(file));
repartition(sin,Integer.parseInt(param1));
}
else {
log.warn(param2 + " is excluded from bundle");
}
}
else {
BundleEntry b = _bundle.searchEntry(param2);
if (b!=null) {
SinFile sin =new SinFile(new File(b.getAbsolutePath()));
repartition(sin,Integer.parseInt(param1));
}
else
log.warn(param2 + " is excluded from bundle");
}
}
else if (action.equals("Write-TA")) {
if (Integer.parseInt(param1) == 2)
if (TaPartition2.get(Long.parseLong(param2))!=null) {
writeTA(2,TaPartition2.get(Long.parseLong(param2)));
}
else {
if (!param2.equals("10100") && !param2.equals("10021"))
log.warn("TA Unit "+param2 + " is excluded from bundle");
}
}
else if (action.equals("set_active")) {
setActive(param1);
}
else if (action.equals("Get-ufs-info")) {
getUfsInfo();
if (pd != null)
pd.setUfsInfos(ufs_infos);
}
else if (action.equals("Get-emmc-info")) {
getEmmcInfo();
if (pd != null)
pd.setEmmcInfos(emmc_infos);
}
else if (action.equals("Get-gpt-info")) {
GetGptInfo(Integer.parseInt(param1));
}
else if (action.equals("getvar")) {
getVar(param1);
}
}
setFlashState(false);
} catch (Exception e) {e.printStackTrace();}
}
public void flash() throws X10FlashException, IOException {
try {
//WidgetTask.openOKBox(_curshell, "This device protocol is not yet supported");
log.info("Start Flashing");
bc = getBootConfig();
pd = _bundle.getXMLPartitionDelivery();
if (pd!=null) {
pd.setFolder(_bundle.getPartitionDelivery().getFolder());
}
else {
String result = WidgetTask.openYESNOBox(_curshell, "No partition delivery included.\nMaybe a bundle created with a previous release of Flashtool.\nDo you want to continue ?");
if (Integer.parseInt(result)!=SWT.YES) throw new X10FlashException("No partition delivery");
}
loadTAFiles();
if (hasScript()) {
if (checkScript())
runScript();
}
else {
log.error("No flash script found. Flash script is mandatory");
}
} catch (Exception e) {
log.error(e.getMessage());
}
LogProgress.initProgress(0);
close();
}
public XMLBootConfig getBootConfig() throws FileNotFoundException, IOException,X10FlashException, TAFileParseException, BootDeliveryException {
if (!_bundle.hasBootDelivery()) {
log.info("No boot delivery into the bundle");
return null;
}
log.info("Parsing boot delivery");
XMLBootDelivery xml = _bundle.getXMLBootDelivery();
Vector<XMLBootConfig> found = new Vector<XMLBootConfig>();
Enumeration<XMLBootConfig> e = xml.getBootConfigs();
while (e.hasMoreElements()) {
// We get matching bootconfig from all configs
XMLBootConfig bc=e.nextElement();
bc.addMatcher("PLF_ROOT_HASH", phoneprops.getProperty("root-key-hash"));
if (bc.matchAttributes()) {
found.add(bc);
}
}
if (found.size()==0)
throw new BootDeliveryException ("Found no matching boot config. Aborting");
// if found more thant 1 config
boolean same = true;
if (found.size()>1) {
// Check if all found configs have the same fileset
Iterator<XMLBootConfig> masterlist = found.iterator();
while (masterlist.hasNext()) {
XMLBootConfig masterconfig = masterlist.next();
Iterator<XMLBootConfig> slavelist = found.iterator();
while (slavelist.hasNext()) {
XMLBootConfig slaveconfig = slavelist.next();
if (slaveconfig.compare(masterconfig)==2)
throw new BootDeliveryException ("Cannot decide among found configurations. Skipping boot delivery");
}
}
}
found.get(found.size()-1).setFolder(_bundle.getBootDelivery().getFolder());
log.info("Found a boot delivery");
return found.get(found.size()-1);
}
public void close() {
try {
sync();
powerDown();
} catch (Exception e) {
e.printStackTrace();
}
USBFlash.close();
}
public String getPhoneProperty(String property) {
return phoneprops.getProperty(property);
}
public Bundle getBundle() {
return _bundle;
}
public void getUfsInfo() throws IOException,X10FlashException {
log.info("Sending Get-ufs-info");
String command = "Get-ufs-info";
USBFlash.write(command.getBytes());
CommandPacket reply = USBFlash.readCommandReply(true);
log.info(" Get-ufs-info status : "+reply.getResponse());
JBBPParser ufs_parser = JBBPParser.prepare(
"byte headerlen;"
+ "byte[headerlen-1] ufs_header;"
+ "luns [_] { "
+ " byte lunlength; "
+ " byte reserved1; "
+ " byte lunid; "
+ " byte[12] reserved2; "
+ " int length; "
+ " byte[lunlength-19] lundata; "
+ "}"
);
try {
JBBPBitInputStream stream = new JBBPBitInputStream(new ByteArrayInputStream(reply.getDataArray()));
ufs_infos = ufs_parser.parse(stream).mapTo(new UfsInfos());
ufs_infos.setSectorSize(Integer.parseInt(getPhoneProperty("Sector-size")));
try {
stream.close();
} catch (Exception streamclose ) {}
}
catch (Exception e) {
log.error("Error parsing Get-ufs-info reply");
ufs_infos=null;
}
}
public void getEmmcInfo() throws IOException,X10FlashException {
log.info("Sending Get-emmc-info");
String command = "Get-emmc-info";
USBFlash.write(command.getBytes());
CommandPacket reply = USBFlash.readCommandReply(true);
log.info(" Get-emmc-info status : "+reply.getResponse());
JBBPParser emmc_parser = JBBPParser.prepare(
"byte[1] not_used;"
+ "byte[7] crc;"
+ "byte[2] ecc;"
+ "byte[2] file_format;"
+ "byte[1] tmp_write_protect;"
+ "byte[1] perm_write_protect;"
+ "byte[1] copy;"
+ "byte[1] file_format_group;"
+ "byte[1] content_prop_app;"
+ "byte[4] reserved1;"
+ "byte[1] write_bl_partial;"
+ "byte[4] write_bl_length;"
+ "byte[3] r2w_factor;"
+ "byte[2] default_ecc;"
+ "byte[1] wp_grp_enable;"
+ "byte[5] wp_grp_size;"
+ "byte[5] erase_grp_mult;"
+ "byte[5] erase_grp_size;"
+ "byte[3] c_size_mult;"
+ "byte[3] wdd_w_curr_max;"
+ "byte[3] wdd_w_curr_min;"
+ "byte[3] wdd_r_curr_max;"
+ "byte[3] wdd_r_curr_min;"
+ "byte[12] c_size;"
+ "byte[2] reserved2;"
+ "byte[1] dsr_imp;"
+ "byte[1] read_blk_misalign;"
+ "byte[1] write_blk_misalign;"
+ "byte[1] read_blk_partial;"
+ "byte[4] read_bl_length;"
+ "byte[12] ccc;"
+ "byte[8] tran_speed;"
+ "byte[8] nsac;"
+ "byte[8] taac;"
+ "byte[2] reserved3;"
+ "byte[4] spec_vers;"
+ "byte[2] csd_structure;"
+ "byte[6] reserved4;"
+ "byte[1] sec_bad_blk_mgmnt;"
+ "byte[1] reserved5;"
+ "byte[4] enh_start_addr;"
+ "byte[3] enh_size_mult;"
+ "byte[12] gp_size_mult;"
+ "byte[1] PARTITION_SETTING_COMPLETED;"
+ "byte[1] PARTITIONS_ATTRIBUTE;"
+ "byte[3] MAX_ENH_SIZE_MULT;"
+ "byte[1] PARTITIONING_SUPPORT;"
+ "byte[1] HPI_MGMT;"
+ "byte[1] RST_n_FUNCTION;"
+ "byte[1] BKOPS_EN;"
+ "byte[1] BKOPS_START;"
+ "byte[1] RESERVED6;"
+ "byte[1] WR_REL_PARAM;"
+ "byte[1] WR_REL_SET;"
+ "byte[1] RPMB_SIZE_MULT;"
+ "byte[1] FW_CONFIG;"
+ "byte[1] RESERVED7;"
+ "byte[1] USER_WP;"
+ "byte[1] RESERVED8;"
+ "byte[1] BOOT_WP;"
+ "byte[1] ERASE_GROUP_DEF;"
+ "byte[1] RESERVED9;"
+ "byte[1] BOOT_BUS_WIDTH;"
+ "byte[1] BOOT_CONFIG_PROT;"
+ "byte[1] PARTITION_CONFIG;"
+ "byte[1] RESERVED10;"
+ "byte[1] ERASED_MEM_CONT;"
+ "byte[1] RESERVED11;"
+ "byte[1] BUS_WIDTH;"
+ "byte[1] RESERVED12;"
+ "byte[1] HS_TIMING;"
+ "byte[1] RESERVED13;"
+ "byte[1] POWER_CLASS;"
+ "byte[1] RESERVED14;"
+ "byte[1] CMD_SET_REV;"
+ "byte[1] RESERVED15;"
+ "byte[1] CMD_SET;"
+ "byte[1] RESERVED16;"
+ "byte[1] EXT_CSD_REV;"
+ "byte[1] RESERVED17;"
+ "byte[1] CSD_STRUCTURE1;"
+ "byte[1] RESERVED18;"
+ "byte[1] CARD_TYPE;"
+ "byte[1] RESERVED19;"
+ "byte[1] OUT_OF_INTERRUPT_TIME;"
+ "byte[1] PARTITION_SWITCH_TIME;"
+ "byte[1] PWR_CL_52_195;"
+ "byte[1] PWR_CL_26_195;"
+ "byte[1] PWR_CL_52_360;"
+ "byte[1] PWR_CL_26_360;"
+ "byte[1] RESERVED20;"
+ "byte[1] MIN_PERF_R_4_26;"
+ "byte[1] MIN_PERF_W_4_26;"
+ "byte[1] MIN_PERF_R_8_26_4_52;"
+ "byte[1] MIN_PERF_W_8_26_4_52;"
+ "byte[1] MIN_PERF_R_8_52;"
+ "byte[1] MIN_PERF_W_8_52;"
+ "byte[1] RESERVED21;"
+ "<int SEC_COUNT;"
+ "byte[1] RESERVED22;"
+ "byte[1] S_A_TIMEOUT;"
+ "byte[1] RESERVED23;"
+ "byte[1] S_C_VCCQ;"
+ "byte[1] S_C_VCC;"
+ "byte[1] HC_WP_GRP_SIZE;"
+ "byte[1] REL_WR_SEC_C;"
+ "byte[1] ERASE_TIMEOUT_MULT;"
+ "byte[1] HC_ERASE_GRP_SIZE;"
+ "byte[1] ACC_SIZE;"
+ "byte[1] BOOT_SIZE_MULT;"
+ "byte[1] RESERVED24;"
+ "byte[1] BOOT_INFO;"
+ "byte[1] SEC_TRIM_MULT;"
+ "byte[1] SEC_ERASE_MULT;"
+ "byte[1] SEC_FEATURE_SUPPORT;"
+ "byte[1] TRIM_MULT;"
+ "byte[1] RESERVED25;"
+ "byte[1] MIN_PERF_DDR_R_8_52;"
+ "byte[1] MIN_PERF_DDR_W_8_52;"
+ "byte[2] RESERVED26;"
+ "byte[1] PWR_CL_DDR_52_195;"
+ "byte[1] PWR_CL_DDR_52_360;"
+ "byte[1] RESERVED27;"
+ "byte[1] INI_TIMEOUT_AP;"
+ "byte[4] CORRECTLY_PRG_SECTORS_NUM;"
+ "byte[1] BKOPS_STATUS;"
+ "byte[255] RESERVED28;"
+ "byte[1] BKOPS_SUPPORT;"
+ "byte[1] HPI_FEATURES;"
+ "byte[1] S_CMD_SET;"
+ "byte[7] RESERVED29;"
);
try {
JBBPBitInputStream stream = new JBBPBitInputStream(new ByteArrayInputStream(reply.getDataArray()));
emmc_infos = emmc_parser.parse(stream).mapTo(new EmmcInfos());
emmc_infos.setSectorSize(Integer.parseInt(getPhoneProperty("Sector-size")));
try {
stream.close();
} catch (Exception streamclose ) {}
}
catch (Exception e) {
log.error("Error parsing Emmc-info reply");
emmc_infos=null;
}
}
public void GetGptInfo(int partnumber) throws IOException,X10FlashException {
log.info("Sending Get-gpt-info:"+partnumber);
String command = "Get-gpt-info:"+partnumber;
USBFlash.write(command.getBytes());
CommandPacket reply = USBFlash.readCommandReply(true);
log.info(" Get-gpt-info status : "+reply.getResponse());
}
public void setActive(String name) throws IOException,X10FlashException {
log.info("Sending set_active:"+name);
if (!_bundle.simulate()) {
String command = "set_active:"+name;
USBFlash.write(command.getBytes());
CommandPacket reply = USBFlash.readCommandReply(true);
log.info(" set_active status : "+reply.getResponse());
}
}
public void setFlashState(boolean ongoing) throws IOException,X10FlashException {
if (!_bundle.simulate()) {
if (ongoing) {
writeTA(2,new TAUnit(10100,new byte[] {0x01}));
}
else {
String result = ZonedDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
TAUnit tau = new TAUnit(10021, BytesUtil.concatAll(result.getBytes(), new byte[] {0x00}));
writeTA(2,tau);
writeTA(2,new TAUnit(10100,new byte[] {0x00}));
}
}
}
public String getLog() throws X10FlashException, IOException {
log.info("Sending Getlog");
String command = "Getlog";
USBFlash.write(command.getBytes());
CommandPacket reply = USBFlash.readCommandReply(true);
log.info(" Getlog status : "+reply.getResponse());
return reply.getMessage();
}
public TAUnit readTA(int partition, int unit) throws X10FlashException, IOException {
return readTA(partition, unit, true);
}
public TAUnit readTA(int partition, int unit, boolean withlog) throws X10FlashException, IOException {
String command = "Read-TA:"+partition+":"+unit;
if (withlog)
log.info("Sending "+command);
USBFlash.write(command.getBytes());
CommandPacket reply = USBFlash.readCommandReply(true);
if (withlog)
log.info(" Read-TA status : "+reply.getResponse());
if (reply.getResponse().equals("OKAY")) {
TAUnit taunit = new TAUnit(unit,reply.getDataArray());
return taunit;
}
else {
if (withlog)
log.warn(" "+reply.getMessage()+" ( Hex unit value "+HexDump.toHex(unit)+" )");
return null;
}
}
public void writeTA(int partition, TAUnit unit) throws X10FlashException, IOException {
try {
//wrotedata=true;
log.info("Writing TA unit "+HexDump.toHex((int)unit.getUnitNumber())+" to partition "+partition);
if (!_bundle.simulate()) {
log.info(" download:"+HexDump.toHex(unit.getDataLength()));
String command = "download:"+HexDump.toHex(unit.getDataLength());
USBFlash.write(command.getBytes());
CommandPacket p = USBFlash.readCommandReply(false);
if (unit.getDataLength()>0) {
USBFlash.write(unit.getUnitData());
}
p = USBFlash.readCommandReply(true);
log.info(" download status : "+p.getResponse());
log.info(" Write-TA:"+partition+":"+unit.getUnitNumber());
command = "Write-TA:"+partition+":"+unit.getUnitNumber();
USBFlash.write(command.getBytes());
p = USBFlash.readCommandReply(true);
log.info(" Write-TA status : "+p.getResponse());
}
}
catch (Exception e) {
}
}
public void getVar(String key) throws X10FlashException, IOException {
String command = "getvar:"+key;
log.info("Sending "+command);
USBFlash.write(command.getBytes());
CommandPacket reply = USBFlash.readCommandReply(true);
log.info(" getvar status : "+reply.getResponse());
if (reply.getResponse().equals("FAIL")) {
log.warn(" "+reply.getMessage());
}
phoneprops.setProperty(key,reply.getMessage());
}
public void sync() throws IOException, X10FlashException {
log.info("Sending Sync");
if (!_bundle.simulate()) {
USBFlash.write(("Sync").getBytes());
CommandPacket p = USBFlash.readCommandReply(true);
log.info(" Sync status : "+p.getResponse());
}
}
public void powerDown() throws IOException, X10FlashException {
log.info("Sending powerdown");
USBFlash.write(("powerdown").getBytes());
CommandPacket p = USBFlash.readCommandReply(true);
log.info(" powerdown status : "+p.getResponse());
}
public void getRootKeyHash() throws IOException, X10FlashException {
log.info("Sending Get-root-key-hash");
USBFlash.write("Get-root-key-hash".getBytes());
CommandPacket p = USBFlash.readCommandReply(true);
log.info(" Get-root-key-hash status : "+p.getResponse());
phoneprops.setProperty("root-key-hash", HexDump.toHex(p.getDataArray()).replaceAll(" ", ""));
}
public void repartition(SinFile sin, int partnumber) throws IOException, X10FlashException {
//wrotedata=true;
String command="";
CommandPacket p;
log.info("processing "+sin.getName());
command = "download:"+HexDump.toHex(sin.getHeader().length);
log.info(" "+command);
if (!_bundle.simulate()) {
USBFlash.write(command.getBytes());
p = USBFlash.readCommandReply(false);
USBFlash.write(sin.getHeader());
p = USBFlash.readCommandReply(true);
log.info(" download status : "+p.getResponse());
command = "signature";
log.info(" "+command);
USBFlash.write(command.getBytes());
p = USBFlash.readCommandReply(true);
log.info(" signature status : "+p.getResponse());
}
TarArchiveInputStream tarIn = sin.getTarInputStream();
TarArchiveEntry entry=null;
while ((entry = tarIn.getNextTarEntry()) != null) {
if (!entry.getName().endsWith("cms")) {
log.info(" sending "+entry.getName());
if (!_bundle.simulate()) {
command = "download:"+HexDump.toHex((int)entry.getSize());
log.info(" "+command);
USBFlash.write(command.getBytes());
p = USBFlash.readCommandReply(false);
//log.info(" Download reply : "+p.getResponse());
}
CircularByteBuffer cb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
IOUtils.copy(tarIn, cb.getOutputStream());
while (cb.getAvailable()>0) {
byte[] buffer = new byte[cb.getAvailable()>=USBFlash.getUSBBufferSize()?USBFlash.getUSBBufferSize():cb.getAvailable()];
cb.getInputStream().read(buffer);
if (!_bundle.simulate()) {
USBFlash.write(buffer);
}
}
p=null;
if (!_bundle.simulate()) {
p = USBFlash.readCommandReply(true);
log.info(" download status : "+p.getResponse());
}
command="Repartition:"+partnumber;
log.info(" "+command);
if (!_bundle.simulate()) {
USBFlash.write(command.getBytes());
p = USBFlash.readCommandReply(true);
log.info(" Repartition status : "+p.getResponse());
}
}
}
tarIn.close();
}
public void flashImage(SinFile sin,String partitionname) throws X10FlashException, IOException {
//wrotedata=true;
String command="";
log.info("processing "+sin.getName());
command = "download:"+HexDump.toHex(sin.getHeader().length);
CommandPacket p=null;
if (!_bundle.simulate()) {
log.info(" "+command);
USBFlash.write(command.getBytes());
p = USBFlash.readCommandReply(false);
USBFlash.write(sin.getHeader());
p = USBFlash.readCommandReply(true);
log.info(" download status : "+p.getResponse());
command="signature";
log.info(" "+command);
USBFlash.write(command.getBytes());
p = USBFlash.readCommandReply(true);
log.info(" signature status : "+p.getResponse());
}
command="erase:"+partitionname;
log.info(" "+command);
if (!_bundle.simulate()) {
USBFlash.write(command.getBytes());
p = USBFlash.readCommandReply(true);
log.info(" erase status : "+p.getResponse());
}
TarArchiveInputStream tarIn = sin.getTarInputStream();
TarArchiveEntry entry=null;
while ((entry = tarIn.getNextTarEntry()) != null) {
if (!entry.getName().endsWith("cms")) {
log.info(" sending "+entry.getName());
if (!_bundle.simulate()) {
command = "download:"+HexDump.toHex((int)entry.getSize());
log.info(" "+command);
USBFlash.write(command.getBytes());
p = USBFlash.readCommandReply(false);
}
CircularByteBuffer cb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
IOUtils.copy(tarIn, cb.getOutputStream());
LogProgress.initProgress(cb.getAvailable()/USBFlash.getUSBBufferSize()+1);
while (cb.getAvailable()>0) {
byte[] buffer = new byte[cb.getAvailable()>=USBFlash.getUSBBufferSize()?USBFlash.getUSBBufferSize():cb.getAvailable()];
cb.getInputStream().read(buffer);
LogProgress.updateProgress();
if (!_bundle.simulate()) {
USBFlash.write(buffer);
}
else {
try {
Thread.sleep(10);} catch (Exception e) {}
}
}
if (!_bundle.simulate()) {
p = USBFlash.readCommandReply(true);
log.info(" download status : "+p.getResponse());
}
command="flash:"+partitionname;
log.info(" "+command);
if (!_bundle.simulate()) {
USBFlash.write(command.getBytes());
p = USBFlash.readCommandReply(true);
log.info(" flash status : "+p.getResponse());
}
LogProgress.initProgress(0);
}
}
tarIn.close();
}
public String getIMEI() {
return phoneprops.getProperty("Phone-id").split(":")[1];
}
public String getRootingStatus() {
return phoneprops.getProperty("Rooting-status");
}
public void sendLoader() throws FileNotFoundException, IOException, X10FlashException, SinFileException {
}
public void backupTA() {
log.info("Making a TA backup");
String timeStamp = OS.getTimeStamp();
LogProgress.initProgress(24000);
try {
backupTA(1, timeStamp);
} catch (Exception e) {}
try {
backupTA(2, timeStamp);
} catch (Exception e) {}
LogProgress.initProgress(0);
}
private void backupTA(int partition, String timestamp) {
log.info("Saving TA partition "+partition);
String folder = OS.getFolderRegisteredDevices()+File.separator+getPhoneProperty("serialno")+File.separator+"s1ta"+File.separator+timestamp;
new File(folder).mkdirs();
TextFile tazone = new TextFile(folder+File.separator+partition+".ta","ISO8859-1");
try {
tazone.open(false);
} catch (Exception e1) {
log.error("Unable to create backup file");
return;
}
try {
tazone.writeln(HexDump.toHex((byte)partition));
for (int unit = 0 ; unit < 12000; unit++) {
LogProgress.updateProgress();
try {
TAUnit taunit = this.readTA(partition, unit, false);
if (taunit != null)
tazone.writeln(taunit.toString());
} catch (Exception e3) {
e3.printStackTrace();
}
}
tazone.close();
log.info("TA partition "+partition+" saved to "+folder+File.separator+partition+".ta");
} catch (Exception e) {
e.printStackTrace();
}
}
public String getCurrentDevice() {
return currentdevice;
}
public String getSerial() {
return serial;
}
public void loadTAFiles() throws FileNotFoundException, IOException,X10FlashException {
Iterator<Category> entries = _bundle.getMeta().getTAEntries(true).iterator();
while (entries.hasNext()) {
Category categ = entries.next();
Iterator<BundleEntry> icateg = categ.getEntries().iterator();
while (icateg.hasNext()) {
BundleEntry bent = icateg.next();
if (bent.getName().toUpperCase().endsWith(".TA")) {
if (!bent.getName().toUpperCase().contains("SIMLOCK")) {
try {
TAFileParser ta = new TAFileParser(new File(bent.getAbsolutePath()));
Iterator<TAUnit> i = ta.entries().iterator();
while (i.hasNext()) {
TAUnit ent = i.next();
if (ent.getUnitNumber()!=2010)
TaPartition2.put(ent.getUnitNumber(),ent);
else
log.warn("Unit "+ent.getUnitNumber()+" is ignored");
}
}
catch (TAFileParseException tae) {
log.error("Error parsing TA file. Skipping");
}
}
else {
log.warn("File "+bent.getName()+" is ignored");
}
}
}
}
try {
if (bc!=null) {
TAFileParser taf = new TAFileParser(new File(bc.getTA()));
Iterator<TAUnit> i = taf.entries().iterator();
while (i.hasNext()) {
TAUnit ent = i.next();
TaPartition2.put(ent.getUnitNumber(),ent);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 38,201 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
FlasherFactory.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/FlasherFactory.java | package org.flashtool.flashsystem;
import org.eclipse.swt.widgets.Shell;
import org.flashtool.system.DeviceEntry;
import org.flashtool.system.Devices;
public class FlasherFactory {
public static Flasher getFlasher(Bundle b, Shell sh) {
if (Devices.getConnectedDevice().getPid().equals("ADDE")) return new S1Flasher(b, sh);
if (Devices.getConnectedDevice().getPid().equals("B00B")) return new CommandFlasher(b, sh);
if (Devices.getDeviceFromVariant(b.getDevice()).getProtocol().equals("Command")) return new CommandFlasher(b, sh);
return new S1Flasher(b, sh);
}
} | 576 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
FlasherConsole.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/FlasherConsole.java | package org.flashtool.flashsystem;
import java.io.File;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import org.flashtool.gui.About;
import org.flashtool.gui.MainSWT;
import org.flashtool.jna.adb.AdbUtility;
import org.flashtool.logger.MyLogger;
import org.flashtool.parsers.sin.SinFile;
import org.flashtool.system.DeviceChangedListener;
import org.flashtool.system.DeviceEntry;
import org.flashtool.system.DeviceProperties;
import org.flashtool.system.Devices;
import org.flashtool.system.FTShell;
import org.flashtool.system.GlobalConfig;
import org.flashtool.system.OS;
import org.flashtool.system.StatusEvent;
import org.flashtool.system.StatusListener;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FlasherConsole {
private static String fsep = OS.getFileSeparator();
public static void init(boolean withadb) {
log.info("Flashtool "+About.getVersion());
MainSWT.guimode=false;
StatusListener phoneStatus = new StatusListener() {
public void statusChanged(StatusEvent e) {
if (!e.isDriverOk()) {
log.error("Drivers need to be installed for connected device.");
log.error("You can find them in the drivers folder of Flashtool.");
}
else {
if (e.getNew().equals("adb")) {
log.info("Device connected with USB debugging on");
log.debug("Device connected, continuing with identification");
doIdent();
}
if (e.getNew().equals("none")) {
log.info("Device disconnected");
}
if (e.getNew().equals("flash")) {
log.info("Device connected in flash mode");
}
if (e.getNew().equals("fastboot")) {
log.info("Device connected in fastboot mode");
}
if (e.getNew().equals("normal")) {
log.info("Device connected with USB debugging off");
log.info("For 2011 devices line, be sure you are not in MTP mode");
}
}
}
};
DeviceChangedListener.starts(null);
}
public static void exit() {
DeviceChangedListener.stop();
MyLogger.writeFile();
System.exit(0);
}
public static void doRoot() {
Devices.waitForReboot(false);
if (Devices.getCurrent().getVersion().contains("2.3")) {
if (!Devices.getCurrent().hasRoot())
doRootzergRush();
else log.error("Your device is already rooted");
}
else
if (!Devices.getCurrent().hasRoot())
doRootpsneuter();
else log.error("Your device is already rooted");
exit();
}
public static void doRootzergRush() {
try {
AdbUtility.push(Devices.getCurrent().getBusybox(false), GlobalConfig.getProperty("deviceworkdir")+"/busybox");
FTShell shell = new FTShell("busyhelper");
shell.run(true);
AdbUtility.push(new File("."+fsep+"custom"+fsep+"root"+fsep+"zergrush.tar.uue").getAbsolutePath(),GlobalConfig.getProperty("deviceworkdir"));
shell = new FTShell("rootit");
log.info("Running part1 of Root Exploit, please wait");
shell.run(true);
Devices.waitForReboot(true);
log.info("Running part2 of Root Exploit");
shell = new FTShell("rootit2");
shell.run(false);
log.info("Finished!.");
log.info("Root should be available after reboot!");
}
catch (Exception e) {
log.error(e.getMessage());
}
}
public static void doRootpsneuter() {
try {
AdbUtility.push(Devices.getCurrent().getBusybox(false), GlobalConfig.getProperty("deviceworkdir")+"/busybox");
FTShell shell = new FTShell("busyhelper");
shell.run(true);
AdbUtility.push("."+fsep+"custom"+fsep+"root"+fsep+"psneuter.tar.uue",GlobalConfig.getProperty("deviceworkdir"));
shell = new FTShell("rootit");
log.info("Running part1 of Root Exploit, please wait");
shell.run(false);
Devices.waitForReboot(true);
log.info("Running part2 of Root Exploit");
shell = new FTShell("rootit2");
shell.run(false);
log.info("Finished!.");
log.info("Root should be available after reboot!");
}
catch (Exception e) {
log.error(e.getMessage());
}
}
public static void doGetIMEI() throws Exception {
Flasher f=null;
try {
Bundle b = new Bundle();
b.setSimulate(false);
f = new S1Flasher(b,null);
log.info("Please connect your phone in flash mode");
while (!f.flashmode());
f.open(false);
log.info("IMEI : "+f.getPhoneProperty("IMEI"));
f.close();
exit();
}
catch (Exception e) {
if (f!=null) f.close();
throw e;
}
}
public static void doExtract(String file) {
try {
SinFile sin = new SinFile(new File(file));
sin.dumpImage();
}
catch (Exception e) {
}
}
public static void doFlash(String file,boolean wipedata,boolean wipecache,boolean excludebb,boolean excludekrnl, boolean excludesys) throws Exception {
Flasher f=null;
try {
File bf = new File(file);
if (!bf.exists()) {
log.error("File "+bf.getAbsolutePath()+" does not exist");
exit();
}
log.info("Choosed "+bf.getAbsolutePath());
Bundle b = new Bundle(bf.getAbsolutePath(),Bundle.JARTYPE);
b.setSimulate(false);
b.getMeta().setCategEnabled("DATA", wipedata);
b.getMeta().setCategEnabled("CACHE", wipecache);
b.getMeta().setCategEnabled("BASEBAND", excludebb);
b.getMeta().setCategEnabled("SYSTEM", excludesys);
b.getMeta().setCategEnabled("KERNEL", excludekrnl);
log.info("Preparing files for flashing");
b.open();
f = new S1Flasher(b,null);
log.info("Please connect your phone in flash mode");
while (!f.flashmode());
f.open(false);
f.flash();
b.close();
exit();
}
catch (Exception e) {
if (f!=null) f.close();
throw e;
}
}
public static void doIdent() {
Enumeration<Object> e = Devices.listDevices(true);
if (!e.hasMoreElements()) {
log.error("No device is registered in Flashtool.");
log.error("You can only flash devices.");
return;
}
boolean found = false;
Properties founditems = new Properties();
founditems.clear();
Properties buildprop = new Properties();
buildprop.clear();
while (e.hasMoreElements()) {
DeviceEntry current = Devices.getDevice((String)e.nextElement());
String prop = current.getBuildProp();
if (!buildprop.containsKey(prop)) {
String readprop = DeviceProperties.getProperty(prop);
buildprop.setProperty(prop,readprop);
}
Iterator<String> i = current.getRecognitionList().iterator();
String localdev = buildprop.getProperty(prop);
while (i.hasNext()) {
String pattern = i.next().toUpperCase();
if (localdev.toUpperCase().contains(pattern)) {
founditems.put(current.getId(), current.getName());
}
}
}
if (founditems.size()==1) {
found = true;
Devices.setCurrent((String)founditems.keys().nextElement());
if (!Devices.isWaitingForReboot())
log.info("Connected device : " + Devices.getCurrent().getId());
}
else {
log.error("Cannot identify your device.");
log.error("You can only flash devices.");
}
if (found) {
if (!Devices.isWaitingForReboot()) {
log.info("Installed version of busybox : " + Devices.getCurrent().getInstalledBusyboxVersion(false));
log.info("Android version : "+Devices.getCurrent().getVersion()+" / kernel version : "+Devices.getCurrent().getKernelVersion());
}
if (Devices.getCurrent().isRecovery()) {
log.info("Phone in recovery mode");
if (!Devices.isWaitingForReboot())
log.info("Root Access Allowed");
}
else {
boolean hasSU = Devices.getCurrent().hasSU();
if (hasSU) {
boolean hasRoot = Devices.getCurrent().hasRoot();
if (hasRoot)
if (!Devices.isWaitingForReboot())
log.info("Root Access Allowed");
}
}
log.debug("Stop waiting for device");
if (Devices.isWaitingForReboot())
Devices.stopWaitForReboot();
log.debug("End of identification");
}
}
} | 8,043 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
S1Packet.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/S1Packet.java | package org.flashtool.flashsystem;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.flashtool.util.BytesUtil;
import org.flashtool.util.HexDump;
public class S1Packet {
//[DWORD] CMD
//[DWORD] FLAGS ( 1 | 2 | 4 )
//[DWORD] LEN
//[BYTE] HDR CHECKSUM
//[BYTE[LEN]] DATA
//[DWORD] DATA CHECKSUM (CRC32)
int command=0;
int flag=0;
int length=0;
byte hdrcksum=0;
ByteArrayOutputStream bcommand = new ByteArrayOutputStream();
ByteArrayOutputStream bflag = new ByteArrayOutputStream();
ByteArrayOutputStream blength = new ByteArrayOutputStream();
ByteArrayOutputStream bdata = new ByteArrayOutputStream();
ByteArrayOutputStream bcrc32 = new ByteArrayOutputStream();
byte[] data=null;
byte[] crc32=null;
public S1Packet(byte[] pdata) throws IOException {
addData(pdata);
}
public S1Packet(int pcommand, byte[] pdata, boolean ongoing) {
command = pcommand;
setFlags(false,true,ongoing);
if (pdata==null)
length = 0;
else
length = pdata.length;
data=pdata;
hdrcksum = calculateHeaderCkSum();
crc32=calculatedCRC32();
}
public S1Packet(int pcommand, byte pdata, boolean ongoing) {
command = pcommand;
setFlags(false,true,ongoing);
data = new byte[] {pdata};
length=1;
hdrcksum = calculateHeaderCkSum();
crc32=calculatedCRC32();
}
public void mergeWith(S1Packet p) throws IOException {
data=BytesUtil.concatAll(data, p.getDataArray());
length=data.length;
bdata.write(p.getDataArray());
flag=p.getFlags();
crc32=getCRC32();
}
public boolean isValid() {
if (BytesUtil.getLong(calculatedCRC32())!=BytesUtil.getLong(crc32))
return false;
if (calculateHeaderCkSum()!=hdrcksum)
return false;
return true;
}
public void validate() throws X10FlashException {
try {
if (BytesUtil.getLong(calculatedCRC32())!=BytesUtil.getLong(crc32))
throw new X10FlashException("S1 Data CRC32 Error");
if (calculateHeaderCkSum()!=hdrcksum)
throw new X10FlashException("S1 Header checksum Error");
}
catch (Exception e) {
throw new X10FlashException(e.getMessage());
}
}
public byte[] getByteArray() {
if (length==0)
return BytesUtil.concatAll(getHeader(), new byte[] {hdrcksum}, crc32);
else
return BytesUtil.concatAll(getHeader(), new byte[] {hdrcksum}, data, crc32);
}
public void release() {
data = null;
crc32 = null;
}
public void setFlags(boolean flag1, boolean flag2, boolean ongoing) {
flag = getFlag(flag1,flag2,ongoing);
}
private int getFlag(boolean flag1, boolean flag2, boolean ongoing)
{
boolean flag = !flag1;
byte byte0 = (byte)(flag2 ? 2 : 0);
byte byte1 = (byte)(ongoing ? 4 : 0);
return (((byte)(flag ? 1 : 0))) | byte0 | byte1;
}
public int getFlags() {
return flag;
}
public String getFlagsAsString() {
String result = "";
int flag1 = getFlags()&1;
int flag2 = getFlags()&2;
int multipacket = getFlags()&4;
if (flag1==0) result = "true"; else result="false";
if (flag2==0) result += ",false"; else result+=",true";
if (multipacket==0) result += ",false"; else result+=",true";
return result;
}
public boolean isMultiPacket() {
int multipacket = getFlags()&4;
if (multipacket==0)
return false;
else
return true;
}
public boolean hasErrors() {
int flag1 = getFlags()&1;
if (flag1==0)
return true;
else
return false;
}
public int getCommand() {
return command;
}
public int getDataLength() {
return length;
}
public byte[] getDataArray() {
return data;
}
public String getDataString() {
try {
return new String(data);
} catch (Exception e) { return "";}
}
public void addData(byte[] datachunk) throws IOException {
for (int i=0;i<datachunk.length;i++) {
if (bcommand.toByteArray().length<4) {
bcommand.write(datachunk[i]);
if (command==0 && bcommand.toByteArray().length==4) {
command=BytesUtil.getInt(bcommand.toByteArray());
}
}
else if (bflag.toByteArray().length<4) {
bflag.write(datachunk[i]);
if (flag==0 && bflag.toByteArray().length==4) {
flag=BytesUtil.getInt(bflag.toByteArray());
}
}
else if (blength.toByteArray().length<4) {
blength.write(datachunk[i]);
if (length==0 && blength.toByteArray().length==4) {
length=BytesUtil.getInt(blength.toByteArray());
}
}
else if (hdrcksum==0) {
hdrcksum=datachunk[i];
}
else if (bdata.toByteArray().length<length) {
bdata.write(datachunk[i]);
if (data==null && bdata.toByteArray().length==length) {
data=bdata.toByteArray();
}
}
else if (bcrc32.toByteArray().length<4) {
bcrc32.write(datachunk[i]);
if (crc32==null && bcrc32.toByteArray().length==4) {
crc32=bcrc32.toByteArray();
}
}
}
}
public String toString() {
return "CommandID : "+getCommand()+" / Flags : "+this.getFlagsAsString()+" / Data length : "+this.getDataLength()+" / Data CRC32 : "+HexDump.toHex(crc32);
}
public byte[] calculatedCRC32() {
if (data ==null) return null;
return BytesUtil.getCRC32(data);
}
public boolean isHeaderValid() {
if (command==0) return false;
return hdrcksum==calculateHeaderCkSum();
}
public boolean isDataComplete() {
if (data==null && length==0) return true;
if (data==null) return false;
if (data.length<length) return false;
return true;
}
public boolean isCRCComplete() {
if (crc32==null) return false;
if (crc32.length<4) return false;
return true;
}
public boolean hasMoreToRead() {
return !(isHeaderValid() && isDataComplete() && isCRCComplete());
}
public byte calculateHeaderCkSum()
{
byte header[] = getHeader();
byte result = calcSum(header);
header = null;
return result;
}
private byte calcSum(byte paramArray[])
{
byte byte0 = 0;
if(paramArray.length < 12)
return 0;
for(int i = 0; i < 12; i++)
byte0 ^= paramArray[i];
byte0 += 7;
return byte0;
}
public void saveDataAs(String file) {
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
}
catch (Exception e) {e.printStackTrace();}
}
public byte[] getCRC32() {
return crc32;
}
public byte[] getHeader() {
return BytesUtil.concatAll(BytesUtil.getBytesWord(command, 4),
BytesUtil.getBytesWord(flag, 4),
BytesUtil.getBytesWord(length, 4)
);
}
public byte[] getHeaderWithChecksum() {
return BytesUtil.concatAll(BytesUtil.getBytesWord(command, 4),
BytesUtil.getBytesWord(flag, 4),
BytesUtil.getBytesWord(length, 4),
new byte[] {hdrcksum}
);
}
public byte getCksum() {
return hdrcksum;
}
} | 6,861 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
BundleEntry.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/BundleEntry.java | package org.flashtool.flashsystem;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.flashtool.parsers.sin.SinFile;
import org.flashtool.system.OS;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class BundleEntry {
private File fileentry = null;
private JarFile jarfile = null;
private JarEntry jarentry = null;
private String _category = "";
private String _internal = "";
private String getExtension() {
if (fileentry!=null) {
int extpos = fileentry.getName().lastIndexOf(".");
if (extpos > -1) {
return fileentry.getName().substring(extpos);
}
return "";
}
else {
int extpos = jarentry.getName().lastIndexOf(".");
if (extpos > -1) {
return jarentry.getName().substring(extpos);
}
return "";
}
}
public BundleEntry(File f) {
fileentry = f;
if (f.getName().toUpperCase().endsWith("FSC"))
_category = "FSC";
else
_category = SinFile.getShortName(fileentry.getName()).toUpperCase();
_internal = org.flashtool.parsers.sin.SinFile.getShortName(fileentry.getName())+getExtension();
}
public BundleEntry(JarFile jf, JarEntry j) {
jarentry = j;
jarfile = jf;
if (jarentry.getName().toUpperCase().endsWith("FSC")) {
_category = "FSC";
}
else
_category = SinFile.getShortName(jarentry.getName()).toUpperCase();
_internal = org.flashtool.parsers.sin.SinFile.getShortName(jarentry.getName())+getExtension();
}
public InputStream getInputStream() throws FileNotFoundException, IOException {
if (fileentry!=null) {
log.info("Streaming from file : "+fileentry.getPath());
return new FileInputStream(fileentry);
}
else {
log.debug("Streaming from jar entry : "+jarentry.getName());
return jarfile.getInputStream(jarentry);
}
}
public String getName() {
if (this.isJarEntry()) return jarentry.getName();
return fileentry.getName();
}
public String getInternal() {
return _internal;
}
public String getAbsolutePath() {
return fileentry.getAbsolutePath();
}
public boolean isJarEntry() {
return jarentry!=null;
}
public String getMD5() {
if (fileentry!=null) return OS.getMD5(fileentry);
else return "";
}
public long getSize() {
if (fileentry!=null) return fileentry.length();
else return jarentry.getSize();
}
public String getCategory() {
return _category;
}
public String getFolder() {
return new File(getAbsolutePath()).getParent();
}
public void saveTo(String folder) throws FileNotFoundException, IOException {
if (isJarEntry()) {
log.debug("Saving entry "+getName()+" to disk");
InputStream in = getInputStream();
String outname = folder+File.separator+getName();
if (outname.endsWith("tab") || outname.endsWith("sinb")) outname = outname.substring(0, outname.length()-1);
fileentry=new File(outname);
fileentry.getParentFile().mkdirs();
log.debug("Writing Entry to "+outname);
OS.writeToFile(in, fileentry);
in.close();
}
}
} | 3,093 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
FlashScript.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/FlashScript.java | package org.flashtool.flashsystem;
import java.io.File;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import org.flashtool.gui.tools.XMLBootConfig;
import org.flashtool.gui.tools.XMLPartitionDelivery;
import org.flashtool.parsers.sin.SinFile;
import org.flashtool.parsers.ta.TAFileParser;
import org.flashtool.parsers.ta.TAUnit;
import org.flashtool.system.TextFile;
public class FlashScript {
Vector<String> categories = new Vector<String>();
Vector<Long> units = new Vector<Long>();
private XMLBootConfig bc=null;
private XMLPartitionDelivery pd=null;
public FlashScript(String fsc) {
TextFile flashscript = new TextFile(fsc,"ISO8859-1");
try {
Map<Integer,String> map = flashscript.getMap();
Iterator<Integer> keys = map.keySet().iterator();
while (keys.hasNext()) {
String line = map.get(keys.next());
String param1="";
String param2="";
String[] parsed = line.split(":");
String action = parsed[0];
if (parsed.length>1) param1=parsed[1];
if (parsed.length>2) param2=parsed[2];
if (action.equals("uploadImage")) {
if (param1.toUpperCase().equals("PARTITION")) {
categories.add("PARTITION-IMAGE");
}
categories.add(Category.getCategoryFromName(param1));
}
if (action.equals("writeTA")) units.add(Long.parseLong(param1));
if (action.equals("flash")) categories.add(Category.getCategoryFromName(param2));
if (action.equals("Repartition")) {
categories.add(Category.getCategoryFromName(param2));
}
if (action.equals("Write-TA")) units.add(Long.parseLong(param2));
}
} catch (Exception e) {}
}
public boolean hasCategory(Category category) {
if (category.isPartitionDelivery()) {
if (pd==null) return false;
Enumeration<String> efiles = pd.getFiles();
while (efiles.hasMoreElements()) {
String file = efiles.nextElement();
if (!categories.contains(Category.getCategoryFromName(file)))
return false;
}
return true;
}
if (category.isBootDelivery()) {
if (bc==null) return false;
Iterator ifiles = bc.getFiles().iterator();
while (ifiles.hasNext()) {
String file = (String)ifiles.next();
if (!categories.contains(Category.getCategoryFromName(file)))
return false;
}
try {
TAFileParser tf = new TAFileParser(new File(bc.getTA()));
Iterator<TAUnit> taul = tf.entries().iterator();
while (taul.hasNext()) {
TAUnit u = taul.next();
if (!units.contains(u.getUnitNumber()))
return false;
}
}
catch (Exception e) {
return false;
}
return true;
}
if (!category.isTa()) {
if (categories.contains(category.getId())) return true;
Enumeration ecategs = categories.elements();
while (ecategs.hasMoreElements()) {
String elem = (String)ecategs.nextElement();
if (category.getId().equals(SinFile.getShortName(elem))) return true;
}
return false;
}
try {
TAFileParser tf = new TAFileParser(new File(category.getEntries().iterator().next().getAbsolutePath()));
Iterator<TAUnit> taul = tf.entries().iterator();
while (taul.hasNext()) {
TAUnit u = taul.next();
if (!units.contains(u.getUnitNumber())) {
return false;
}
}
return true;
}
catch (Exception e) {
return false;
}
}
public void setBootConfig(XMLBootConfig bc) {
this.bc=bc;
}
public void setPartitionDelivery(XMLPartitionDelivery pd) {
this.pd=pd;
}
} | 3,528 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
Category.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/Category.java | package org.flashtool.flashsystem;
import java.util.ArrayList;
import java.util.List;
import org.flashtool.parsers.sin.SinFile;
import org.flashtool.parsers.sin.SinFileException;
public class Category implements Comparable<Category> {
private String id;
private List<BundleEntry> entries = new ArrayList<BundleEntry>();
private boolean enabled = false;
private boolean issin = false;
private boolean ista = false;
private boolean isbootdelivery = false;
private boolean ispartitiondelivery = false;
private boolean ispartition = false;
private boolean issecro = false;
private boolean ispreload = false;
private boolean iselabel = false;
private boolean issystemuser = false;
private boolean issw = false;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<BundleEntry> getEntries() {
return entries;
}
public void addEntry(BundleEntry f) throws SinFileException {
//System.out.println(f.getInternal()+" + "+f.getName());
entries.add(f);
if (f.getName().endsWith(".sin")) issin=true;
if (f.getName().endsWith(".ta")) ista=true;
if (f.getName().contains("boot_delivery")) isbootdelivery = true;
if (f.getName().contains("partition_delivery")) ispartitiondelivery = true;
if (issin) {
if (f.getName().toUpperCase().contains("PARTITION")) {
ispartition = true;
}
else if (f.getName().toUpperCase().contains("SECRO")) {
issecro = true;
}
else if (f.getName().toUpperCase().contains("PRELOAD")) {
ispreload = true;
}
else if (f.getName().toUpperCase().contains("ELABEL")) {
iselabel = true;
}
else if (f.getName().toUpperCase().contains("SYSTEM") || f.getName().toUpperCase().contains("USER") || f.getName().toUpperCase().contains("OEM") || f.getName().toUpperCase().contains("VENDOR") || f.getName().toUpperCase().contains("B2B") || f.getName().toUpperCase().contains("SSD")) {
issystemuser = true;
}
else
issw = true;
}
}
public boolean isPartition() {
return ispartition;
}
public boolean isSecro() {
return issecro;
}
public boolean isPreload() {
return ispreload;
}
public boolean isElabel() {
return iselabel;
}
public boolean isSystem() {
return issystemuser;
}
public boolean isSoftware() {
return issw;
}
public String toString() {
return id;
}
public boolean isTa() {
return ista;
}
public boolean isSin() {
return issin;
}
public boolean isBootDelivery() {
return isbootdelivery;
}
public boolean isPartitionDelivery() {
return ispartitiondelivery;
}
public boolean equals(Category c) {
return c.getId().equals(id);
}
@Override
public int hashCode() {
return id.hashCode();
}
public boolean isEnabled() {
return enabled;
}
@Override
public boolean equals(Object o) {
if (o instanceof String)
return id.equals((String)o);
if (o instanceof Category)
return ((Category)o).getId().equals(id);
return false;
}
@Override
public int compareTo(Category o) {
return this.id.compareTo(o.getId());
}
public void setEnabled(boolean enabled) {
this.enabled=enabled;
}
public static String getCategoryFromName(String name) {
return SinFile.getShortName(name).toUpperCase();
}
}
| 3,530 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
CommandPacket.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/CommandPacket.java | package org.flashtool.flashsystem;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import org.flashtool.util.BytesUtil;
public class CommandPacket {
ByteArrayOutputStream bresponse = new ByteArrayOutputStream();
String response="";
ByteArrayOutputStream blength = new ByteArrayOutputStream();
int length=-1;
ByteArrayOutputStream bdata = new ByteArrayOutputStream();
ByteArrayOutputStream tmpdata = new ByteArrayOutputStream();
boolean withOK=true;
public CommandPacket(byte[] datachunk, boolean withOk) {
this.withOK=withOk;
addData(datachunk);
}
public void addData(byte[] datachunk) {
for (int i=0;i<datachunk.length;i++) {
if (bresponse.toByteArray().length<4) {
bresponse.write(datachunk[i]);
if (response.length()==0 && bresponse.toByteArray().length==4) {
response=new String(bresponse.toByteArray());
}
}
else {
if (response.equals("OKAY") || response.equals("FAIL")) {
bdata.write(datachunk[i]);
} else if (response.equals("DATA")) {
if (blength.toByteArray().length<8) {
blength.write(datachunk[i]);
if (length==-1 && blength.toByteArray().length==8) {
length=BytesUtil.getInt(blength.toByteArray());
}
} else {
tmpdata.write(datachunk[i]);
try {
if (new String(tmpdata.toByteArray()).endsWith("FAIL")) {
response="FAIL";
bdata.write(Arrays.copyOf(tmpdata.toByteArray(), tmpdata.toByteArray().length-4));
}
if (new String(tmpdata.toByteArray()).endsWith("OKAY")) {
response="OKAY";
bdata.write(Arrays.copyOf(tmpdata.toByteArray(), tmpdata.toByteArray().length-4));
}
} catch (Exception e) {}
}
}
}
}
}
public boolean hasMoreToRead() {
boolean isFinished1 = (response.equals("DATA") && withOK==false);
boolean isFinished2 = ((response.equals("OKAY") || response.equals("FAIL")) && withOK);
return !isFinished1 && !isFinished2;
}
public byte[] getDataArray() {
return bdata.toByteArray();
}
public String getMessage() {
return new String(bdata.toByteArray());
}
public int getStatus() {
return 0;
}
public String getResponse() {
return response;
}
} | 2,226 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
USBFlashWin32.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/io/USBFlashWin32.java | package org.flashtool.flashsystem.io;
import java.io.IOException;
import org.flashtool.flashsystem.S1Command;
import org.flashtool.flashsystem.X10FlashException;
import org.flashtool.jna.win32.JKernel32;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class USBFlashWin32 {
public static void windowsOpen(String pid) throws IOException {
log.info("Opening device for R/W");
JKernel32.openDevice();
log.info("Device ready for R/W.");
}
public static void windowsClose() {
JKernel32.closeDevice();
}
public static boolean windowsWrite(byte[] array) throws IOException,X10FlashException {
JKernel32.writeBytes(array);
return true;
}
public static byte[] windowsRead(int length) throws IOException {
return JKernel32.readBytes(length);
}
} | 783 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
USBFlash.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/io/USBFlash.java | package org.flashtool.flashsystem.io;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.flashtool.flashsystem.CommandPacket;
import org.flashtool.flashsystem.S1Command;
import org.flashtool.flashsystem.S1Packet;
import org.flashtool.flashsystem.X10FlashException;
import org.flashtool.libusb.LibUsbException;
import org.flashtool.system.OS;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class USBFlash {
private static int buffersize=512*1024;
private static int readbuffer=512*1024;
public static void setUSBBufferSize(int size) {
buffersize=size;
}
public static int getUSBBufferSize() {
return buffersize;
}
public static void open(String pid) throws IOException, Exception {
if (OS.getName().equals("windows")) {
USBFlashWin32.windowsOpen(pid);
}
else {
USBFlashLinux.linuxOpen(pid);
}
}
public static void close() {
if (OS.getName().equals("windows")) {
USBFlashWin32.windowsClose();
}
else
USBFlashLinux.linuxClose();
}
public static S1Packet writeS1(S1Packet p) throws IOException,X10FlashException {
write(p.getHeaderWithChecksum());
if (p.getDataLength()>0) {
long totalread=0;
ByteArrayInputStream in = new ByteArrayInputStream(p.getDataArray());
while (totalread<p.getDataLength()) {
long remaining = p.getDataLength()-totalread;
long bufsize=(remaining<buffersize)?remaining:buffersize;
byte[] buf = new byte[(int)bufsize];
int read = in.read(buf);
write(buf);
totalread+=read;
}
in.close();
}
write(p.getCRC32());
return readS1Reply();
}
public static void write(byte[] array) throws IOException,X10FlashException {
if (OS.getName().equals("windows")) {
USBFlashWin32.windowsWrite(array);
}
else {
USBFlashLinux.linuxWrite(array);
}
}
public static S1Packet readS1Reply() throws X10FlashException, IOException
{
byte[] read=null;
S1Packet p=new S1Packet("".getBytes());
while (p.hasMoreToRead()) {
try {
read = read(readbuffer);
} catch (LibUsbException e) {
read=null;
}
if (read != null)
p.addData(read);
}
p.validate();
return p;
}
public static CommandPacket readCommandReply(boolean withOK) throws X10FlashException, IOException
{
log.debug("Reading packet from phone");
byte[] read=null;
CommandPacket p = new CommandPacket("".getBytes(),withOK);
while (p.hasMoreToRead()) {
try {
read = read(readbuffer);
} catch (LibUsbException e) {
read=null;
}
if (read != null)
p.addData(read);
}
log.debug("IN : " + p);
return p;
//lastflags = p.getFlags();
}
private static byte[] read(int length) throws LibUsbException, IOException,X10FlashException {
if (OS.getName().equals("windows")) {
return USBFlashWin32.windowsRead(length);
}
else {
return USBFlashLinux.linuxRead(length);
}
}
} | 2,955 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
USBFlashLinux.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/flashsystem/io/USBFlashLinux.java | package org.flashtool.flashsystem.io;
import java.io.IOException;
import org.flashtool.flashsystem.S1Command;
import org.flashtool.flashsystem.X10FlashException;
import org.flashtool.jna.linux.JUsb;
import org.flashtool.libusb.LibUsbException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class USBFlashLinux {
public static void linuxOpen(String pid) throws IOException, Exception {
log.info("Opening device for R/W");
JUsb.fillDevice(false);
JUsb.open();
log.info("Device ready for R/W.");
}
public static void linuxClose() {
try {
JUsb.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void linuxWrite(byte[] array) throws IOException,X10FlashException {
try {
JUsb.writeBytes(array);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static byte[] linuxRead(int length) throws LibUsbException {
return JUsb.readBytes(length);
}
} | 1,002 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
ElfHelper.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/elf/ElfHelper.java | /*******************************************************************************
* Copyright (c) 2011 - J.W. Janssen
*
* Copyright (c) 2000, 2008 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - Initial API and implementation
* J.W. Janssen - Clean up and made API more OO-oriented
*******************************************************************************/
package org.flashtool.binutils.elf;
import java.io.*;
import java.util.*;
/**
*
*/
public class ElfHelper
{
// INNER TYPES
/**
*
*/
public static class Sizes
{
// VARIABLES
public final long text;
public final long data;
public final long bss;
public final long total;
// CONSTRUCTORS
/**
* @param aText
* @param aData
* @param aBss
*/
public Sizes(final long aText, final long aData, final long aBss)
{
this.text = aText;
this.data = aData;
this.bss = aBss;
this.total = this.text + this.data + this.bss;
}
}
// VARIABLES
private Elf elf;
private Symbol[] dynsyms;
private Symbol[] symbols;
private Section[] sections;
private Dynamic[] dynamics;
// CONSTRUCTORS
/**
* Create a new <code>ElfHelper</code> using an existing <code>Elf</code>
* object.
*
* @param aElf
* An existing Elf object to wrap.
* @throws IOException
* Error processing the Elf file.
*/
public ElfHelper(final Elf aElf) throws IOException
{
this.elf = aElf;
}
/**
* Create a new <code>ElfHelper</code> based on the given filename.
*
* @param aFile
* The file to use for creating a new Elf object.
* @throws IOException
* Error processing the Elf file.
* @see Elf#Elf(String )
*/
public ElfHelper(final File aFile) throws IOException
{
this.elf = new Elf(aFile);
}
// METHODS
/**
*
*/
public void dispose()
{
if (this.elf != null)
{
this.elf.dispose();
this.elf = null;
}
}
/**
* @return
* @throws IOException
*/
public Symbol[] getCommonObjects() throws IOException
{
final List<Symbol> v = new ArrayList<Symbol>();
loadSymbols();
loadSections();
for (final Symbol symbol : this.symbols)
{
if ((symbol.getBind() == Symbol.STB_GLOBAL) && (symbol.getType() == Symbol.STT_OBJECT))
{
final int idx = symbol.getSectionHeaderTableIndex();
if (idx == Symbol.SHN_COMMON)
{
v.add(symbol);
}
}
}
return v.toArray(new Symbol[v.size()]);
}
/**
* Give back the Elf object that this helper is wrapping
*/
public Elf getElf()
{
return this.elf;
}
/**
* @return
* @throws IOException
*/
public Symbol[] getExternalFunctions() throws IOException
{
final List<Symbol> v = new ArrayList<Symbol>();
loadSymbols();
loadSections();
for (final Symbol dynsym : this.dynsyms)
{
if ((dynsym.getBind() == Symbol.STB_GLOBAL) && (dynsym.getType() == Symbol.STT_FUNC))
{
final int idx = dynsym.getSectionHeaderTableIndex();
if ((idx < Symbol.SHN_HIPROC) && (idx > Symbol.SHN_LOPROC))
{
final String name = dynsym.toString();
if ((name != null) && (name.trim().length() > 0))
{
v.add(dynsym);
}
}
else if ((idx >= 0) && (this.sections[idx].getType() == Section.SHT_NULL))
{
v.add(dynsym);
}
}
}
return v.toArray(new Symbol[v.size()]);
}
/**
* @return
* @throws IOException
*/
public Symbol[] getExternalObjects() throws IOException
{
final List<Symbol> v = new ArrayList<Symbol>();
loadSymbols();
loadSections();
for (final Symbol dynsym : this.dynsyms)
{
if ((dynsym.getBind() == Symbol.STB_GLOBAL) && (dynsym.getType() == Symbol.STT_OBJECT))
{
final int idx = dynsym.getSectionHeaderTableIndex();
if ((idx < Symbol.SHN_HIPROC) && (idx > Symbol.SHN_LOPROC))
{
final String name = dynsym.toString();
if ((name != null) && (name.trim().length() > 0))
{
v.add(dynsym);
}
}
else if ((idx >= 0) && (this.sections[idx].getType() == Section.SHT_NULL))
{
v.add(dynsym);
}
}
}
return v.toArray(new Symbol[v.size()]);
}
/**
* @return
* @throws IOException
*/
public Symbol[] getLocalFunctions() throws IOException
{
final List<Symbol> v = new ArrayList<Symbol>();
loadSymbols();
loadSections();
for (final Symbol symbol : this.symbols)
{
if (symbol.getType() == Symbol.STT_FUNC)
{
final int idx = symbol.getSectionHeaderTableIndex();
if ((idx < Symbol.SHN_HIPROC) && (idx > Symbol.SHN_LOPROC))
{
final String name = symbol.toString();
if ((name != null) && (name.trim().length() > 0))
{
v.add(symbol);
}
}
else if ((idx >= 0) && (this.sections[idx].getType() != Section.SHT_NULL))
{
v.add(symbol);
}
}
}
return v.toArray(new Symbol[v.size()]);
}
/**
* @return
* @throws IOException
*/
public Symbol[] getLocalObjects() throws IOException
{
final List<Symbol> v = new ArrayList<Symbol>();
loadSymbols();
loadSections();
for (final Symbol symbol : this.symbols)
{
if (symbol.getType() == Symbol.STT_OBJECT)
{
final int idx = symbol.getSectionHeaderTableIndex();
if ((idx < Symbol.SHN_HIPROC) && (idx > Symbol.SHN_LOPROC))
{
final String name = symbol.toString();
if ((name != null) && (name.trim().length() > 0))
{
v.add(symbol);
}
}
else if ((idx >= 0) && (this.sections[idx].getType() != Section.SHT_NULL))
{
v.add(symbol);
}
}
}
return v.toArray(new Symbol[v.size()]);
}
/**
* @return
* @throws IOException
*/
public Dynamic[] getNeeded() throws IOException
{
final List<Dynamic> v = new ArrayList<Dynamic>();
loadDynamics();
for (final Dynamic dynamic : this.dynamics)
{
if (dynamic.getTag() == Dynamic.DT_NEEDED)
{
v.add(dynamic);
}
}
return v.toArray(new Dynamic[v.size()]);
}
/**
* @return
* @throws IOException
*/
public Sizes getSizes() throws IOException
{
long text, data, bss;
text = 0;
data = 0;
bss = 0;
loadSections();
for (final Section section : this.sections)
{
if (section.getType() != Section.SHT_NOBITS)
{
if (section.getFlags() == (Section.SHF_WRITE | Section.SHF_ALLOC))
{
data += section.getSize();
}
else if ((section.getFlags() & Section.SHF_ALLOC) != 0)
{
text += section.getSize();
}
}
else
{
if (section.getFlags() == (Section.SHF_WRITE | Section.SHF_ALLOC))
{
bss += section.getSize();
}
}
}
return new Sizes(text, data, bss);
}
/**
* @return
* @throws IOException
*/
public String getSoName() throws IOException
{
String soname = "";
loadDynamics();
for (final Dynamic dynamic : this.dynamics)
{
if (dynamic.getTag() == Dynamic.DT_SONAME)
{
soname = dynamic.toString();
}
}
return soname;
}
/**
* @return
* @throws IOException
*/
public Symbol[] getUndefined() throws IOException
{
final List<Symbol> v = new ArrayList<Symbol>();
loadSymbols();
for (final Symbol dynsym : this.dynsyms)
{
if (dynsym.getSectionHeaderTableIndex() == Symbol.SHN_UNDEF)
{
v.add(dynsym);
}
}
return v.toArray(new Symbol[v.size()]);
}
/**
* @throws IOException
*/
private void loadDynamics() throws IOException
{
if (this.dynamics == null)
{
this.dynamics = new Dynamic[0];
final Section dynSect = this.elf.getSectionByName(".dynamic");
if (dynSect != null)
{
this.dynamics = this.elf.getDynamicSections(dynSect);
}
}
}
/**
* @throws IOException
*/
private void loadSections() throws IOException
{
if (this.sections == null)
{
this.sections = this.elf.getSections();
}
}
/**
* @throws IOException
*/
private void loadSymbols() throws IOException
{
if (this.symbols == null)
{
this.elf.loadSymbols();
this.symbols = this.elf.getSymtabSymbols();
this.dynsyms = this.elf.getDynamicSymbols();
if (this.symbols.length <= 0)
{
this.symbols = this.dynsyms;
}
if (this.dynsyms.length <= 0)
{
this.dynsyms = this.symbols;
}
}
}
}
| 9,169 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
ElfHeader.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/elf/ElfHeader.java | /*******************************************************************************
* Copyright (c) 2011 - J.W. Janssen
*
* Copyright (c) 2000, 2008 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - Initial API and implementation
* J.W. Janssen - Clean up and made API more OO-oriented
*******************************************************************************/
package org.flashtool.binutils.elf;
import java.io.*;
/**
* Denotes the header of an ELF file.
*/
public class ElfHeader
{
// CONSTANTS
/* e_ident offsets */
/** Magic number: 0x7f */
private final static int EI_MAG0 = 0;
/** Magic number: 'E' */
private final static int EI_MAG1 = 1;
/** Magic number: 'L' */
private final static int EI_MAG2 = 2;
/** Magic number: 'F' */
private final static int EI_MAG3 = 3;
/** The file's class, or capacity. */
private final static int EI_CLASS = 4;
/** Data encoding */
private final static int EI_DATA = 5;
/** ELF header version number. */
@SuppressWarnings("unused")
private final static int EI_VERSION = 6;
/** the unused bytes in e_ident. These bytes are reserved and set to zero. */
@SuppressWarnings("unused")
private final static int EI_PAD = 7;
/** */
private final static int EI_NDENT = 16;
/* e_ident[EI_CLASS] */
private final static int ELFCLASSNONE = 0;
private final static int ELFCLASS32 = 1;
private final static int ELFCLASS64 = 2;
/* e_ident[EI_DATA] */
@SuppressWarnings("unused")
private final static int ELFDATANONE = 0;
private final static int ELFDATA2LSB = 1;
private final static int ELFDATA2MSB = 2;
/* values of e_type */
public static final int ET_NONE = 0;
public static final int ET_REL = 1;
public static final int ET_EXEC = 2;
public static final int ET_DYN = 3;
public static final int ET_CORE = 4;
public static final int ET_NUM = 5;
public static final int ET_LOOS = 0xfe00;
public static final int ET_HIOS = 0xfeff;
public static final int ET_LOPROC = 0xff00;
public static final int ET_HIPROC = 0xffff;
/* values of e_machine */
public static final int EM_NONE = 0;
public static final int EM_M32 = 1;
public static final int EM_SPARC = 2;
public static final int EM_386 = 3;
public static final int EM_68K = 4;
public static final int EM_88K = 5;
public static final int EM_486 = 6;
public static final int EM_860 = 7;
public static final int EM_MIPS = 8;
public static final int EM_MIPS_RS3_LE = 10;
public static final int EM_RS6000 = 11;
public static final int EM_PARISC = 15;
public static final int EM_nCUBE = 16;
public static final int EM_VPP550 = 17;
public static final int EM_SPARC32PLUS = 18;
public static final int EM_960 = 19;
public static final int EM_PPC = 20;
public static final int EM_PPC64 = 21;
public static final int EM_S390 = 22;
public static final int EM_V800 = 36; /* NEC V800 series */
public static final int EM_FR20 = 37; /* Fujitsu FR20 */
public static final int EM_RH32 = 38; /* TRW RH-32 */
public static final int EM_RCE = 39; /* Motorola RCE */
public static final int EM_ARM = 40;
public static final int EM_FAKE_ALPHA = 41; /* Digital Alpha */
public static final int EM_SH = 42;
public static final int EM_SPARCV9 = 43;
public static final int EM_TRICORE = 44;
public static final int EM_ARC = 45; /* Argonaut RISC Core */
public static final int EM_H8_300 = 46;
public static final int EM_H8_300H = 47;
public static final int EM_H8S = 48; /* Hitachi H8S */
public static final int EM_H8_500 = 49; /* Hitachi H8/500 */
public static final int EM_IA_64 = 50;
public static final int EM_MIPS_X = 51; /* Stanford MIPS-X */
public static final int EM_COLDFIRE = 52;
public static final int EM_68HC12 = 53; /* Motorola M68HC12 */
public static final int EM_MMA = 54; /* Fujitsu MMA Multimedia Accelerator */
public static final int EM_PCP = 55; /* Siemens PCP */
public static final int EM_NCPU = 56; /* Sony nCPU embeeded RISC */
public static final int EM_NDR1 = 57; /* Denso NDR1 microprocessor */
public static final int EM_STARCORE = 58;
public static final int EM_ME16 = 59; /* Toyota ME16 processor */
public static final int EM_ST100 = 60; /* STMicroelectronic ST100 processor */
public static final int EM_TINYJ = 61; /* Advanced Logic Corp. Tinyj emb.fam */
public static final int EM_X86_64 = 62;
public static final int EM_PDSP = 63; /* Sony DSP Processor */
public static final int EM_FX66 = 66; /* Siemens FX66 microcontroller */
public static final int EM_ST9PLUS = 67; /* STMicroelectronics ST9+ 8/16 mc */
public static final int EM_ST7 = 68; /* STmicroelectronics ST7 8 bit mc */
public static final int EM_68HC16 = 69; /* Motorola MC68HC16 microcontroller */
public static final int EM_68HC11 = 70; /* Motorola MC68HC11 microcontroller */
/* Freescale MC68HC08 Microcontroller */
public static final int EM_68HC08 = 71;
/* Motorola MC68HC05 microcontroller */
public static final int EM_68HC05 = 72;
public static final int EM_SVX = 73; /* Silicon Graphics SVx */
public static final int EM_ST19 = 74; /* STMicroelectronics ST19 8 bit mc */
public static final int EM_VAX = 75; /* Digital VAX */
/* Axis Communications 32-bit embedded processor */
public static final int EM_CRIS = 76;
/* Infineon Technologies 32-bit embedded processor */
public static final int EM_JAVELIN = 77;
public static final int EM_FIREPATH = 78; /* Element 14 64-bit DSP Processor */
public static final int EM_ZSP = 79; /* LSI Logic 16-bit DSP Processor */
/* Donald Knuth's educational 64-bit processor */
public static final int EM_MMIX = 80;
/* Harvard University machine-independent object files */
public static final int EM_HUANY = 81;
public static final int EM_PRISM = 82; /* SiTera Prism */
public static final int EM_AVR = 83;
/* Fujitsu FR30 */
public static final int EM_FR30 = 84;
public static final int EM_D10V = 85; /* Mitsubishi D10V */
public static final int EM_D30V = 86; /* Mitsubishi D30V */
public static final int EM_V850 = 87;
public static final int EM_M32R = 88;
public static final int EM_MN10300 = 89;
public static final int EM_MN10200 = 90;
public static final int EM_PJ = 91; /* picoJava */
/* OpenRISC 32-bit embedded processor */
public static final int EM_OPENRISC = 92;
public static final int EM_ARC_A5 = 93; /* ARC Cores Tangent-A5 */
public static final int EM_XTENSA = 94; /* Tensilica Xtensa Architecture */
public static final int EM_MSP430 = 105;
public static final int EM_BLACKFIN = 106;
public static final int EM_EXCESS = 111;
public static final int EM_NIOSII = 113;
public static final int EM_C166 = 116;
public static final int EM_M16C = 117;
/* Freescale RS08 embedded processor */
public static final int EM_RS08 = 132;
public static final int EM_MMDSP = 160;
public static final int EM_NIOS = 0xFEBB;
public static final int EM_CYGNUS_POWERPC = 0x9025;
public static final int EM_CYGNUS_M32R = 0x9041;
public static final int EM_CYGNUS_V850 = 0x9080;
public static final int EM_CYGNUS_MN10200 = 0xdead;
public static final int EM_CYGNUS_MN10300 = 0xbeef;
public static final int EM_CYGNUS_FR30 = 0x3330;
public static final int EM_XSTORMY16 = 0xad45;
public static final int EM_CYGNUS_FRV = 0x5441;
public static final int EM_IQ2000 = 0xFEBA;
public static final int EM_XILINX_MICROBLAZE = 0xbaab;
public static final int EM_SDMA = 0xcafe;
public static final int EM_CRADLE = 0x4d55;
// VARIABLES
private final byte e_ident[] = new byte[EI_NDENT];
private final int e_type;
private final int e_machine;
private final long e_version;
private final long e_entry;
private final long e_phoff;
private final long e_shoff;
private final long e_flags;
private final short e_ehsize;
private final short e_phentsize;
private final short e_phnum;
private final short e_shentsize;
private final short e_shnum;
private final short e_shstrndx;
// CONSTRUCTORS
/**
* Creates a new {@link ElfHeader} instance.
*
* @param bytes
* the binary header to convert to a header.
* @throws IOException
* in case the given bytes did not look like a valid ELF header.
*/
protected ElfHeader(final byte[] bytes) throws IOException
{
if (bytes.length <= this.e_ident.length)
{
throw new EOFException("Not an ELF-file!");
}
System.arraycopy(bytes, 0, this.e_ident, 0, this.e_ident.length);
if (!isElfHeader(this.e_ident))
{
throw new IOException("Not an ELF file!");
}
final boolean isle = (this.e_ident[ElfHeader.EI_DATA] == ElfHeader.ELFDATA2LSB);
int offset = this.e_ident.length;
this.e_type = makeShort(bytes, offset, isle);
offset += 2;
this.e_machine = makeShort(bytes, offset, isle);
offset += 2;
this.e_version = makeInt(bytes, offset, isle);
offset += 4;
switch (this.e_ident[ElfHeader.EI_CLASS])
{
case ElfHeader.ELFCLASS32:
{
final byte[] addrArray = new byte[Elf.ELF32_ADDR_SIZE];
System.arraycopy(bytes, offset, addrArray, 0, Elf.ELF32_ADDR_SIZE);
offset += Elf.ELF32_ADDR_SIZE;
this.e_entry = Elf.createAddr32(addrArray);
this.e_phoff = makeInt(bytes, offset, isle);
offset += Elf.ELF32_OFF_SIZE;
this.e_shoff = makeInt(bytes, offset, isle);
offset += Elf.ELF32_OFF_SIZE;
}
break;
case ElfHeader.ELFCLASS64:
{
final byte[] addrArray = new byte[Elf.ELF64_ADDR_SIZE];
System.arraycopy(bytes, offset, addrArray, 0, Elf.ELF64_ADDR_SIZE);
offset += Elf.ELF64_ADDR_SIZE;
this.e_entry = Elf.createAddr64(addrArray);
this.e_phoff = makeUnsignedLong(bytes, offset, isle);
offset += Elf.ELF64_OFF_SIZE;
this.e_shoff = makeUnsignedLong(bytes, offset, isle);
offset += Elf.ELF64_OFF_SIZE;
}
break;
case ElfHeader.ELFCLASSNONE:
default:
throw new IOException("Unknown ELF class " + this.e_ident[ElfHeader.EI_CLASS]);
}
this.e_flags = makeInt(bytes, offset, isle);
offset += 4;
this.e_ehsize = makeShort(bytes, offset, isle);
offset += 2;
this.e_phentsize = makeShort(bytes, offset, isle);
offset += 2;
this.e_phnum = makeShort(bytes, offset, isle);
offset += 2;
this.e_shentsize = makeShort(bytes, offset, isle);
offset += 2;
this.e_shnum = makeShort(bytes, offset, isle);
offset += 2;
this.e_shstrndx = makeShort(bytes, offset, isle);
offset += 2;
}
/**
* @param efile
* @throws IOException
*/
protected ElfHeader(final ERandomAccessFile efile) throws IOException
{
efile.seek(0);
efile.readFully(this.e_ident);
if (!isElfHeader(this.e_ident))
{
throw new IOException("Not an ELF file!");
}
efile.setEndiannes(this.e_ident[ElfHeader.EI_DATA] == ElfHeader.ELFDATA2LSB);
this.e_type = efile.readShortE();
this.e_machine = efile.readShortE();
this.e_version = efile.readIntE();
switch (this.e_ident[ElfHeader.EI_CLASS])
{
case ElfHeader.ELFCLASS32:
{
final byte[] addrArray = new byte[Elf.ELF32_ADDR_SIZE];
efile.readFullyE(addrArray);
this.e_entry = Elf.createAddr32(addrArray);
this.e_phoff = efile.readIntE();
this.e_shoff = efile.readIntE();
}
break;
case ElfHeader.ELFCLASS64:
{
final byte[] addrArray = new byte[Elf.ELF64_ADDR_SIZE];
efile.readFullyE(addrArray);
this.e_entry = Elf.createAddr64(addrArray);
this.e_phoff = Elf.readUnsignedLong(efile);
this.e_shoff = Elf.readUnsignedLong(efile);
}
break;
case ElfHeader.ELFCLASSNONE:
default:
throw new IOException("Unknown ELF class " + this.e_ident[ElfHeader.EI_CLASS]);
}
this.e_flags = efile.readIntE();
this.e_ehsize = efile.readShortE();
this.e_phentsize = efile.readShortE();
this.e_phnum = efile.readShortE();
this.e_shentsize = efile.readShortE();
this.e_shnum = efile.readShortE();
this.e_shstrndx = efile.readShortE();
}
// METHODS
/**
* Helper method to determine whether the first few bytes of the given array
* correspond to the "magic" string of an ELF object.
*
* @param e_ident
* the byte array to test, cannot be <code>null</code>.
* @return <code>true</code> if the first few bytes resemble the ELF "magic"
* string, <code>false</code> otherwise.
*/
static boolean isElfHeader(final byte[] e_ident)
{
if ((e_ident.length < 4) || (e_ident[ElfHeader.EI_MAG0] != 0x7f) || (e_ident[ElfHeader.EI_MAG1] != 'E')
|| (e_ident[ElfHeader.EI_MAG2] != 'L') || (e_ident[ElfHeader.EI_MAG3] != 'F'))
{
return false;
}
return true;
}
/**
* Returns the entry point (Elf32_Addr).
*
* @return the entry point address, >= 0.
*/
public long getEntryPoint()
{
return this.e_entry;
}
/**
* Returns the processor flags (Elf32_Word).
*
* @return the processor flags.
*/
public long getFlags()
{
return this.e_flags;
}
/**
* Returns the machine type, or required architecture for an individual file.
*
* @return the machine type.
*/
public int getMachineType()
{
return this.e_machine & 0xFFFF;
}
/**
* Returns the number of entries in the program header table. Thus the
* product of {@link #getProgramHeaderEntrySize()} and
* {@link #getProgramHeaderEntryCount()} gives the table's size in bytes. If a
* file has no program header table, this method returns zero.
*
* @return the number of entries in the program header table, >= 0.
*/
public int getProgramHeaderEntryCount()
{
return this.e_phnum & 0xffff;
}
/**
* Returns the size in bytes of one entry in the file's program header table;
* all entries are the same size.
*
* @return the program header entry size.
*/
public int getProgramHeaderEntrySize()
{
return this.e_phentsize & 0xffff;
}
/**
* Returns the program header table's file offset in bytes. If the file has no
* program header table, this method returns zero.
*
* @return the program header table file offset (in bytes), >= 0.
*/
public long getProgramHeaderFileOffset()
{
return this.e_phoff;
}
/**
* Returns the raw elf header.
*
* @return the raw header, never <code>null</code>.
*/
public byte[] getRawHeader()
{
return this.e_ident;
}
/**
* Returns the number of entries in the section header table. Thus the product
* of e_shentsize and e_shnum gives the section header table's size in bytes.
* If a file has no section header table, e_shnum holds the value zero.
*
* @return the e_shnum
*/
public int getSectionHeaderEntryCount()
{
return this.e_shnum & 0xffff;
}
/**
* Returns a section header's size in bytes. A section header is one entry
* in the section header table; all entries are the same size.
*
* @return the section header's size (in bytes), >= 0.
*/
public int getSectionHeaderEntrySize()
{
return this.e_shentsize & 0xffff;
}
/**
* Returns the section header table's file offset in bytes. If the file has no
* section header table, this member holds zero.
*
* @return the section header table's file offset (in bytes), >= 0.
*/
public long getSectionHeaderFileOffset()
{
return this.e_shoff;
}
/**
* Returns the size of the header.
*
* @return a header size, >= 0.
*/
public short getSize()
{
return this.e_ehsize;
}
/**
* Returns the section header table index of the entry associated with the
* section name string table. If the file has no section name string table,
* this member holds the value SHN_UNDEF. See "Sections" and "String Table"
* below for more information.
*
* @return the e_shstrndx
*/
public int getStringTableSectionIndex()
{
return this.e_shstrndx & 0xFFFF;
}
/**
* Returns the object file type.
*
* @return the file type, >= 0.
*/
public int getType()
{
return this.e_type;
}
/**
* Returns the object file version.
*
* @return the file version.
*/
public long getVersion()
{
return this.e_version;
}
/**
* Returns whether or not the program header table contains entries.
*
* @return <code>true</code> if there are entries in the program header table,
* <code>false</code> otherwise.
* @see #getProgramHeaderEntryCount()
*/
public boolean hasProgramHeaderTable()
{
return this.e_phoff > 0;
}
/**
* Returns whether or not the program header table contains entries.
*
* @return <code>true</code> if there are entries in the program header table,
* <code>false</code> otherwise.
* @see #getProgramHeaderEntryCount()
*/
public boolean hasSectionHeaderTable()
{
return this.e_shoff > 0;
}
/**
* Returns whether this ELF-file represents a 32-bit file.
*
* @return <code>true</code> if the ELF-file is for 32-bit platforms,
* <code>false</code> otherwise.
*/
public boolean is32bit()
{
return this.e_ident[EI_CLASS] == ELFCLASS32;
}
/**
* Returns whether this ELF-file represents a 32-bit file.
*
* @return <code>true</code> if the ELF-file is for 32-bit platforms,
* <code>false</code> otherwise.
*/
public boolean is64bit()
{
return this.e_ident[EI_CLASS] == ELFCLASS64;
}
/**
* Returns whether the ELF file's data is in big endian format or not.
*
* @return <code>true</code> if the ELF's data is expected to be big
* endian, <code>false</code> if it is expected to be little endian or
* unknown.
*/
public boolean isBigEndian()
{
return this.e_ident[EI_DATA] == ELFDATA2MSB;
}
/**
* Returns whether the ELF file's data is in little endian format or not.
*
* @return <code>true</code> if the ELF's data is expected to be little
* endian, <code>false</code> if it is expected to be big endian or
* unknown.
*/
public boolean isLittleEndian()
{
return this.e_ident[EI_DATA] == ELFDATA2LSB;
}
/**
* @param val
* @param offset
* @param isle
* @return
* @throws IOException
*/
private final long makeInt(final byte[] val, final int offset, final boolean isle) throws IOException
{
if (val.length < (offset + 4))
{
throw new IOException();
}
if (isle)
{
return ((val[offset + 3] << 24) + (val[offset + 2] << 16) + (val[offset + 1] << 8) + val[offset + 0]);
}
return ((val[offset + 0] << 24) + (val[offset + 1] << 16) + (val[offset + 2] << 8) + val[offset + 3]);
}
/**
* @param val
* @param offset
* @param isle
* @return
* @throws IOException
*/
private final long makeLong(final byte[] val, final int offset, final boolean isle) throws IOException
{
long result = 0;
int shift = 0;
if (isle)
{
for (int i = 7; i >= 0; i--)
{
shift = i * 8;
result += (((long) val[offset + i]) << shift) & (0xffL << shift);
}
}
else
{
for (int i = 0; i <= 7; i++)
{
shift = (7 - i) * 8;
result += (((long) val[offset + i]) << shift) & (0xffL << shift);
}
}
return result;
}
/**
* @param val
* @param offset
* @param isle
* @return
* @throws IOException
*/
private final short makeShort(final byte[] val, final int offset, final boolean isle) throws IOException
{
if (val.length < (offset + 2))
{
throw new IOException();
}
if (isle)
{
return (short) ((val[offset + 1] << 8) + val[offset + 0]);
}
return (short) ((val[offset + 0] << 8) + val[offset + 1]);
}
/**
* @param val
* @param offset
* @param isle
* @return
* @throws IOException
*/
private final long makeUnsignedLong(final byte[] val, final int offset, final boolean isle) throws IOException
{
final long result = makeLong(val, offset, isle);
if (result < 0)
{
throw new IOException("Maximal file offset is " + Long.toHexString(Long.MAX_VALUE) + " given offset is "
+ Long.toHexString(result));
}
return result;
}
}
| 20,707 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
Attribute.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/elf/Attribute.java | /*******************************************************************************
* Copyright (c) 2011 - J.W. Janssen
*
* Copyright (c) 2000, 2008 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - Initial API and implementation
* J.W. Janssen - Clean up and made API more OO-oriented
*******************************************************************************/
package org.flashtool.binutils.elf;
/**
* Denotes some general attributes of the ELF file.
*/
public class Attribute
{
// CONSTANTS
public static final int ELF_TYPE_EXE = 1;
public static final int ELF_TYPE_SHLIB = 2;
public static final int ELF_TYPE_OBJ = 3;
public static final int ELF_TYPE_CORE = 4;
public static final int DEBUG_TYPE_NONE = 0;
public static final int DEBUG_TYPE_STABS = 1;
public static final int DEBUG_TYPE_DWARF = 2;
// VARIABLES
private String cpu;
private int type;
private int debugType;
private boolean isle;
private int width; // 32 or 64
// CONSTRUCTORS
/**
* Creates a new Attribute instance.
*/
private Attribute()
{
super();
}
// METHODS
/**
* Factory method for creating an {@link Attribute} instance.
*
* @param aHeader
* the ELF-header to create the attribute for;
* @param aSections
* the sections of the ELF-file.
* @return a new {@link Attribute} instance, never <code>null</code>.
*/
static Attribute create(final ElfHeader aHeader, final Section[] aSections)
{
final Attribute attrib = new Attribute();
switch (aHeader.getType())
{
case ElfHeader.ET_CORE:
attrib.type = Attribute.ELF_TYPE_CORE;
break;
case ElfHeader.ET_EXEC:
attrib.type = Attribute.ELF_TYPE_EXE;
break;
case ElfHeader.ET_REL:
attrib.type = Attribute.ELF_TYPE_OBJ;
break;
case ElfHeader.ET_DYN:
attrib.type = Attribute.ELF_TYPE_SHLIB;
break;
}
switch (aHeader.getMachineType())
{
case ElfHeader.EM_386:
case ElfHeader.EM_486:
attrib.cpu = "x86";
break;
case ElfHeader.EM_68K:
attrib.cpu = "m68k";
break;
case ElfHeader.EM_PPC:
case ElfHeader.EM_CYGNUS_POWERPC:
case ElfHeader.EM_RS6000:
attrib.cpu = "ppc";
break;
case ElfHeader.EM_PPC64:
attrib.cpu = "ppc64";
break;
case ElfHeader.EM_SH:
attrib.cpu = "sh";
break;
case ElfHeader.EM_ARM:
attrib.cpu = "arm";
break;
case ElfHeader.EM_MIPS_RS3_LE:
case ElfHeader.EM_MIPS:
attrib.cpu = "mips";
break;
case ElfHeader.EM_SPARC32PLUS:
case ElfHeader.EM_SPARC:
case ElfHeader.EM_SPARCV9:
attrib.cpu = "sparc";
break;
case ElfHeader.EM_H8_300:
case ElfHeader.EM_H8_300H:
attrib.cpu = "h8300";
break;
case ElfHeader.EM_V850:
case ElfHeader.EM_CYGNUS_V850:
attrib.cpu = "v850";
break;
case ElfHeader.EM_MN10300:
case ElfHeader.EM_CYGNUS_MN10300:
attrib.cpu = "mn10300";
break;
case ElfHeader.EM_MN10200:
case ElfHeader.EM_CYGNUS_MN10200:
attrib.cpu = "mn10200";
break;
case ElfHeader.EM_M32R:
attrib.cpu = "m32r";
break;
case ElfHeader.EM_FR30:
case ElfHeader.EM_CYGNUS_FR30:
attrib.cpu = "fr30";
break;
case ElfHeader.EM_XSTORMY16:
attrib.cpu = "xstormy16";
break;
case ElfHeader.EM_CYGNUS_FRV:
attrib.cpu = "frv";
break;
case ElfHeader.EM_IQ2000:
attrib.cpu = "iq2000";
break;
case ElfHeader.EM_EXCESS:
attrib.cpu = "excess";
break;
case ElfHeader.EM_NIOSII:
attrib.cpu = "alteranios2";
break;
case ElfHeader.EM_NIOS:
attrib.cpu = "alteranios";
break;
case ElfHeader.EM_IA_64:
attrib.cpu = "ia64";
break;
case ElfHeader.EM_COLDFIRE:
attrib.cpu = "coldfire";
break;
case ElfHeader.EM_AVR:
attrib.cpu = "avr";
break;
case ElfHeader.EM_MSP430:
attrib.cpu = "msp430";
break;
case ElfHeader.EM_XTENSA:
attrib.cpu = "xtensa";
break;
case ElfHeader.EM_ST100:
attrib.cpu = "st100";
break;
case ElfHeader.EM_X86_64:
attrib.cpu = "x86_64";
break;
case ElfHeader.EM_XILINX_MICROBLAZE:
attrib.cpu = "microblaze";
break;
case ElfHeader.EM_C166:
attrib.cpu = "c166";
break;
case ElfHeader.EM_TRICORE:
attrib.cpu = "TriCore";
break;
case ElfHeader.EM_M16C:
attrib.cpu = "M16C";
break;
case ElfHeader.EM_STARCORE:
attrib.cpu = "StarCore";
break;
case ElfHeader.EM_BLACKFIN:
attrib.cpu = "bfin";
break;
case ElfHeader.EM_SDMA:
attrib.cpu = "sdma";
break;
case ElfHeader.EM_CRADLE:
attrib.cpu = "cradle";
break;
case ElfHeader.EM_MMDSP:
attrib.cpu = "mmdsp";
break;
case ElfHeader.EM_68HC08:
attrib.cpu = "hc08";
break;
case ElfHeader.EM_RS08:
attrib.cpu = "rs08";
break;
case ElfHeader.EM_NONE:
attrib.cpu = "none";
default:
attrib.cpu = String.format("Unknown (0x%x)", aHeader.getMachineType());
}
attrib.isle = aHeader.isLittleEndian();
attrib.width = aHeader.is32bit() ? 32 : aHeader.is64bit() ? 64 : -1;
if (aSections != null)
{
for (final Section element : aSections)
{
final String s = element.toString();
if (s.startsWith(".debug"))
{
attrib.debugType = Attribute.DEBUG_TYPE_DWARF;
break;
}
else if (s.equals(".stab"))
{
attrib.debugType = Attribute.DEBUG_TYPE_STABS;
break;
}
}
}
return attrib;
}
/**
* @return
*/
public String getCPU()
{
return this.cpu;
}
/**
* @return
*/
public int getDebugType()
{
return this.debugType;
}
/**
* @return
*/
public int getType()
{
return this.type;
}
/**
* @return
*/
public int getWidth()
{
return this.width;
}
/**
* @return
*/
public boolean hasDebug()
{
return this.debugType != DEBUG_TYPE_NONE;
}
/**
* @return
*/
public boolean isLittleEndian()
{
return this.isle;
}
}
| 6,822 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
SymbolComparator.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/elf/SymbolComparator.java | /*******************************************************************************
* Copyright (c) 2011 - J.W. Janssen
*
* Copyright (c) 2000, 2008 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - Initial API and implementation
* J.W. Janssen - Clean up and made API more OO-oriented
*******************************************************************************/
package org.flashtool.binutils.elf;
import java.util.*;
/**
* We have to implement a separate compararator since when we do the binary
* search down below we are using a Long and a Symbol object and the Long
* doesn't know how to compare against a Symbol so if we compare Symbol vs Long
* it is ok, but not if we do Long vs Symbol.
*/
class SymbolComparator implements Comparator<Object>
{
// METHODS
/**
* {@inheritDoc}
*/
@Override
public int compare(Object o1, Object o2)
{
Long val1, val2;
if (o1 instanceof Long)
{
val1 = (Long) o1;
}
else if (o1 instanceof Symbol)
{
val1 = ((Symbol) o1).getValue();
}
else
{
return -1;
}
if (o2 instanceof Long)
{
val2 = (Long) o2;
}
else if (o2 instanceof Symbol)
{
val2 = ((Symbol) o2).getValue();
}
else
{
return -1;
}
return val1.compareTo(val2);
}
}
| 1,594 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
Section.java | /FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/binutils/elf/Section.java | /*******************************************************************************
* Copyright (c) 2011 - J.W. Janssen
*
* Copyright (c) 2000, 2008 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - Initial API and implementation
* J.W. Janssen - Clean up and made API more OO-oriented
*******************************************************************************/
package org.flashtool.binutils.elf;
import java.io.*;
import java.util.*;
/**
* An object file's section header table lets one locate all the file's
* sections. The section header table is an array of {@link Section}s. A section
* header table index (see {@link #getHeaderTableIndexLink()}) is a subscript
* into this array.
*/
public class Section
{
// CONSTANTS
/* sh_type */
public final static int SHT_NULL = 0;
public final static int SHT_PROGBITS = 1;
public final static int SHT_SYMTAB = 2;
public final static int SHT_STRTAB = 3;
public final static int SHT_RELA = 4;
public final static int SHT_HASH = 5;
public final static int SHT_DYNAMIC = 6;
public final static int SHT_NOTE = 7;
public final static int SHT_NOBITS = 8;
public final static int SHT_REL = 9;
public final static int SHT_SHLIB = 10;
public final static int SHT_DYNSYM = 11;
public final static int SHT_LOPROC = 0x70000000;
/* sh_flags */
public final static int SHF_WRITE = 1;
public final static int SHF_ALLOC = 2;
public final static int SHF_EXECINTR = 4;
// VARIABLES
private int sh_name;
private int sh_type;
private long sh_flags;
private long sh_addr;
private long sh_offset;
private long sh_size;
private long sh_link;
private long sh_info;
private long sh_addralign;
private long sh_entsize;
private final Elf elf;
private String name;
// CONSTRUCTORS
/**
* Creates a new Section instance.
*
* @param elf
*/
private Section(Elf elf)
{
this.elf = elf;
}
// METHODS
/**
* @param aHeader
* @param aFile
* @return
*/
static Section[] create(Elf aElf, ElfHeader aHeader, ERandomAccessFile aFile) throws IOException
{
if (!aHeader.hasSectionHeaderTable())
{
return new Section[0];
}
final int length = aHeader.getSectionHeaderEntryCount();
final int shentsize = aHeader.getSectionHeaderEntrySize();
final Section[] sections = new Section[length];
long offset = aHeader.getSectionHeaderFileOffset();
for (int i = 0; i < length; i++, offset += shentsize)
{
aFile.seek(offset);
sections[i] = createSection(aElf, aHeader, aFile);
}
return sections;
}
/**
* @param aElf
* @param aHeader
* @param aFile
* @return
* @throws IOException
*/
private static Section createSection(Elf aElf, ElfHeader aHeader, ERandomAccessFile aFile) throws IOException
{
Section section = new Section(aElf);
section.sh_name = aFile.readIntE();
section.sh_type = aFile.readIntE();
if (aHeader.is32bit())
{
final byte[] addrArray = new byte[Elf.ELF32_ADDR_SIZE];
section.sh_flags = aFile.readIntE();
aFile.readFullyE(addrArray);
section.sh_addr = Elf.createAddr32(addrArray);
section.sh_offset = aFile.readIntE();
section.sh_size = aFile.readIntE();
}
else if (aHeader.is64bit())
{
final byte[] addrArray = new byte[Elf.ELF64_ADDR_SIZE];
section.sh_flags = aFile.readLongE();
aFile.readFullyE(addrArray);
section.sh_addr = Elf.createAddr64(addrArray);
section.sh_offset = Elf.readUnsignedLong(aFile);
section.sh_size = Elf.readUnsignedLong(aFile);
}
else
{
throw new IOException("Unknown ELF class!");
}
section.sh_link = aFile.readIntE();
section.sh_info = aFile.readIntE();
if (aHeader.is32bit())
{
section.sh_addralign = aFile.readIntE();
section.sh_entsize = aFile.readIntE();
}
else if (aHeader.is64bit())
{
section.sh_addralign = aFile.readLongE();
section.sh_entsize = Elf.readUnsignedLong(aFile);
}
else
{
throw new IOException("Unknown ELF class!");
}
return section;
}
/**
* Returns whether this section holds a table of fixed-size entries.
*
* @return <code>true</code> if this section holds a table, <code>false</code>
* otherwise.
*/
public boolean containsTable()
{
return this.sh_entsize != 0;
}
/**
* If the section will appear in the memory image of a process, this method
* returns the address at which the section's first byte should reside.
* Otherwise, the member contains 0.
*
* @return the address in the memory image, >= 0.
*/
public long getAddress()
{
return this.sh_addr;
}
/**
* Some sections have address alignment constraints. For example, if a section
* holds a double word, the system must ensure double word alignment for the
* entire section. That is, the value of sh_addr must be congruent to 0,
* modulo the value of sh_addralign. Currently, only 0 and positive integral
* powers of two are allowed. Values 0 and 1 mean the section has no alignment
* constraints.
*
* @return the address alignment constraints, >= 0.
*/
public long getAddressAlignment()
{
return this.sh_addralign;
}
/**
* @return
*/
public Elf getElf()
{
return this.elf;
}
/**
* Returns the byte offset from the beginning of the file to the first byte in
* the section. One section type, SHT_NOBITS, occupies no space in the file,
* and its sh_offset member locates the conceptual placement in the file.
*
* @return the file offset to this section (in bytes).
*/
public long getFileOffset()
{
return this.sh_offset;
}
/**
* Returns 1-bit flags that describe miscellaneous attributes.
*
* @return the flags, >= 0.
*/
public long getFlags()
{
return this.sh_flags;
}
/**
* Returns a section header table index link, whose interpretation depends on
* the section type.
*
* @return the index link, >= 0.
*/
public long getHeaderTableIndexLink()
{
return this.sh_link;
}
/**
* Returns the extra information, whose interpretation depends on the section
* type.
*
* @return the extra information.
*/
public long getInfo()
{
return this.sh_info;
}
/**
* Returns the name of this section.
*
* @return a name, never <code>null</code>.
*/
public String getName()
{
if (this.name == null)
{
try
{
final byte[] stringTable = this.elf.getStringTable();
int length = 0;
int offset = getNameIndex();
if (offset > stringTable.length)
{
this.name = "";
}
else
{
while (stringTable[offset + length] != 0)
{
length++;
}
this.name = new String(stringTable, offset, length);
}
}
catch (IOException exception)
{
this.name = "";
}
}
return this.name;
}
/**
* Returns the name of the section. Its value is an index into the section
* header string table section, giving the location of a null-terminated
* string.
*
* @return the index of this section's name in the string table, >= 0.
*/
public int getNameIndex()
{
return this.sh_name;
}
/**
* Some sections hold a table of fixed-size entries, such as a symbol table.
* For such a section, this member gives the size in bytes of each entry. The
* member contains 0 if the section does not hold a table of fixed-size
* entries.
*
* @return the sh_entsize
*/
public long getSectionTableEntrySize()
{
return this.sh_entsize;
}
/**
* Returns the section's size in bytes. Unless the section type is SHT_NOBITS,
* the section occupies sh_size bytes in the file. A section of type
* SHT_NOBITS may have a non-zero size, but it occupies no space in the file.
*
* @return the size (in bytes), >= 0.
*/
public long getSize()
{
return this.sh_size;
}
/**
* If this section contains a table, this method returns the number of entries
* in this table.
*
* @return a table entry count, >= 1.
*/
public int getTableEntryCount()
{
if (!containsTable())
{
return 1;
}
return (int) (getSize() / getSectionTableEntrySize());
}
/**
* Returns the category denoting the section's contents and semantics.
*
* @return the section type value.
*/
public int getType()
{
return this.sh_type;
}
/**
* Loads the symbols for this section.
*
* @param aHeader
* the ELF header to use;
* @param aFile
* the ELF-file to read the symbols from.
* @return an array of symbols, never <code>null</code>.
* @throws IOException
* in case of I/O problems.
*/
public Symbol[] loadSymbols(ElfHeader aHeader, ERandomAccessFile aFile) throws IOException
{
int numSyms = 1;
if (containsTable())
{
numSyms = getTableEntryCount();
}
final ArrayList<Symbol> symList = new ArrayList<Symbol>(numSyms);
long entsize = getSectionTableEntrySize();
long offset = getFileOffset();
for (int c = 0; c < numSyms; offset += entsize, c++)
{
aFile.seek(offset);
Symbol symbol = Symbol.create(aHeader, this, aFile);
if (symbol.getInfo() == 0)
{
continue;
}
symList.add(symbol);
}
final Symbol[] results = symList.toArray(new Symbol[symList.size()]);
Arrays.sort(results);
return results;
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
return getName();
}
/**
* @param aIndex
* @return
*/
final String getStringByIndex(int aIndex)
{
try
{
final Section sections[] = this.elf.getSections();
final Section symstr = sections[(int) this.sh_link];
return this.elf.getStringFromSection(symstr, aIndex);
}
catch (IOException exception)
{
return "";
}
}
}
| 10,368 | Java | .java | Androxyde/Flashtool | 468 | 244 | 165 | 2014-04-17T19:54:33Z | 2024-03-12T15:17:26Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.