language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResBagValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.ResResource; import brut.androlib.res.xml.ResValuesXmlSerializable; import brut.util.Duo; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; public class ResBagValue extends ResValue implements ResValuesXmlSerializable { protected final ResReferenceValue mParent; public ResBagValue(ResReferenceValue parent) { this.mParent = parent; } @Override public void serializeToResValuesXml(XmlSerializer serializer, ResResource res) throws IOException, AndrolibException { String type = res.getResSpec().getType().getName(); if ("style".equals(type)) { new ResStyleValue(mParent, new Duo[0], null) .serializeToResValuesXml(serializer, res); return; } if ("array".equals(type)) { new ResArrayValue(mParent, new Duo[0]).serializeToResValuesXml( serializer, res); return; } if ("plurals".equals(type)) { new ResPluralsValue(mParent, new Duo[0]).serializeToResValuesXml( serializer, res); return; } serializer.startTag(null, "item"); serializer.attribute(null, "type", type); serializer.attribute(null, "name", res.getResSpec().getName()); serializer.endTag(null, "item"); } public ResReferenceValue getParent() { return mParent; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResBoolValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; public class ResBoolValue extends ResScalarValue { private final boolean mValue; public ResBoolValue(boolean value, int rawIntValue, String rawValue) { super("bool", rawIntValue, rawValue); this.mValue = value; } public boolean getValue() { return mValue; } @Override protected String encodeAsResXml() { return mValue ? "true" : "false"; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResColorValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; public class ResColorValue extends ResIntValue { public ResColorValue(int value, String rawValue) { super(value, rawValue, "color"); } @Override protected String encodeAsResXml() { return String.format("#%08x", mValue); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResDimenValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import android.util.TypedValue; import brut.androlib.exceptions.AndrolibException; public class ResDimenValue extends ResIntValue { public ResDimenValue(int value, String rawValue) { super(value, rawValue, "dimen"); } @Override protected String encodeAsResXml() throws AndrolibException { return TypedValue.coerceToString(TypedValue.TYPE_DIMENSION, mValue); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResEmptyValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import brut.androlib.exceptions.AndrolibException; public class ResEmptyValue extends ResScalarValue { protected final int mValue; protected int type; public ResEmptyValue(int value, String rawValue, int type) { this(value, rawValue, "integer"); this.type = type; } public ResEmptyValue(int value, String rawValue, String type) { super(type, value, rawValue); if (value != 1) throw new UnsupportedOperationException(); this.mValue = value; } public int getValue() { return mValue; } @Override protected String encodeAsResXml() throws AndrolibException { return "@empty"; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResEnumAttr.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.ResResSpec; import brut.androlib.res.data.ResResource; import brut.util.Duo; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class ResEnumAttr extends ResAttr { ResEnumAttr(ResReferenceValue parent, int type, Integer min, Integer max, Boolean l10n, Duo<ResReferenceValue, ResIntValue>[] items) { super(parent, type, min, max, l10n); mItems = items; } @Override public String convertToResXmlFormat(ResScalarValue value) throws AndrolibException { if (value instanceof ResIntValue) { String ret = decodeValue(((ResIntValue) value).getValue()); if (ret != null) { return ret; } } return super.convertToResXmlFormat(value); } @Override protected void serializeBody(XmlSerializer serializer, ResResource res) throws AndrolibException, IOException { for (Duo<ResReferenceValue, ResIntValue> duo : mItems) { int intVal = duo.m2.getValue(); ResResSpec m1Referent = duo.m1.getReferent(); serializer.startTag(null, "enum"); serializer.attribute(null, "name", m1Referent != null ? m1Referent.getName() : "@null" ); serializer.attribute(null, "value", String.valueOf(intVal)); serializer.endTag(null, "enum"); } } private String decodeValue(int value) throws AndrolibException { String value2 = mItemsCache.get(value); if (value2 == null) { ResReferenceValue ref = null; for (Duo<ResReferenceValue, ResIntValue> duo : mItems) { if (duo.m2.getValue() == value) { ref = duo.m1; break; } } if (ref != null && !ref.referentIsNull()) { value2 = ref.getReferent().getName(); mItemsCache.put(value, value2); } } return value2; } private final Duo<ResReferenceValue, ResIntValue>[] mItems; private final Map<Integer, String> mItemsCache = new HashMap<>(); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResFileValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import brut.androlib.exceptions.AndrolibException; public class ResFileValue extends ResIntBasedValue { private final String mPath; public ResFileValue(String path, int rawIntValue) { super(rawIntValue); this.mPath = path; } public String getStrippedPath() throws AndrolibException { if (mPath.startsWith("res/")) { return mPath.substring(4); } if (mPath.startsWith("r/") || mPath.startsWith("R/")) { return mPath.substring(2); } throw new AndrolibException("File path does not start with \"res/\" or \"r/\": " + mPath); } @Override public String toString() { return mPath; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResFlagsAttr.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.ResResource; import brut.util.Duo; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; import java.util.Arrays; public class ResFlagsAttr extends ResAttr { ResFlagsAttr(ResReferenceValue parent, int type, Integer min, Integer max, Boolean l10n, Duo<ResReferenceValue, ResIntValue>[] items) { super(parent, type, min, max, l10n); mItems = new FlagItem[items.length]; for (int i = 0; i < items.length; i++) { mItems[i] = new FlagItem(items[i].m1, items[i].m2.getValue()); } } @Override public String convertToResXmlFormat(ResScalarValue value) throws AndrolibException { if(value instanceof ResReferenceValue) { return value.encodeAsResXml(); } if (!(value instanceof ResIntValue)) { return super.convertToResXmlFormat(value); } loadFlags(); int intVal = ((ResIntValue) value).getValue(); if (intVal == 0) { return renderFlags(mZeroFlags); } FlagItem[] flagItems = new FlagItem[mFlags.length]; int[] flags = new int[mFlags.length]; int flagsCount = 0; for (FlagItem flagItem : mFlags) { int flag = flagItem.flag; if ((intVal & flag) != flag) { continue; } if (!isSubpartOf(flag, flags)) { flags[flagsCount] = flag; flagItems[flagsCount++] = flagItem; } } return renderFlags(Arrays.copyOf(flagItems, flagsCount)); } @Override protected void serializeBody(XmlSerializer serializer, ResResource res) throws AndrolibException, IOException { for (FlagItem item : mItems) { serializer.startTag(null, "flag"); serializer.attribute(null, "name", item.getValue()); serializer.attribute(null, "value", String.format("0x%08x", item.flag)); serializer.endTag(null, "flag"); } } private boolean isSubpartOf(int flag, int[] flags) { for (int j : flags) { if ((j & flag) == flag) { return true; } } return false; } private String renderFlags(FlagItem[] flags) throws AndrolibException { StringBuilder ret = new StringBuilder(); for (FlagItem flag : flags) { ret.append("|").append(flag.getValue()); } if (ret.length() == 0) { return ret.toString(); } return ret.substring(1); } private void loadFlags() { if (mFlags != null) { return; } FlagItem[] zeroFlags = new FlagItem[mItems.length]; int zeroFlagsCount = 0; FlagItem[] flags = new FlagItem[mItems.length]; int flagsCount = 0; for (FlagItem item : mItems) { if (item.flag == 0) { zeroFlags[zeroFlagsCount++] = item; } else { flags[flagsCount++] = item; } } mZeroFlags = Arrays.copyOf(zeroFlags, zeroFlagsCount); mFlags = Arrays.copyOf(flags, flagsCount); Arrays.sort(mFlags, (o1, o2) -> Integer.compare(Integer.bitCount(o2.flag), Integer.bitCount(o1.flag))); } private final FlagItem[] mItems; private FlagItem[] mZeroFlags; private FlagItem[] mFlags; private static class FlagItem { public final ResReferenceValue ref; public final int flag; public String value; public FlagItem(ResReferenceValue ref, int flag) { this.ref = ref; this.flag = flag; } public String getValue() throws AndrolibException { if (value == null) { if (ref.referentIsNull()) { return "@null"; } value = ref.getReferent().getName(); } return value; } } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResFloatValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; public class ResFloatValue extends ResScalarValue { private final float mValue; public ResFloatValue(float value, int rawIntValue, String rawValue) { super("float", rawIntValue, rawValue); this.mValue = value; } public float getValue() { return mValue; } @Override protected String encodeAsResXml() { return String.valueOf(mValue); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResFractionValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import android.util.TypedValue; import brut.androlib.exceptions.AndrolibException; public class ResFractionValue extends ResIntValue { public ResFractionValue(int value, String rawValue) { super(value, rawValue, "fraction"); } @Override protected String encodeAsResXml() throws AndrolibException { return TypedValue.coerceToString(TypedValue.TYPE_FRACTION, mValue); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResIdValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import brut.androlib.res.data.ResResource; import brut.androlib.res.xml.ResValuesXmlSerializable; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; public class ResIdValue extends ResValue implements ResValuesXmlSerializable { @Override public void serializeToResValuesXml(XmlSerializer serializer, ResResource res) throws IOException { serializer.startTag(null, "item"); serializer.attribute(null, "type", res.getResSpec().getType().getName()); serializer.attribute(null, "name", res.getResSpec().getName()); serializer.endTag(null, "item"); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResIntBasedValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; public class ResIntBasedValue extends ResValue { private final int mRawIntValue; protected ResIntBasedValue(int rawIntValue) { mRawIntValue = rawIntValue; } public int getRawIntValue() { return mRawIntValue; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResIntValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import android.util.TypedValue; import brut.androlib.exceptions.AndrolibException; public class ResIntValue extends ResScalarValue { protected final int mValue; private int type; public ResIntValue(int value, String rawValue, int type) { this(value, rawValue, "integer"); this.type = type; } public ResIntValue(int value, String rawValue, String type) { super(type, value, rawValue); this.mValue = value; } public int getValue() { return mValue; } @Override protected String encodeAsResXml() throws AndrolibException { return TypedValue.coerceToString(type, mValue); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResPluralsValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.ResResource; import brut.androlib.res.xml.ResValuesXmlSerializable; import brut.androlib.res.xml.ResXmlEncoders; import brut.util.Duo; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; public class ResPluralsValue extends ResBagValue implements ResValuesXmlSerializable { ResPluralsValue(ResReferenceValue parent, Duo<Integer, ResScalarValue>[] items) { super(parent); mItems = new ResScalarValue[6]; for (Duo<Integer, ResScalarValue> item : items) { mItems[item.m1 - BAG_KEY_PLURALS_START] = item.m2; } } @Override public void serializeToResValuesXml(XmlSerializer serializer, ResResource res) throws IOException, AndrolibException { serializer.startTag(null, "plurals"); serializer.attribute(null, "name", res.getResSpec().getName()); for (int i = 0; i < mItems.length; i++) { ResScalarValue item = mItems[i]; if (item == null) { continue; } serializer.startTag(null, "item"); serializer.attribute(null, "quantity", QUANTITY_MAP[i]); serializer.text(ResXmlEncoders.enumerateNonPositionalSubstitutionsIfRequired(item.encodeAsResXmlNonEscapedItemValue())); serializer.endTag(null, "item"); } serializer.endTag(null, "plurals"); } private final ResScalarValue[] mItems; public static final int BAG_KEY_PLURALS_START = 0x01000004; public static final int BAG_KEY_PLURALS_END = 0x01000009; private static final String[] QUANTITY_MAP = new String[] { "other", "zero", "one", "two", "few", "many" }; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResReferenceValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import brut.androlib.exceptions.AndrolibException; import brut.androlib.exceptions.UndefinedResObjectException; import brut.androlib.res.data.ResPackage; import brut.androlib.res.data.ResResSpec; public class ResReferenceValue extends ResIntValue { private final ResPackage mPackage; private final boolean mTheme; public ResReferenceValue(ResPackage package_, int value, String rawValue) { this(package_, value, rawValue, false); } public ResReferenceValue(ResPackage package_, int value, String rawValue, boolean theme) { super(value, rawValue, "reference"); mPackage = package_; mTheme = theme; } @Override protected String encodeAsResXml() throws AndrolibException { if (isNull()) { return "@null"; } ResResSpec spec = getReferent(); if (spec == null) { return "@null"; } boolean newId = spec.hasDefaultResource() && spec.getDefaultResource().getValue() instanceof ResIdValue; // generate the beginning to fix @android String mStart = (mTheme ? '?' : '@') + (newId ? "+" : ""); return mStart + spec.getFullName(mPackage, mTheme && spec.getType().getName().equals("attr")); } public ResResSpec getReferent() throws AndrolibException { try { return mPackage.getResTable().getResSpec(getValue()); } catch (UndefinedResObjectException ex) { return null; } } public boolean isNull() { return mValue == 0; } public boolean referentIsNull() throws AndrolibException { return getReferent() == null; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResScalarValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.ResResource; import brut.androlib.res.xml.ResValuesXmlSerializable; import brut.androlib.res.xml.ResXmlEncodable; import brut.androlib.res.xml.ResXmlEncoders; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; public abstract class ResScalarValue extends ResIntBasedValue implements ResXmlEncodable, ResValuesXmlSerializable { protected final String mType; protected final String mRawValue; protected ResScalarValue(String type, int rawIntValue, String rawValue) { super(rawIntValue); mType = type; mRawValue = rawValue; } @Override public String encodeAsResXmlAttr() throws AndrolibException { if (mRawValue != null) { return mRawValue; } return encodeAsResXml(); } public String encodeAsResXmlItemValue() throws AndrolibException { return encodeAsResXmlValue(); } @Override public String encodeAsResXmlValue() throws AndrolibException { if (mRawValue != null) { return mRawValue; } return encodeAsResXml(); } public String encodeAsResXmlNonEscapedItemValue() throws AndrolibException { return encodeAsResXmlValue().replace("&amp;", "&").replace("&lt;","<"); } public boolean hasMultipleNonPositionalSubstitutions() { return ResXmlEncoders.hasMultipleNonPositionalSubstitutions(mRawValue); } @Override public void serializeToResValuesXml(XmlSerializer serializer, ResResource res) throws IOException, AndrolibException { String type = res.getResSpec().getType().getName(); boolean item = !"reference".equals(mType) && !type.equals(mType); String body = encodeAsResXmlValue(); // check for resource reference if (!type.equalsIgnoreCase("color")) { if (body.contains("@")) { if (!res.getFilePath().contains("string")) { item = true; } } } // Android does not allow values (false) for ids.xml anymore // https://issuetracker.google.com/issues/80475496 // But it decodes as a ResBoolean, which makes no sense. So force it to empty if (type.equalsIgnoreCase("id") && !body.isEmpty()) { body = ""; } // check for using attrib as node or item String tagName = item ? "item" : type; serializer.startTag(null, tagName); if (item) { serializer.attribute(null, "type", type); } serializer.attribute(null, "name", res.getResSpec().getName()); serializeExtraXmlAttrs(serializer, res); if (!body.isEmpty()) { serializer.ignorableWhitespace(body); } serializer.endTag(null, tagName); } public String getType() { return mType; } protected void serializeExtraXmlAttrs(XmlSerializer serializer, ResResource res) throws IOException { } protected abstract String encodeAsResXml() throws AndrolibException; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResStringValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.ResResource; import brut.androlib.res.xml.ResXmlEncoders; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; import java.util.regex.Pattern; public class ResStringValue extends ResScalarValue { public ResStringValue(String value, int rawValue) { this(value, rawValue, "string"); } public ResStringValue(String value, int rawValue, String type) { super(type, rawValue, value); } @Override public String encodeAsResXmlAttr() { return checkIfStringIsNumeric(ResXmlEncoders.encodeAsResXmlAttr(mRawValue)); } @Override public String encodeAsResXmlItemValue() { return ResXmlEncoders.enumerateNonPositionalSubstitutionsIfRequired(ResXmlEncoders.encodeAsXmlValue(mRawValue)); } @Override public String encodeAsResXmlValue() { return ResXmlEncoders.encodeAsXmlValue(mRawValue); } @Override protected String encodeAsResXml() throws AndrolibException { throw new UnsupportedOperationException(); } @Override protected void serializeExtraXmlAttrs(XmlSerializer serializer, ResResource res) throws IOException { if (ResXmlEncoders.hasMultipleNonPositionalSubstitutions(mRawValue)) { serializer.attribute(null, "formatted", "false"); } } private String checkIfStringIsNumeric(String val) { if (val == null || val.isEmpty()) { return val; } return allDigits.matcher(val).matches() ? "\\ " + val : val; } private static final Pattern allDigits = Pattern.compile("\\d{9,}"); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResStyleValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.ResResSpec; import brut.androlib.res.data.ResResource; import brut.androlib.res.xml.ResValuesXmlSerializable; import brut.util.Duo; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; import java.util.logging.Logger; public class ResStyleValue extends ResBagValue implements ResValuesXmlSerializable { ResStyleValue(ResReferenceValue parent, Duo<Integer, ResScalarValue>[] items, ResValueFactory factory) { super(parent); mItems = new Duo[items.length]; for (int i = 0; i < items.length; i++) { mItems[i] = new Duo<>( factory.newReference(items[i].m1, null), items[i].m2); } } @Override public void serializeToResValuesXml(XmlSerializer serializer, ResResource res) throws IOException, AndrolibException { serializer.startTag(null, "style"); serializer.attribute(null, "name", res.getResSpec().getName()); if (!mParent.isNull() && !mParent.referentIsNull()) { serializer.attribute(null, "parent", mParent.encodeAsResXmlAttr()); } else if (res.getResSpec().getName().indexOf('.') != -1) { serializer.attribute(null, "parent", ""); } for (Duo<ResReferenceValue, ResScalarValue> mItem : mItems) { ResResSpec spec = mItem.m1.getReferent(); if (spec == null) { LOGGER.fine(String.format("null reference: m1=0x%08x(%s), m2=0x%08x(%s)", mItem.m1.getRawIntValue(), mItem.m1.getType(), mItem.m2.getRawIntValue(), mItem.m2.getType())); continue; } String name; String value = null; ResValue resource = spec.getDefaultResource().getValue(); if (resource instanceof ResReferenceValue) { continue; } else if (resource instanceof ResAttr) { ResAttr attr = (ResAttr) resource; value = attr.convertToResXmlFormat(mItem.m2); name = spec.getFullName(res.getResSpec().getPackage(), true); } else { name = "@" + spec.getFullName(res.getResSpec().getPackage(), false); } if (value == null) { value = mItem.m2.encodeAsResXmlValue(); } if (value == null) { continue; } serializer.startTag(null, "item"); serializer.attribute(null, "name", name); serializer.text(value); serializer.endTag(null, "item"); } serializer.endTag(null, "style"); } private final Duo<ResReferenceValue, ResScalarValue>[] mItems; private static final Logger LOGGER = Logger.getLogger(ResStyleValue.class.getName()); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; public class ResValue { }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResValueFactory.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.data.value; import android.util.TypedValue; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.ResPackage; import brut.androlib.res.data.ResTypeSpec; import brut.util.Duo; public class ResValueFactory { private final ResPackage mPackage; public ResValueFactory(ResPackage package_) { this.mPackage = package_; } public ResScalarValue factory(int type, int value, String rawValue) throws AndrolibException { switch (type) { case TypedValue.TYPE_NULL: if (value == TypedValue.DATA_NULL_UNDEFINED) { // Special case $empty as explicitly defined empty value return new ResStringValue(null, value); } else if (value == TypedValue.DATA_NULL_EMPTY) { return new ResEmptyValue(value, rawValue, type); } return new ResReferenceValue(mPackage, 0, null); case TypedValue.TYPE_REFERENCE: return newReference(value, null); case TypedValue.TYPE_ATTRIBUTE: case TypedValue.TYPE_DYNAMIC_ATTRIBUTE: return newReference(value, rawValue, true); case TypedValue.TYPE_STRING: return new ResStringValue(rawValue, value); case TypedValue.TYPE_FLOAT: return new ResFloatValue(Float.intBitsToFloat(value), value, rawValue); case TypedValue.TYPE_DIMENSION: return new ResDimenValue(value, rawValue); case TypedValue.TYPE_FRACTION: return new ResFractionValue(value, rawValue); case TypedValue.TYPE_INT_BOOLEAN: return new ResBoolValue(value != 0, value, rawValue); case TypedValue.TYPE_DYNAMIC_REFERENCE: return newReference(value, rawValue); } if (type >= TypedValue.TYPE_FIRST_COLOR_INT && type <= TypedValue.TYPE_LAST_COLOR_INT) { return new ResColorValue(value, rawValue); } if (type >= TypedValue.TYPE_FIRST_INT && type <= TypedValue.TYPE_LAST_INT) { return new ResIntValue(value, rawValue, type); } throw new AndrolibException("Invalid value type: " + type); } public ResIntBasedValue factory(String value, int rawValue) { if (value == null) { return new ResFileValue("", rawValue); } if (value.startsWith("res/")) { return new ResFileValue(value, rawValue); } if (value.startsWith("r/") || value.startsWith("R/")) { //AndroResGuard return new ResFileValue(value, rawValue); } return new ResStringValue(value, rawValue); } public ResBagValue bagFactory(int parent, Duo<Integer, ResScalarValue>[] items, ResTypeSpec resTypeSpec) throws AndrolibException { ResReferenceValue parentVal = newReference(parent, null); if (items.length == 0) { return new ResBagValue(parentVal); } int key = items[0].m1; if (key == ResAttr.BAG_KEY_ATTR_TYPE) { return ResAttr.factory(parentVal, items, this, mPackage); } String resTypeName = resTypeSpec.getName(); // Android O Preview added an unknown enum for c. This is hardcoded as 0 for now. if (ResTypeSpec.RES_TYPE_NAME_ARRAY.equals(resTypeName) || key == ResArrayValue.BAG_KEY_ARRAY_START || key == 0) { return new ResArrayValue(parentVal, items); } if (ResTypeSpec.RES_TYPE_NAME_PLURALS.equals(resTypeName) || (key >= ResPluralsValue.BAG_KEY_PLURALS_START && key <= ResPluralsValue.BAG_KEY_PLURALS_END)) { return new ResPluralsValue(parentVal, items); } if (ResTypeSpec.RES_TYPE_NAME_ATTR.equals(resTypeName)) { return new ResAttr(parentVal, 0, null, null, null); } if (resTypeName.startsWith(ResTypeSpec.RES_TYPE_NAME_STYLES)) { return new ResStyleValue(parentVal, items, this); } throw new AndrolibException("unsupported res type name for bags. Found: " + resTypeName); } public ResReferenceValue newReference(int resID, String rawValue) { return newReference(resID, rawValue, false); } public ResReferenceValue newReference(int resID, String rawValue, boolean theme) { return new ResReferenceValue(mPackage, resID, rawValue, theme); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/AndroidManifestResourceParser.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.decoder; import android.util.TypedValue; import brut.androlib.res.data.ResTable; import java.util.regex.Pattern; /** * AXmlResourceParser specifically for parsing encoded AndroidManifest.xml. */ public class AndroidManifestResourceParser extends AXmlResourceParser { public AndroidManifestResourceParser(ResTable resTable) { super(resTable); } /** * Pattern for matching numeric string meta-data values. aapt automatically infers the * type for a manifest meta-data value based on the string in the unencoded XML. However, * some apps intentionally coerce integers to be strings by prepending an escaped space. * For details/discussion, see https://stackoverflow.com/questions/2154945/how-to-force-a-meta-data-value-to-type-string * With aapt1, the escaped space is dropped when encoded. For aapt2, the escaped space is preserved. */ private static final Pattern PATTERN_NUMERIC_STRING = Pattern.compile("\\s?\\d+"); @Override public String getAttributeValue(int index) { String value = super.getAttributeValue(index); if (value == null) { return ""; } if (!isNumericStringMetadataAttributeValue(index, value)) { return value; } // Patch the numeric string value by prefixing it with an escaped space. // Otherwise, when the decoded app is rebuilt, aapt will incorrectly encode // the value as an int or float (depending on aapt version), breaking the original // app functionality. return "\\ " + value.trim(); } private boolean isNumericStringMetadataAttributeValue(int index, String value) { return "meta-data".equalsIgnoreCase(super.getName()) && "value".equalsIgnoreCase(super.getAttributeName(index)) && super.getAttributeValueType(index) == TypedValue.TYPE_STRING && PATTERN_NUMERIC_STRING.matcher(value).matches(); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/ARSCDecoder.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.decoder; import android.util.TypedValue; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.*; import brut.androlib.res.data.arsc.*; import brut.androlib.res.data.value.*; import brut.util.Duo; import brut.util.ExtCountingDataInput; import com.google.common.io.LittleEndianDataInputStream; import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.logging.Logger; public class ARSCDecoder { public static ARSCData decode(InputStream arscStream, boolean findFlagsOffsets, boolean keepBroken) throws AndrolibException { return decode(arscStream, findFlagsOffsets, keepBroken, new ResTable()); } public static ARSCData decode(InputStream arscStream, boolean findFlagsOffsets, boolean keepBroken, ResTable resTable) throws AndrolibException { try { ARSCDecoder decoder = new ARSCDecoder(arscStream, resTable, findFlagsOffsets, keepBroken); ResPackage[] pkgs = decoder.readResourceTable(); return new ARSCData(pkgs, decoder.mFlagsOffsets == null ? null : decoder.mFlagsOffsets.toArray(new FlagsOffset[0])); } catch (IOException ex) { throw new AndrolibException("Could not decode arsc file", ex); } } private ARSCDecoder(InputStream arscStream, ResTable resTable, boolean storeFlagsOffsets, boolean keepBroken) { if (storeFlagsOffsets) { mFlagsOffsets = new ArrayList<>(); } else { mFlagsOffsets = null; } mIn = new ExtCountingDataInput(new LittleEndianDataInputStream(arscStream)); mResTable = resTable; mKeepBroken = keepBroken; } private ResPackage[] readResourceTable() throws IOException, AndrolibException { Set<ResPackage> pkgs = new LinkedHashSet<>(); ResTypeSpec typeSpec; int chunkNumber = 1; chunkLoop: for (;;) { nextChunk(); LOGGER.fine(String.format( "Chunk #%d start: type=0x%04x chunkSize=0x%08x", chunkNumber++, mHeader.type, mHeader.chunkSize )); switch (mHeader.type) { case ARSCHeader.RES_NULL_TYPE: readUnknownChunk(); break; case ARSCHeader.RES_STRING_POOL_TYPE: readStringPoolChunk(); break; case ARSCHeader.RES_TABLE_TYPE: readTableChunk(); break; // Chunk types in RES_TABLE_TYPE case ARSCHeader.XML_TYPE_PACKAGE: mTypeIdOffset = 0; pkgs.add(readTablePackage()); break; case ARSCHeader.XML_TYPE_TYPE: readTableType(); break; case ARSCHeader.XML_TYPE_SPEC_TYPE: typeSpec = readTableSpecType(); addTypeSpec(typeSpec); break; case ARSCHeader.XML_TYPE_LIBRARY: readLibraryType(); break; case ARSCHeader.XML_TYPE_OVERLAY: readOverlaySpec(); break; case ARSCHeader.XML_TYPE_OVERLAY_POLICY: readOverlayPolicySpec(); break; case ARSCHeader.XML_TYPE_STAGED_ALIAS: readStagedAliasSpec(); break; default: if (mHeader.type != ARSCHeader.RES_NONE_TYPE) { LOGGER.severe(String.format("Unknown chunk type: %04x", mHeader.type)); } break chunkLoop; } } return pkgs.toArray(new ResPackage[0]); } private void readStringPoolChunk() throws IOException, AndrolibException { checkChunkType(ARSCHeader.RES_STRING_POOL_TYPE); mTableStrings = StringBlock.readWithoutChunk(mIn, mHeader.startPosition, mHeader.headerSize, mHeader.chunkSize); } private void readTableChunk() throws IOException, AndrolibException { checkChunkType(ARSCHeader.RES_TABLE_TYPE); mIn.skipInt(); // packageCount mHeader.checkForUnreadHeader(mIn); } private void readUnknownChunk() throws IOException, AndrolibException { checkChunkType(ARSCHeader.RES_NULL_TYPE); mHeader.checkForUnreadHeader(mIn); LOGGER.warning("Skipping unknown chunk data of size " + mHeader.chunkSize); mHeader.skipChunk(mIn); } private ResPackage readTablePackage() throws IOException, AndrolibException { checkChunkType(ARSCHeader.XML_TYPE_PACKAGE); int id = mIn.readInt(); if (id == 0) { // This means we are dealing with a Library Package, we should just temporarily // set the packageId to the next available id . This will be set at runtime regardless, but // for Apktool's use we need a non-zero packageId. // AOSP indicates 0x02 is next, as 0x01 is system and 0x7F is private. id = 2; if (mResTable.getPackageOriginal() == null && mResTable.getPackageRenamed() == null) { mResTable.setSharedLibrary(true); } } String name = mIn.readNullEndedString(128, true); mIn.skipInt(); // typeStrings mIn.skipInt(); // lastPublicType mIn.skipInt(); // keyStrings mIn.skipInt(); // lastPublicKey // TypeIdOffset was added platform_frameworks_base/@f90f2f8dc36e7243b85e0b6a7fd5a590893c827e // which is only in split/new applications. int splitHeaderSize = (2 + 2 + 4 + 4 + (2 * 128) + (4 * 5)); // short, short, int, int, char[128], int * 4 if (mHeader.headerSize == splitHeaderSize) { mTypeIdOffset = mIn.readInt(); } if (mTypeIdOffset > 0) { LOGGER.warning("Please report this application to Apktool for a fix: https://github.com/iBotPeaches/Apktool/issues/1728"); } mHeader.checkForUnreadHeader(mIn); mTypeNames = StringBlock.readWithChunk(mIn); mSpecNames = StringBlock.readWithChunk(mIn); mResId = id << 24; mPkg = new ResPackage(mResTable, id, name); return mPkg; } private void readLibraryType() throws AndrolibException, IOException { checkChunkType(ARSCHeader.XML_TYPE_LIBRARY); int libraryCount = mIn.readInt(); int packageId; String packageName; mHeader.checkForUnreadHeader(mIn); for (int i = 0; i < libraryCount; i++) { packageId = mIn.readInt(); packageName = mIn.readNullEndedString(128, true); LOGGER.info(String.format("Decoding Shared Library (%s), pkgId: %d", packageName, packageId)); } } private void readStagedAliasSpec() throws IOException { int count = mIn.readInt(); mHeader.checkForUnreadHeader(mIn); for (int i = 0; i < count; i++) { LOGGER.fine(String.format("Skipping staged alias stagedId (%h) finalId: %h", mIn.readInt(), mIn.readInt())); } } private void readOverlaySpec() throws AndrolibException, IOException { checkChunkType(ARSCHeader.XML_TYPE_OVERLAY); String name = mIn.readNullEndedString(256, true); String actor = mIn.readNullEndedString(256, true); mHeader.checkForUnreadHeader(mIn); LOGGER.fine(String.format("Overlay name: \"%s\", actor: \"%s\")", name, actor)); } private void readOverlayPolicySpec() throws AndrolibException, IOException { checkChunkType(ARSCHeader.XML_TYPE_OVERLAY_POLICY); mIn.skipInt(); // policyFlags int count = mIn.readInt(); mHeader.checkForUnreadHeader(mIn); for (int i = 0; i < count; i++) { LOGGER.fine(String.format("Skipping overlay (%h)", mIn.readInt())); } } private ResTypeSpec readTableSpecType() throws AndrolibException, IOException { checkChunkType(ARSCHeader.XML_TYPE_SPEC_TYPE); int id = mIn.readUnsignedByte(); mIn.skipBytes(1); // reserved0 mIn.skipBytes(2); // reserved1 int entryCount = mIn.readInt(); if (mFlagsOffsets != null) { mFlagsOffsets.add(new FlagsOffset(mIn.position(), entryCount)); } mHeader.checkForUnreadHeader(mIn); mIn.skipBytes(entryCount * 4); // flags mTypeSpec = new ResTypeSpec(mTypeNames.getString(id - 1), id); mPkg.addType(mTypeSpec); return mTypeSpec; } private ResType readTableType() throws IOException, AndrolibException { checkChunkType(ARSCHeader.XML_TYPE_TYPE); int typeId = mIn.readUnsignedByte() - mTypeIdOffset; if (mResTypeSpecs.containsKey(typeId)) { mResId = (0xff000000 & mResId) | mResTypeSpecs.get(typeId).getId() << 16; mTypeSpec = mResTypeSpecs.get(typeId); } int typeFlags = mIn.readByte(); mIn.skipBytes(2); // reserved int entryCount = mIn.readInt(); mIn.skipInt(); // entriesStart ResConfigFlags flags = readConfigFlags(); mHeader.checkForUnreadHeader(mIn); if ((typeFlags & 0x01) != 0) { mResTable.setSparseResources(true); } HashMap<Integer, Integer> entryOffsetMap = new LinkedHashMap<>(); for (int i = 0; i < entryCount; i++) { if ((typeFlags & 0x01) != 0) { entryOffsetMap.put(mIn.readUnsignedShort(), mIn.readUnsignedShort()); } else { entryOffsetMap.put(i, mIn.readInt()); } } if (flags.isInvalid) { String resName = mTypeSpec.getName() + flags.getQualifiers(); if (mKeepBroken) { LOGGER.warning("Invalid config flags detected: " + resName); } else { LOGGER.warning("Invalid config flags detected. Dropping resources: " + resName); } } mType = flags.isInvalid && !mKeepBroken ? null : mPkg.getOrCreateConfig(flags); for (int i : entryOffsetMap.keySet()) { mResId = (mResId & 0xffff0000) | i; int offset = entryOffsetMap.get(i); if (offset == NO_ENTRY) { continue; } // As seen in some recent APKs - there are more entries reported than can fit in the chunk. if (mIn.position() == mHeader.endPosition) { int remainingEntries = entryCount - i; LOGGER.warning(String.format("End of chunk hit. Skipping remaining entries (%d) in type: %s", remainingEntries, mTypeSpec.getName() )); break; } EntryData entryData = readEntryData(); if (entryData != null) { readEntry(entryData); } } // skip "TYPE 8 chunks" and/or padding data at the end of this chunk if (mIn.position() < mHeader.endPosition) { long bytesSkipped = mIn.skip(mHeader.endPosition - mIn.position()); LOGGER.warning("Unknown data detected. Skipping: " + bytesSkipped + " byte(s)"); } return mType; } private EntryData readEntryData() throws IOException, AndrolibException { short size = mIn.readShort(); if (size < 0) { throw new AndrolibException("Entry size is under 0 bytes."); } short flags = mIn.readShort(); int specNamesId = mIn.readInt(); if (specNamesId == NO_ENTRY) { return null; } ResValue value = (flags & ENTRY_FLAG_COMPLEX) == 0 ? readValue() : readComplexEntry(); // #2824 - In some applications the res entries are duplicated with the 2nd being malformed. // AOSP skips this, so we will do the same. if (value == null) { return null; } EntryData entryData = new EntryData(); entryData.mFlags = flags; entryData.mSpecNamesId = specNamesId; entryData.mValue = value; return entryData; } private void readEntry(EntryData entryData) throws AndrolibException { int specNamesId = entryData.mSpecNamesId; ResValue value = entryData.mValue; if (mTypeSpec.isString() && value instanceof ResFileValue) { value = new ResStringValue(value.toString(), ((ResFileValue) value).getRawIntValue()); } if (mType == null) { return; } ResID resId = new ResID(mResId); ResResSpec spec; if (mPkg.hasResSpec(resId)) { spec = mPkg.getResSpec(resId); } else { spec = new ResResSpec(resId, mSpecNames.getString(specNamesId), mPkg, mTypeSpec); mPkg.addResSpec(spec); mTypeSpec.addResSpec(spec); } ResResource res = new ResResource(mType, spec, value); try { mType.addResource(res); spec.addResource(res); } catch (AndrolibException ex) { if (mKeepBroken) { mType.addResource(res, true); spec.addResource(res, true); LOGGER.warning(String.format("Duplicate Resource Detected. Ignoring duplicate: %s", res)); } else { throw ex; } } } private ResBagValue readComplexEntry() throws IOException, AndrolibException { int parent = mIn.readInt(); int count = mIn.readInt(); ResValueFactory factory = mPkg.getValueFactory(); Duo<Integer, ResScalarValue>[] items = new Duo[count]; ResIntBasedValue resValue; int resId; for (int i = 0; i < count; i++) { resId = mIn.readInt(); resValue = readValue(); if (!(resValue instanceof ResScalarValue)) { resValue = new ResStringValue(resValue.toString(), resValue.getRawIntValue()); } items[i] = new Duo<>(resId, (ResScalarValue) resValue); } return factory.bagFactory(parent, items, mTypeSpec); } private ResIntBasedValue readValue() throws IOException, AndrolibException { int size = mIn.readShort(); if (size < 8) { return null; } mIn.skipCheckByte((byte) 0); // zero byte type = mIn.readByte(); int data = mIn.readInt(); return type == TypedValue.TYPE_STRING ? mPkg.getValueFactory().factory(mTableStrings.getHTML(data), data) : mPkg.getValueFactory().factory(type, data, null); } private ResConfigFlags readConfigFlags() throws IOException, AndrolibException { int size = mIn.readInt(); int read = 8; if (size < 8) { throw new AndrolibException("Config size < 8"); } boolean isInvalid = false; short mcc = mIn.readShort(); short mnc = mIn.readShort(); char[] language = new char[0]; char[] country = new char[0]; if (size >= 12) { language = this.unpackLanguageOrRegion(mIn.readByte(), mIn.readByte(), 'a'); country = this.unpackLanguageOrRegion(mIn.readByte(), mIn.readByte(), '0'); read = 12; } byte orientation = 0; byte touchscreen = 0; if (size >= 14) { orientation = mIn.readByte(); touchscreen = mIn.readByte(); read = 14; } int density = 0; if (size >= 16) { density = mIn.readUnsignedShort(); read = 16; } byte keyboard = 0; byte navigation = 0; byte inputFlags = 0; if (size >= 20) { keyboard = mIn.readByte(); navigation = mIn.readByte(); inputFlags = mIn.readByte(); mIn.skipBytes(1); // inputPad0 read = 20; } short screenWidth = 0; short screenHeight = 0; short sdkVersion = 0; if (size >= 28) { screenWidth = mIn.readShort(); screenHeight = mIn.readShort(); sdkVersion = mIn.readShort(); mIn.skipBytes(2); // minorVersion read = 28; } byte screenLayout = 0; byte uiMode = 0; short smallestScreenWidthDp = 0; if (size >= 32) { screenLayout = mIn.readByte(); uiMode = mIn.readByte(); smallestScreenWidthDp = mIn.readShort(); read = 32; } short screenWidthDp = 0; short screenHeightDp = 0; if (size >= 36) { screenWidthDp = mIn.readShort(); screenHeightDp = mIn.readShort(); read = 36; } char[] localeScript = null; char[] localeVariant = null; if (size >= 48) { localeScript = readVariantLengthString(4).toCharArray(); localeVariant = readVariantLengthString(8).toCharArray(); read = 48; } byte screenLayout2 = 0; byte colorMode = 0; if (size >= 52) { screenLayout2 = mIn.readByte(); colorMode = mIn.readByte(); mIn.skipBytes(2); // screenConfigPad2 read = 52; } char[] localeNumberingSystem = null; if (size >= 60) { localeNumberingSystem = readVariantLengthString(8).toCharArray(); read = 60; } int exceedingKnownSize = size - KNOWN_CONFIG_BYTES; if (exceedingKnownSize > 0) { byte[] buf = new byte[exceedingKnownSize]; read += exceedingKnownSize; mIn.readFully(buf); BigInteger exceedingBI = new BigInteger(1, buf); if (exceedingBI.equals(BigInteger.ZERO)) { LOGGER.fine(String .format("Config flags size > %d, but exceeding bytes are all zero, so it should be ok.", KNOWN_CONFIG_BYTES)); } else { LOGGER.warning(String.format("Config flags size > %d. Size = %d. Exceeding bytes: 0x%X.", KNOWN_CONFIG_BYTES, size, exceedingBI)); isInvalid = true; } } int remainingSize = size - read; if (remainingSize > 0) { mIn.skipBytes(remainingSize); } return new ResConfigFlags(mcc, mnc, language, country, orientation, touchscreen, density, keyboard, navigation, inputFlags, screenWidth, screenHeight, sdkVersion, screenLayout, uiMode, smallestScreenWidthDp, screenWidthDp, screenHeightDp, localeScript, localeVariant, screenLayout2, colorMode, localeNumberingSystem, isInvalid, size); } private char[] unpackLanguageOrRegion(byte in0, byte in1, char base) { // check high bit, if so we have a packed 3 letter code if (((in0 >> 7) & 1) == 1) { int first = in1 & 0x1F; int second = ((in1 & 0xE0) >> 5) + ((in0 & 0x03) << 3); int third = (in0 & 0x7C) >> 2; // since this function handles languages & regions, we add the value(s) to the base char // which is usually 'a' or '0' depending on language or region. return new char[] { (char) (first + base), (char) (second + base), (char) (third + base) }; } return new char[] { (char) in0, (char) in1 }; } private String readVariantLengthString(int maxLength) throws IOException { StringBuilder string = new StringBuilder(16); while (maxLength-- != 0) { short ch = mIn.readByte(); if (ch == 0) { break; } string.append((char) ch); } mIn.skipBytes(maxLength); return string.toString(); } private void addTypeSpec(ResTypeSpec resTypeSpec) { mResTypeSpecs.put(resTypeSpec.getId(), resTypeSpec); } private ARSCHeader nextChunk() throws IOException { return mHeader = ARSCHeader.read(mIn); } private void checkChunkType(int expectedType) throws AndrolibException { if (mHeader.type != expectedType) { throw new AndrolibException(String.format("Invalid chunk type: expected=0x%08x, got=0x%08x", expectedType, mHeader.type)); } } private final ExtCountingDataInput mIn; private final ResTable mResTable; private final List<FlagsOffset> mFlagsOffsets; private final boolean mKeepBroken; private ARSCHeader mHeader; private StringBlock mTableStrings; private StringBlock mTypeNames; private StringBlock mSpecNames; private ResPackage mPkg; private ResTypeSpec mTypeSpec; private ResType mType; private int mResId; private int mTypeIdOffset = 0; private final HashMap<Integer, ResTypeSpec> mResTypeSpecs = new HashMap<>(); private final static short ENTRY_FLAG_COMPLEX = 0x0001; private final static short ENTRY_FLAG_PUBLIC = 0x0002; private final static short ENTRY_FLAG_WEAK = 0x0004; private static final int KNOWN_CONFIG_BYTES = 64; private static final int NO_ENTRY = 0xFFFFFFFF; private static final Logger LOGGER = Logger.getLogger(ARSCDecoder.class.getName()); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/AXmlResourceParser.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.decoder; import android.content.res.XmlResourceParser; import android.util.TypedValue; import brut.androlib.exceptions.AndrolibException; import brut.androlib.exceptions.CantFindFrameworkResException; import brut.androlib.exceptions.UndefinedResObjectException; import brut.androlib.res.data.ResID; import brut.androlib.res.data.ResResSpec; import brut.androlib.res.data.ResTable; import brut.androlib.res.data.arsc.ARSCHeader; import brut.androlib.res.data.axml.NamespaceStack; import brut.androlib.res.data.value.ResAttr; import brut.androlib.res.data.value.ResScalarValue; import brut.androlib.res.xml.ResXmlEncoders; import brut.util.ExtCountingDataInput; import com.google.common.io.LittleEndianDataInputStream; import org.xmlpull.v1.XmlPullParserException; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Binary xml files parser. * * <p>Parser has only two states: (1) Operational state, which parser * obtains after first successful call to next() and retains until * open(), close(), or failed call to next(). (2) Closed state, which * parser obtains after open(), close(), or failed call to next(). In * this state methods return invalid values or throw exceptions. */ public class AXmlResourceParser implements XmlResourceParser { public AXmlResourceParser(ResTable resTable) { mResTable = resTable; resetEventInfo(); } public AndrolibException getFirstError() { return mFirstError; } public ResTable getResTable() { return mResTable; } public void open(InputStream stream) { close(); if (stream != null) { mIn = new ExtCountingDataInput(new LittleEndianDataInputStream(stream)); } } @Override public void close() { if (!isOperational) { return; } isOperational = false; mIn = null; mStringBlock = null; mResourceIds = null; mNamespaces.reset(); resetEventInfo(); } @Override public int next() throws XmlPullParserException, IOException { if (mIn == null) { throw new XmlPullParserException("Parser is not opened.", this, null); } try { doNext(); return mEvent; } catch (IOException e) { close(); throw e; } } @Override public int nextToken() throws XmlPullParserException, IOException { return next(); } @Override public int nextTag() throws XmlPullParserException, IOException { int eventType = next(); if (eventType == TEXT && isWhitespace()) { eventType = next(); } if (eventType != START_TAG && eventType != END_TAG) { throw new XmlPullParserException("Expected start or end tag.", this, null); } return eventType; } @Override public String nextText() throws XmlPullParserException, IOException { if (getEventType() != START_TAG) { throw new XmlPullParserException("Parser must be on START_TAG to read next text.", this, null); } int eventType = next(); if (eventType == TEXT) { String result = getText(); eventType = next(); if (eventType != END_TAG) { throw new XmlPullParserException("Event TEXT must be immediately followed by END_TAG.", this, null); } return result; } else if (eventType == END_TAG) { return ""; } else { throw new XmlPullParserException("Parser must be on START_TAG or TEXT to read text.", this, null); } } @Override public void require(int type, String namespace, String name) throws XmlPullParserException { if (type != getEventType() || (namespace != null && !namespace.equals(getNamespace())) || (name != null && !name.equals(getName()))) { throw new XmlPullParserException(TYPES[type] + " is expected.", this, null); } } @Override public int getDepth() { return mNamespaces.getDepth() - 1; } @Override public int getEventType(){ return mEvent; } @Override public int getLineNumber() { return mLineNumber; } @Override public String getName() { if (mNameIndex == -1 || (mEvent != START_TAG && mEvent != END_TAG)) { return null; } return mStringBlock.getString(mNameIndex); } @Override public String getText() { if (mNameIndex == -1 || mEvent != TEXT) { return null; } return mStringBlock.getString(mNameIndex); } @Override public char[] getTextCharacters(int[] holderForStartAndLength) { String text = getText(); if (text == null) { return null; } holderForStartAndLength[0] = 0; holderForStartAndLength[1] = text.length(); char[] chars = new char[text.length()]; text.getChars(0, text.length(), chars, 0); return chars; } @Override public String getNamespace() { return mStringBlock.getString(mNamespaceIndex); } @Override public String getPrefix() { int prefix = mNamespaces.findPrefix(mNamespaceIndex); return mStringBlock.getString(prefix); } @Override public String getPositionDescription() { return "XML line #" + getLineNumber(); } @Override public int getNamespaceCount(int depth) { return mNamespaces.getAccumulatedCount(depth); } @Override public String getNamespacePrefix(int pos) { int prefix = mNamespaces.getPrefix(pos); return mStringBlock.getString(prefix); } @Override public String getNamespaceUri(int pos) { int uri = mNamespaces.getUri(pos); return mStringBlock.getString(uri); } @Override public String getClassAttribute() { if (mClassIndex == -1) { return null; } int offset = getAttributeOffset(mClassIndex); int value = mAttributes[offset + ATTRIBUTE_IX_VALUE_STRING]; return mStringBlock.getString(value); } @Override public String getIdAttribute() { if (mIdIndex == -1) { return null; } int offset = getAttributeOffset(mIdIndex); int value = mAttributes[offset + ATTRIBUTE_IX_VALUE_STRING]; return mStringBlock.getString(value); } @Override public int getIdAttributeResourceValue(int defaultValue) { if (mIdIndex == -1) { return defaultValue; } int offset = getAttributeOffset(mIdIndex); int valueType = mAttributes[offset + ATTRIBUTE_IX_VALUE_TYPE]; if (valueType != TypedValue.TYPE_REFERENCE) { return defaultValue; } return mAttributes[offset + ATTRIBUTE_IX_VALUE_DATA]; } @Override public int getStyleAttribute() { if (mStyleIndex == -1) { return 0; } int offset = getAttributeOffset(mStyleIndex); return mAttributes[offset + ATTRIBUTE_IX_VALUE_DATA]; } @Override public int getAttributeCount() { if (mEvent != START_TAG) { return -1; } return mAttributes.length / ATTRIBUTE_LENGTH; } @Override public String getAttributeNamespace(int index) { int offset = getAttributeOffset(index); int namespace = mAttributes[offset + ATTRIBUTE_IX_NAMESPACE_URI]; // #2972 - If the namespace index is -1, the attribute is not present, but if the attribute is from system // we can resolve it to the default namespace. This may prove to be too aggressive as we scope the entire // system namespace, but it is better than not resolving it at all. ResID resId = new ResID(getAttributeNameResource(index)); if (namespace == -1 && resId.pkgId == 1) { return ANDROID_RES_NS; } if (namespace == -1) { return ""; } // Minifiers like removing the namespace, so we will default to default namespace // unless the pkgId of the resource is private. We will grab the non-standard one. String value = mStringBlock.getString(namespace); if (value == null || value.isEmpty()) { if (resId.pkgId == PRIVATE_PKG_ID) { return getNonDefaultNamespaceUri(offset); } else { return ANDROID_RES_NS; } } return value; } public String decodeFromResourceId(int attrResId) throws AndrolibException { if (attrResId != 0) { try { ResResSpec resResSpec = mResTable.getResSpec(attrResId); if (resResSpec != null) { return resResSpec.getName(); } } catch (UndefinedResObjectException | CantFindFrameworkResException ignored) {} } return null; } private String getNonDefaultNamespaceUri(int offset) { String prefix = mStringBlock.getString(mNamespaces.getPrefix(offset)); if (prefix != null) { return mStringBlock.getString(mNamespaces.getUri(offset)); } // If we are here. There is some clever obfuscation going on. Our reference points to the namespace are gone. // Normally we could take the index * attributeCount to get an offset. // That would point to the URI in the StringBlock table, but that is empty. // We have the namespaces that can't be touched in the opening tag. // Though no known way to correlate them at this time. // So return the res-auto namespace. return ANDROID_RES_NS_AUTO; } @Override public String getAttributePrefix(int index) { int offset = getAttributeOffset(index); int uri = mAttributes[offset + ATTRIBUTE_IX_NAMESPACE_URI]; int prefix = mNamespaces.findPrefix(uri); if (prefix == -1) { return ""; } return mStringBlock.getString(prefix); } @Override public String getAttributeName(int index) { int offset = getAttributeOffset(index); int name = mAttributes[offset + ATTRIBUTE_IX_NAME]; if (name == -1) { return ""; } String resourceMapValue; String stringBlockValue = mStringBlock.getString(name); int resourceId = getAttributeNameResource(index); try { resourceMapValue = decodeFromResourceId(resourceId); } catch (AndrolibException ignored) { resourceMapValue = null; } // Android prefers the resource map value over what the String block has. // This can be seen quite often in obfuscated apps where values such as: // <item android:state_enabled="true" app:state_collapsed="false" app:state_collapsible="true"> // Are improperly decoded when trusting the String block. // Leveraging the resource map allows us to get the proper value. // <item android:state_enabled="true" app:d2="false" app:d3="true"> if (resourceMapValue != null) { return resourceMapValue; } if (stringBlockValue != null) { return stringBlockValue; } // In this case we have a bogus resource. If it was not found in either. return "APKTOOL_MISSING_" + Integer.toHexString(resourceId); } @Override public int getAttributeNameResource(int index) { int offset = getAttributeOffset(index); int name = mAttributes[offset + ATTRIBUTE_IX_NAME]; if (mResourceIds == null || name < 0 || name >= mResourceIds.length) { return 0; } return mResourceIds[name]; } @Override public int getAttributeValueType(int index) { int offset = getAttributeOffset(index); return mAttributes[offset + ATTRIBUTE_IX_VALUE_TYPE]; } @Override public int getAttributeValueData(int index) { int offset = getAttributeOffset(index); return mAttributes[offset + ATTRIBUTE_IX_VALUE_DATA]; } @Override public String getAttributeValue(int index) { int offset = getAttributeOffset(index); int valueType = mAttributes[offset + ATTRIBUTE_IX_VALUE_TYPE]; int valueData = mAttributes[offset + ATTRIBUTE_IX_VALUE_DATA]; int valueRaw = mAttributes[offset + ATTRIBUTE_IX_VALUE_STRING]; try { String stringBlockValue = valueRaw == -1 ? null : ResXmlEncoders.escapeXmlChars(mStringBlock.getString(valueRaw)); String resourceMapValue = null; // Ensure we only track down obfuscated values for reference/attribute type values. Otherwise, we might // spam lookups against resource table for invalid ids. if (valueType == TypedValue.TYPE_REFERENCE || valueType == TypedValue.TYPE_DYNAMIC_REFERENCE || valueType == TypedValue.TYPE_ATTRIBUTE || valueType == TypedValue.TYPE_DYNAMIC_ATTRIBUTE) { resourceMapValue = decodeFromResourceId(valueData); } String value = getPreferredString(stringBlockValue, resourceMapValue); // try to decode from resource table int attrResId = getAttributeNameResource(index); ResScalarValue resValue = mResTable.getCurrentResPackage() .getValueFactory().factory(valueType, valueData, value); String decoded = null; if (attrResId > 0) { try { ResAttr attr = (ResAttr) mResTable.getResSpec(attrResId).getDefaultResource().getValue(); decoded = attr.convertToResXmlFormat(resValue); } catch (UndefinedResObjectException | ClassCastException ignored) {} } return decoded != null ? decoded : resValue.encodeAsResXmlAttr(); } catch (AndrolibException ex) { setFirstError(ex); LOGGER.log(Level.WARNING, String.format("Could not decode attr value, using undecoded value " + "instead: ns=%s, name=%s, value=0x%08x", getAttributePrefix(index), getAttributeName(index), valueData), ex); } return TypedValue.coerceToString(valueType, valueData); } @Override public boolean getAttributeBooleanValue(int index, boolean defaultValue) { return getAttributeIntValue(index, defaultValue ? 1 : 0) != 0; } @Override public float getAttributeFloatValue(int index, float defaultValue) { int offset = getAttributeOffset(index); int valueType = mAttributes[offset + ATTRIBUTE_IX_VALUE_TYPE]; if (valueType == TypedValue.TYPE_FLOAT) { int valueData = mAttributes[offset + ATTRIBUTE_IX_VALUE_DATA]; return Float.intBitsToFloat(valueData); } return defaultValue; } @Override public int getAttributeIntValue(int index, int defaultValue) { int offset = getAttributeOffset(index); int valueType = mAttributes[offset + ATTRIBUTE_IX_VALUE_TYPE]; if (valueType >= TypedValue.TYPE_FIRST_INT && valueType <= TypedValue.TYPE_LAST_INT) { return mAttributes[offset + ATTRIBUTE_IX_VALUE_DATA]; } return defaultValue; } @Override public int getAttributeUnsignedIntValue(int index, int defaultValue) { return getAttributeIntValue(index, defaultValue); } @Override public int getAttributeResourceValue(int index, int defaultValue) { int offset = getAttributeOffset(index); int valueType = mAttributes[offset + ATTRIBUTE_IX_VALUE_TYPE]; if (valueType == TypedValue.TYPE_REFERENCE) { return mAttributes[offset + ATTRIBUTE_IX_VALUE_DATA]; } return defaultValue; } @Override public String getAttributeValue(String namespace, String attribute) { int index = findAttribute(namespace, attribute); if (index == -1) { return ""; } return getAttributeValue(index); } @Override public boolean getAttributeBooleanValue(String namespace, String attribute, boolean defaultValue) { int index = findAttribute(namespace, attribute); if (index == -1) { return defaultValue; } return getAttributeBooleanValue(index, defaultValue); } @Override public float getAttributeFloatValue(String namespace, String attribute, float defaultValue) { int index = findAttribute(namespace, attribute); if (index == -1) { return defaultValue; } return getAttributeFloatValue(index, defaultValue); } @Override public int getAttributeIntValue(String namespace, String attribute, int defaultValue) { int index = findAttribute(namespace, attribute); if (index == -1) { return defaultValue; } return getAttributeIntValue(index, defaultValue); } @Override public int getAttributeUnsignedIntValue(String namespace, String attribute, int defaultValue) { int index = findAttribute(namespace, attribute); if (index == -1) { return defaultValue; } return getAttributeUnsignedIntValue(index, defaultValue); } @Override public int getAttributeResourceValue(String namespace, String attribute, int defaultValue) { int index = findAttribute(namespace, attribute); if (index == -1) { return defaultValue; } return getAttributeResourceValue(index, defaultValue); } @Override public int getAttributeListValue(int index, String[] options, int defaultValue) { return 0; } @Override public int getAttributeListValue(String namespace, String attribute, String[] options, int defaultValue) { return 0; } @Override public String getAttributeType(int index) { return "CDATA"; } @Override public boolean isAttributeDefault(int index) { return false; } @Override public void setInput(InputStream stream, String inputEncoding) { open(stream); } @Override public void setInput(Reader reader) throws XmlPullParserException { throw new XmlPullParserException(E_NOT_SUPPORTED); } @Override public String getInputEncoding() { return null; } @Override public int getColumnNumber() { return -1; } @Override public boolean isEmptyElementTag() { return false; } @Override public boolean isWhitespace() { return false; } @Override public void defineEntityReplacementText(String entityName, String replacementText) throws XmlPullParserException { throw new XmlPullParserException(E_NOT_SUPPORTED); } @Override public String getNamespace(String prefix) { throw new RuntimeException(E_NOT_SUPPORTED); } @Override public Object getProperty(String name) { return null; } @Override public void setProperty(String name, Object value) throws XmlPullParserException { throw new XmlPullParserException(E_NOT_SUPPORTED); } @Override public boolean getFeature(String feature) { return false; } @Override public void setFeature(String name, boolean value) throws XmlPullParserException { throw new XmlPullParserException(E_NOT_SUPPORTED); } private int getAttributeOffset(int index) { if (mEvent != START_TAG) { throw new IndexOutOfBoundsException("Current event is not START_TAG."); } int offset = index * ATTRIBUTE_LENGTH; if (offset >= mAttributes.length) { throw new IndexOutOfBoundsException("Invalid attribute index (" + index + ")."); } return offset; } private int findAttribute(String namespace, String attribute) { if (mStringBlock == null || attribute == null) { return -1; } int name = mStringBlock.find(attribute); if (name == -1) { return -1; } int uri = (namespace != null) ? mStringBlock.find(namespace) : -1; for (int o = 0; o != mAttributes.length; o += ATTRIBUTE_LENGTH) { if (name == mAttributes[o + ATTRIBUTE_IX_NAME] && (uri == -1 || uri == mAttributes[o + ATTRIBUTE_IX_NAMESPACE_URI])) { return o / ATTRIBUTE_LENGTH; } } return -1; } private static String getPreferredString(String stringBlockValue, String resourceMapValue) { String value = stringBlockValue; if (stringBlockValue != null && resourceMapValue != null) { int slashPos = stringBlockValue.lastIndexOf("/"); int colonPos = stringBlockValue.lastIndexOf(":"); // Handle a value with a format of "@yyy/xxx", but avoid "@yyy/zzz:xxx" if (slashPos != -1) { if (colonPos == -1) { String type = stringBlockValue.substring(0, slashPos); value = type + "/" + resourceMapValue; } } else if (! stringBlockValue.equals(resourceMapValue)) { value = resourceMapValue; } } return value; } private void resetEventInfo() { mEvent = -1; mLineNumber = -1; mNameIndex = -1; mNamespaceIndex = -1; mAttributes = null; mIdIndex = -1; mClassIndex = -1; mStyleIndex = -1; } private void doNext() throws IOException { if (mStringBlock == null) { mIn.skipInt(); // XML Chunk AXML Type mIn.skipInt(); // Chunk Size mStringBlock = StringBlock.readWithChunk(mIn); mNamespaces.increaseDepth(); isOperational = true; } if (mEvent == END_DOCUMENT) { return; } int event = mEvent; resetEventInfo(); while (true) { if (m_decreaseDepth) { m_decreaseDepth = false; mNamespaces.decreaseDepth(); } // Fake END_DOCUMENT event. if (event == END_TAG && mNamespaces.getDepth() == 1 && mNamespaces.getCurrentCount() == 0) { mEvent = END_DOCUMENT; break; } // #2070 - Some applications have 2 start namespaces, but only 1 end namespace. if (mIn.remaining() == 0) { LOGGER.warning(String.format("AXML hit unexpected end of file at byte: 0x%X", mIn.position())); mEvent = END_DOCUMENT; break; } int chunkType; int headerSize = 0; if (event == START_DOCUMENT) { // Fake event, see CHUNK_XML_START_TAG handler. chunkType = ARSCHeader.RES_XML_START_ELEMENT_TYPE; } else { chunkType = mIn.readShort(); headerSize = mIn.readShort(); } if (chunkType == ARSCHeader.RES_XML_RESOURCE_MAP_TYPE) { int chunkSize = mIn.readInt(); if (chunkSize < 8 || (chunkSize % 4) != 0) { throw new IOException("Invalid resource ids size (" + chunkSize + ")."); } mResourceIds = mIn.readIntArray(chunkSize / 4 - 2); continue; } if (chunkType < ARSCHeader.RES_XML_FIRST_CHUNK_TYPE || chunkType > ARSCHeader.RES_XML_LAST_CHUNK_TYPE) { int chunkSize = mIn.readInt(); mIn.skipBytes(chunkSize - 8); LOGGER.warning(String.format("Unknown chunk type at: (0x%08x) skipping...", mIn.position())); break; } // Fake START_DOCUMENT event. if (chunkType == ARSCHeader.RES_XML_START_ELEMENT_TYPE && event == -1) { mEvent = START_DOCUMENT; break; } // Read remainder of ResXMLTree_node mIn.skipInt(); // chunkSize mLineNumber = mIn.readInt(); mIn.skipInt(); // Optional XML Comment if (chunkType == ARSCHeader.RES_XML_START_NAMESPACE_TYPE || chunkType == ARSCHeader.RES_XML_END_NAMESPACE_TYPE) { if (chunkType == ARSCHeader.RES_XML_START_NAMESPACE_TYPE) { int prefix = mIn.readInt(); int uri = mIn.readInt(); mNamespaces.push(prefix, uri); } else { mIn.skipInt(); // prefix mIn.skipInt(); // uri mNamespaces.pop(); } // Check for larger header than we read. We know the current header is 0x10 bytes, but some apps // are packed with a larger header of unknown data. if (headerSize > 0x10) { int bytesToSkip = headerSize - 0x10; LOGGER.warning(String.format("AXML header larger than 0x10 bytes, skipping %d bytes.", bytesToSkip)); mIn.skipBytes(bytesToSkip); } continue; } if (chunkType == ARSCHeader.RES_XML_START_ELEMENT_TYPE) { mNamespaceIndex = mIn.readInt(); mNameIndex = mIn.readInt(); mIn.skipShort(); // attributeStart int attributeSize = mIn.readShort(); int attributeCount = mIn.readShort(); mIdIndex = mIn.readShort(); mClassIndex = mIn.readShort(); mStyleIndex = mIn.readShort(); mAttributes = mIn.readIntArray(attributeCount * ATTRIBUTE_LENGTH); for (int i = ATTRIBUTE_IX_VALUE_TYPE; i < mAttributes.length; ) { mAttributes[i] = (mAttributes[i] >>> 24); i += ATTRIBUTE_LENGTH; } int byteAttrSizeRead = (attributeCount * ATTRIBUTE_LENGTH) * 4; int byteAttrSizeReported = (attributeSize * attributeCount); // Check for misleading chunk sizes if (byteAttrSizeRead < byteAttrSizeReported) { int bytesToSkip = byteAttrSizeReported - byteAttrSizeRead; mIn.skipBytes(bytesToSkip); LOGGER.fine("Skipping " + bytesToSkip + " unknown bytes in attributes area."); } mNamespaces.increaseDepth(); mEvent = START_TAG; break; } if (chunkType == ARSCHeader.RES_XML_END_ELEMENT_TYPE) { mNamespaceIndex = mIn.readInt(); mNameIndex = mIn.readInt(); mEvent = END_TAG; m_decreaseDepth = true; break; } if (chunkType == ARSCHeader.RES_XML_CDATA_TYPE) { mNameIndex = mIn.readInt(); mIn.skipInt(); mIn.skipInt(); mEvent = TEXT; break; } } } private void setFirstError(AndrolibException error) { if (mFirstError == null) { mFirstError = error; } } private ExtCountingDataInput mIn; private final ResTable mResTable; private AndrolibException mFirstError; private boolean isOperational = false; private StringBlock mStringBlock; private int[] mResourceIds; private final NamespaceStack mNamespaces = new NamespaceStack(); private boolean m_decreaseDepth; // All values are essentially indices, e.g. mNameIndex is an index of name in mStringBlock. private int mEvent; private int mLineNumber; private int mNameIndex; private int mNamespaceIndex; private int[] mAttributes; private int mIdIndex; private int mClassIndex; private int mStyleIndex; private final static Logger LOGGER = Logger.getLogger(AXmlResourceParser.class.getName()); private static final String E_NOT_SUPPORTED = "Method is not supported."; // ResXMLTree_attribute private static final int ATTRIBUTE_IX_NAMESPACE_URI = 0; // ns private static final int ATTRIBUTE_IX_NAME = 1; // name private static final int ATTRIBUTE_IX_VALUE_STRING = 2; // rawValue private static final int ATTRIBUTE_IX_VALUE_TYPE = 3; // (size/res0/dataType) private static final int ATTRIBUTE_IX_VALUE_DATA = 4; // data private static final int ATTRIBUTE_LENGTH = 5; private static final int PRIVATE_PKG_ID = 0x7F; private static final String ANDROID_RES_NS_AUTO = "http://schemas.android.com/apk/res-auto"; private static final String ANDROID_RES_NS = "http://schemas.android.com/apk/res/android"; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/Res9patchStreamDecoder.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.decoder; import brut.androlib.exceptions.AndrolibException; import brut.androlib.exceptions.CantFind9PatchChunkException; import brut.androlib.res.data.ninepatch.NinePatchData; import brut.androlib.res.data.ninepatch.OpticalInset; import brut.util.ExtDataInput; import org.apache.commons.io.IOUtils; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.io.*; public class Res9patchStreamDecoder implements ResStreamDecoder { @Override public void decode(InputStream in, OutputStream out) throws AndrolibException { try { byte[] data = IOUtils.toByteArray(in); if (data.length == 0) { return; } BufferedImage im = ImageIO.read(new ByteArrayInputStream(data)); int w = im.getWidth(), h = im.getHeight(); BufferedImage im2 = new BufferedImage(w + 2, h + 2, BufferedImage.TYPE_INT_ARGB); if (im.getType() == BufferedImage.TYPE_CUSTOM) { //TODO: Ensure this is gray + alpha case? Raster srcRaster = im.getRaster(); WritableRaster dstRaster = im2.getRaster(); int[] gray = null, alpha = null; for (int y = 0; y < im.getHeight(); y++) { gray = srcRaster.getSamples(0, y, w, 1, 0, gray); alpha = srcRaster.getSamples(0, y, w, 1, 1, alpha); dstRaster.setSamples(1, y + 1, w, 1, 0, gray); dstRaster.setSamples(1, y + 1, w, 1, 1, gray); dstRaster.setSamples(1, y + 1, w, 1, 2, gray); dstRaster.setSamples(1, y + 1, w, 1, 3, alpha); } } else { im2.createGraphics().drawImage(im, 1, 1, w, h, null); } NinePatchData np = getNinePatch(data); drawHLine(im2, h + 1, np.padLeft + 1, w - np.padRight); drawVLine(im2, w + 1, np.padTop + 1, h - np.padBottom); int[] xDivs = np.xDivs; if (xDivs.length == 0) { drawHLine(im2, 0, 1, w); } else { for (int i = 0; i < xDivs.length; i += 2) { drawHLine(im2, 0, xDivs[i] + 1, xDivs[i + 1]); } } int[] yDivs = np.yDivs; if (yDivs.length == 0) { drawVLine(im2, 0, 1, h); } else { for (int i = 0; i < yDivs.length; i += 2) { drawVLine(im2, 0, yDivs[i] + 1, yDivs[i + 1]); } } // Some images additionally use Optical Bounds // https://developer.android.com/about/versions/android-4.3.html#OpticalBounds try { OpticalInset oi = getOpticalInset(data); for (int i = 0; i < oi.layoutBoundsLeft; i++) { int x = 1 + i; im2.setRGB(x, h + 1, OI_COLOR); } for (int i = 0; i < oi.layoutBoundsRight; i++) { int x = w - i; im2.setRGB(x, h + 1, OI_COLOR); } for (int i = 0; i < oi.layoutBoundsTop; i++) { int y = 1 + i; im2.setRGB(w + 1, y, OI_COLOR); } for (int i = 0; i < oi.layoutBoundsBottom; i++) { int y = h - i; im2.setRGB(w + 1, y, OI_COLOR); } } catch (CantFind9PatchChunkException t) { // This chunk might not exist } ImageIO.write(im2, "png", out); } catch (IOException | NullPointerException ex) { // In my case this was triggered because a .png file was // containing a html document instead of an image. // This could be more verbose and try to MIME ? throw new AndrolibException(ex); } } private NinePatchData getNinePatch(byte[] data) throws AndrolibException, IOException { ExtDataInput di = new ExtDataInput(new ByteArrayInputStream(data)); find9patchChunk(di, NP_CHUNK_TYPE); return NinePatchData.decode(di); } private OpticalInset getOpticalInset(byte[] data) throws AndrolibException, IOException { ExtDataInput di = new ExtDataInput(new ByteArrayInputStream(data)); find9patchChunk(di, OI_CHUNK_TYPE); return OpticalInset.decode(di); } private void find9patchChunk(DataInput di, int magic) throws AndrolibException, IOException { di.skipBytes(8); while (true) { int size; try { size = di.readInt(); } catch (IOException ex) { throw new CantFind9PatchChunkException("Cant find nine patch chunk", ex); } if (di.readInt() == magic) { return; } di.skipBytes(size + 4); } } private void drawHLine(BufferedImage im, int y, int x1, int x2) { for (int x = x1; x <= x2; x++) { im.setRGB(x, y, NP_COLOR); } } private void drawVLine(BufferedImage im, int x, int y1, int y2) { for (int y = y1; y <= y2; y++) { im.setRGB(x, y, NP_COLOR); } } private static final int NP_CHUNK_TYPE = 0x6e705463; // npTc private static final int OI_CHUNK_TYPE = 0x6e704c62; // npLb private static final int NP_COLOR = 0xff000000; private static final int OI_COLOR = 0xffff0000; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/ResFileDecoder.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.decoder; import brut.androlib.exceptions.AndrolibException; import brut.androlib.exceptions.CantFind9PatchChunkException; import brut.androlib.exceptions.RawXmlEncounteredException; import brut.androlib.res.data.ResResource; import brut.androlib.res.data.value.ResBoolValue; import brut.androlib.res.data.value.ResFileValue; import brut.directory.DirUtil; import brut.directory.Directory; import brut.directory.DirectoryException; import java.io.*; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public class ResFileDecoder { private final ResStreamDecoderContainer mDecoders; public ResFileDecoder(ResStreamDecoderContainer decoders) { this.mDecoders = decoders; } public void decode(ResResource res, Directory inDir, Directory outDir, Map<String, String> resFileMapping) throws AndrolibException { ResFileValue fileValue = (ResFileValue) res.getValue(); String inFilePath = fileValue.toString(); String inFileName = fileValue.getStrippedPath(); String outResName = res.getFilePath(); String typeName = res.getResSpec().getType().getName(); String ext = null; String outFileName; int extPos = inFileName.lastIndexOf("."); if (extPos == -1) { outFileName = outResName; } else { ext = inFileName.substring(extPos).toLowerCase(); outFileName = outResName + ext; } String outFilePath = "res/" + outFileName; if (!inFilePath.equals(outFilePath)) { resFileMapping.put(inFilePath, outFilePath); } LOGGER.fine("Decoding file " + inFilePath + " to " + outFilePath); try { if (typeName.equals("raw")) { decode(inDir, inFilePath, outDir, outFileName, "raw"); return; } if (typeName.equals("font") && !".xml".equals(ext)) { decode(inDir, inFilePath, outDir, outFileName, "raw"); return; } if (typeName.equals("drawable") || typeName.equals("mipmap")) { if (inFileName.toLowerCase().endsWith(".9" + ext)) { outFileName = outResName + ".9" + ext; // check for htc .r.9.png if (inFileName.toLowerCase().endsWith(".r.9" + ext)) { outFileName = outResName + ".r.9" + ext; } // check for raw 9patch images for (String extension : RAW_9PATCH_IMAGE_EXTENSIONS) { if (inFileName.toLowerCase().endsWith("." + extension)) { copyRaw(inDir, outDir, inFilePath, outFileName); return; } } // check for xml 9 patches which are just xml files if (inFileName.toLowerCase().endsWith(".xml")) { decode(inDir, inFilePath, outDir, outFileName, "xml"); return; } try { decode(inDir, inFilePath, outDir, outFileName, "9patch"); return; } catch (CantFind9PatchChunkException ex) { LOGGER.log(Level.WARNING, String.format( "Cant find 9patch chunk in file: \"%s\". Renaming it to *.png.", inFileName ), ex); outDir.removeFile(outFileName); outFileName = outResName + ext; } } // check for raw image for (String extension : RAW_IMAGE_EXTENSIONS) { if (inFileName.toLowerCase().endsWith("." + extension)) { copyRaw(inDir, outDir, inFilePath, outFileName); return; } } if (!".xml".equals(ext)) { decode(inDir, inFilePath, outDir, outFileName, "raw"); return; } } decode(inDir, inFilePath, outDir, outFileName, "xml"); } catch (RawXmlEncounteredException ex) { // If we got an error to decode XML, lets assume the file is in raw format. // This is a large assumption, that might increase runtime, but will save us for situations where // XSD files are AXML`d on aapt1, but left in plaintext in aapt2. decode(inDir, inFilePath, outDir, outFileName, "raw"); } catch (AndrolibException ex) { LOGGER.log(Level.SEVERE, String.format( "Could not decode file, replacing by FALSE value: %s", inFileName), ex); res.replace(new ResBoolValue(false, 0, null)); } } public void decode(Directory inDir, String inFileName, Directory outDir, String outFileName, String decoder) throws AndrolibException { try ( InputStream in = inDir.getFileInput(inFileName); OutputStream out = outDir.getFileOutput(outFileName) ) { mDecoders.decode(in, out, decoder); } catch (DirectoryException | IOException ex) { throw new AndrolibException(ex); } } public void copyRaw(Directory inDir, Directory outDir, String inFilename, String outFilename) throws AndrolibException { try { DirUtil.copyToDir(inDir, outDir, inFilename, outFilename); } catch (DirectoryException ex) { throw new AndrolibException(ex); } } private final static Logger LOGGER = Logger.getLogger(ResFileDecoder.class.getName()); private final static String[] RAW_IMAGE_EXTENSIONS = new String[] { "m4a", // apple "qmg", // samsung }; private final static String[] RAW_9PATCH_IMAGE_EXTENSIONS = new String[] { "qmg", // samsung "spi", // samsung }; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/ResRawStreamDecoder.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.decoder; import brut.androlib.exceptions.AndrolibException; import org.apache.commons.io.IOUtils; import java.io.*; public class ResRawStreamDecoder implements ResStreamDecoder { @Override public void decode(InputStream in, OutputStream out) throws AndrolibException { try { IOUtils.copy(in, out); } catch (IOException ex) { throw new AndrolibException("Could not decode raw stream", ex); } } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/ResStreamDecoder.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.decoder; import brut.androlib.exceptions.AndrolibException; import java.io.*; public interface ResStreamDecoder { void decode(InputStream in, OutputStream out) throws AndrolibException; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/ResStreamDecoderContainer.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.decoder; import brut.androlib.exceptions.AndrolibException; import java.io.*; import java.util.*; public class ResStreamDecoderContainer { private final Map<String, ResStreamDecoder> mDecoders = new HashMap<>(); public void decode(InputStream in, OutputStream out, String decoderName) throws AndrolibException { getDecoder(decoderName).decode(in, out); } public ResStreamDecoder getDecoder(String name) throws AndrolibException { ResStreamDecoder decoder = mDecoders.get(name); if (decoder == null) { throw new AndrolibException("Undefined decoder: " + name); } return decoder; } public void setDecoder(String name, ResStreamDecoder decoder) { mDecoders.put(name, decoder); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/StringBlock.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.decoder; import brut.androlib.res.data.arsc.ARSCHeader; import brut.androlib.res.xml.ResXmlEncoders; import brut.util.ExtCountingDataInput; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; public class StringBlock { public static StringBlock readWithChunk(ExtCountingDataInput reader) throws IOException { int startPosition = reader.position(); reader.skipCheckShort(ARSCHeader.RES_STRING_POOL_TYPE); int headerSize = reader.readShort(); int chunkSize = reader.readInt(); return readWithoutChunk(reader, startPosition, headerSize, chunkSize); } public static StringBlock readWithoutChunk(ExtCountingDataInput reader, int startPosition, int headerSize, int chunkSize) throws IOException { // ResStringPool_header int stringCount = reader.readInt(); int styleCount = reader.readInt(); int flags = reader.readInt(); int stringsOffset = reader.readInt(); int stylesOffset = reader.readInt(); // For some applications they pack the StringBlock header with more unused data at end. if (headerSize > STRING_BLOCK_HEADER_SIZE) { reader.skipBytes(headerSize - STRING_BLOCK_HEADER_SIZE); } StringBlock block = new StringBlock(); block.mIsUtf8 = (flags & UTF8_FLAG) != 0; block.mStringOffsets = reader.readSafeIntArray(stringCount, startPosition + stringsOffset); if (styleCount != 0) { block.mStyleOffsets = reader.readSafeIntArray(styleCount, startPosition + stylesOffset); } // #3236 - Some applications give a style offset, but have 0 styles. Make this check more robust. boolean hasStyles = stylesOffset != 0 && styleCount != 0; int size = chunkSize - stringsOffset; // If we have both strings and even just a lying style offset - lets calculate the size of the strings without // accidentally parsing all the styles. if (styleCount > 0) { size = stylesOffset - stringsOffset; } block.mStrings = new byte[size]; reader.readFully(block.mStrings); if (hasStyles) { size = chunkSize - stylesOffset; block.mStyles = reader.readIntArray(size / 4); } // In case we aren't 4 byte aligned we need to skip the remaining bytes. int remaining = size % 4; if (remaining >= 1) { while (remaining-- > 0) { reader.readByte(); } } return block; } /** * Returns raw string (without any styling information) at specified index. * @param index int * @return String */ public String getString(int index) { if (index < 0 || mStringOffsets == null || index >= mStringOffsets.length) { return null; } int offset = mStringOffsets[index]; int length; int[] val; if (mIsUtf8) { val = getUtf8(mStrings, offset); offset = val[0]; } else { val = getUtf16(mStrings, offset); offset += val[0]; } length = val[1]; return decodeString(offset, length); } /** * @param index Location (index) of string to process to HTML * @return String Returns string with style tags (html-like). */ public String getHTML(int index) { String text = getString(index); if (text == null) { return null; } int[] style = getStyle(index); if (style == null) { return ResXmlEncoders.escapeXmlChars(text); } // If the returned style is further in string, than string length. Lets skip it. if (style[1] > text.length()) { return ResXmlEncoders.escapeXmlChars(text); } // Convert styles to spans List<StyledString.Span> spans = new ArrayList<>(style.length / 3); for (int i = 0; i < style.length; i += 3) { spans.add(new StyledString.Span(getString(style[i]), style[i + 1], style[i + 2])); } Collections.sort(spans); StyledString styledString = new StyledString(text, spans); return styledString.toString(); } /** * Finds index of the string. Returns -1 if the string was not found. * * @param string String to index location of * @return int (Returns -1 if not found) */ public int find(String string) { if (string == null) { return -1; } for (int i = 0; i != mStringOffsets.length; ++i) { int offset = mStringOffsets[i]; int length = getShort(mStrings, offset); if (length != string.length()) { continue; } int j = 0; for (; j != length; ++j) { offset += 2; if (string.charAt(j) != getShort(mStrings, offset)) { break; } } if (j == length) { return i; } } return -1; } private StringBlock() { } @VisibleForTesting StringBlock(byte[] strings, boolean isUTF8) { mStrings = strings; mIsUtf8 = isUTF8; } /** * Returns style information - array of int triplets, where in each triplet: * * first int is index of tag name ('b','i', etc.) * second int is tag * start index in string * third int is tag end index in string */ private int[] getStyle(int index) { if (mStyleOffsets == null || mStyles == null|| index >= mStyleOffsets.length) { return null; } int offset = mStyleOffsets[index] / 4; int count = 0; int[] style; for (int i = offset; i < mStyles.length; ++i) { if (mStyles[i] == -1) { break; } count += 1; } if (count == 0 || (count % 3) != 0) { return null; } style = new int[count]; for (int i = offset, j = 0; i < mStyles.length;) { if (mStyles[i] == -1) { break; } style[j++] = mStyles[i++]; } return style; } @VisibleForTesting String decodeString(int offset, int length) { try { final ByteBuffer wrappedBuffer = ByteBuffer.wrap(mStrings, offset, length); return (mIsUtf8 ? UTF8_DECODER : UTF16LE_DECODER).decode(wrappedBuffer).toString(); } catch (CharacterCodingException ex) { if (!mIsUtf8) { LOGGER.warning("Failed to decode a string at offset " + offset + " of length " + length); return null; } } catch (IndexOutOfBoundsException ex) { if (!mIsUtf8) { LOGGER.warning("String extends outside of pool at " + offset + " of length " + length); return null; } } try { final ByteBuffer wrappedBufferRetry = ByteBuffer.wrap(mStrings, offset, length); // in some places, Android uses 3-byte UTF-8 sequences instead of 4-bytes. // If decoding failed, we try to use CESU-8 decoder, which is closer to what Android actually uses. return CESU8_DECODER.decode(wrappedBufferRetry).toString(); } catch (CharacterCodingException e) { LOGGER.warning("Failed to decode a string with CESU-8 decoder."); return null; } } private static int getShort(byte[] array, int offset) { return (array[offset + 1] & 0xff) << 8 | array[offset] & 0xff; } private static int[] getUtf8(byte[] array, int offset) { int val = array[offset]; int length; // We skip the utf16 length of the string if ((val & 0x80) != 0) { offset += 2; } else { offset += 1; } // And we read only the utf-8 encoded length of the string val = array[offset]; offset += 1; if ((val & 0x80) != 0) { int low = (array[offset] & 0xFF); length = ((val & 0x7F) << 8) + low; offset += 1; } else { length = val; } return new int[] { offset, length}; } private static int[] getUtf16(byte[] array, int offset) { int val = ((array[offset + 1] & 0xFF) << 8 | array[offset] & 0xFF); if ((val & 0x8000) != 0) { int high = (array[offset + 3] & 0xFF) << 8; int low = (array[offset + 2] & 0xFF); int len_value = ((val & 0x7FFF) << 16) + (high + low); return new int[] {4, len_value * 2}; } return new int[] {2, val * 2}; } private int[] mStringOffsets; private byte[] mStrings; private int[] mStyleOffsets; private int[] mStyles; private boolean mIsUtf8; private final CharsetDecoder UTF16LE_DECODER = StandardCharsets.UTF_16LE.newDecoder(); private final CharsetDecoder UTF8_DECODER = StandardCharsets.UTF_8.newDecoder(); private final CharsetDecoder CESU8_DECODER = Charset.forName("CESU8").newDecoder(); private static final Logger LOGGER = Logger.getLogger(StringBlock.class.getName()); private static final int UTF8_FLAG = 0x00000100; private static final int STRING_BLOCK_HEADER_SIZE = 28; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/StyledString.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.decoder; import brut.androlib.res.xml.ResXmlEncoders; import com.google.common.base.Splitter; import com.google.common.base.Splitter.MapSplitter; import com.google.common.collect.Iterators; import com.google.common.collect.PeekingIterator; import java.util.List; import java.util.Map; import java.util.logging.Logger; public class StyledString { private final String mText; private final List<Span> mSpans; public StyledString(String text, List<Span> spans) { this.mText = text; this.mSpans = spans; } String getText() { return mText; } List<Span> getSpans() { return mSpans; } @Override public String toString() { return new Decoder().decode(this); } public static class Span implements Comparable<Span> { private static final MapSplitter ATTRIBUTES_SPLITTER = Splitter.on(';').omitEmptyStrings().withKeyValueSeparator(Splitter.on('=').limit(2)); private final String tag; private final int firstChar; private final int lastChar; public Span(String tag, int firstChar, int lastChar) { this.tag = tag; this.firstChar = firstChar; this.lastChar = lastChar; } public String getTag() { return tag; } public int getFirstChar() { return firstChar; } public int getLastChar() { return lastChar; } public String getName() { int separatorIdx = tag.indexOf(';'); return separatorIdx == -1 ? tag : tag.substring(0, separatorIdx); } public Map<String, String> getAttributes() { int separatorIdx = tag.indexOf(';'); return separatorIdx == -1 ? null : ATTRIBUTES_SPLITTER.split( tag.substring(separatorIdx + 1, tag.endsWith(";") ? tag.length() - 1 : tag.length()) ); } @Override public int compareTo(Span o) { int res = Integer.compare(firstChar, o.firstChar); if (res != 0) { return res; } res = Integer.compare(lastChar, o.lastChar); if (res != 0) { return -res; } return -tag.compareTo(o.tag); } } private static class Decoder { private String text; private StringBuilder xmlValue; private int lastOffset; String decode(StyledString styledString) { text = styledString.getText(); xmlValue = new StringBuilder(text.length() * 2); lastOffset = 0; // recurse top-level tags PeekingIterator<Span> it = Iterators.peekingIterator(styledString.getSpans().iterator()); while (it.hasNext()) { decodeIterate(it); } // write the remaining encoded raw text if (lastOffset < text.length()) { xmlValue.append(ResXmlEncoders.escapeXmlChars(text.substring(lastOffset))); } return xmlValue.toString(); } private void decodeIterate(PeekingIterator<Span> it) { Span span = it.next(); String name = span.getName(); Map<String, String> attributes = span.getAttributes(); int spanStart = span.getFirstChar(); int spanEnd = span.getLastChar() + 1; // write encoded raw text preceding the opening tag if (spanStart > lastOffset) { xmlValue.append(ResXmlEncoders.escapeXmlChars(text.substring(lastOffset, spanStart))); } lastOffset = spanStart; // write opening tag xmlValue.append('<').append(name); if (attributes != null) { for (Map.Entry<String, String> attrEntry : attributes.entrySet()) { xmlValue.append(' ').append(attrEntry.getKey()).append("=\"") .append(ResXmlEncoders.escapeXmlChars(attrEntry.getValue())).append('"'); } } // if an opening tag is followed by a matching closing tag, write as an empty-element tag if (spanStart == spanEnd) { xmlValue.append("/>"); return; } xmlValue.append('>'); // recurse nested tags while (it.hasNext() && it.peek().getFirstChar() < spanEnd) { decodeIterate(it); } // write encoded raw text preceding the closing tag if (spanEnd > lastOffset && text.length() >= spanEnd) { xmlValue.append(ResXmlEncoders.escapeXmlChars(text.substring(lastOffset, spanEnd))); } else if (text.length() >= lastOffset && text.length() < spanEnd) { LOGGER.warning("Span (" + name + ") exceeds text length " + text.length()); xmlValue.append(ResXmlEncoders.escapeXmlChars(text.substring(lastOffset))); } lastOffset = spanEnd; // write closing tag xmlValue.append("</").append(name).append('>'); } } private static final Logger LOGGER = Logger.getLogger(StyledString.class.getName()); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/XmlPullStreamDecoder.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.decoder; import brut.androlib.exceptions.AndrolibException; import brut.androlib.exceptions.AXmlDecodingException; import brut.androlib.exceptions.RawXmlEncounteredException; import brut.androlib.res.data.ResTable; import brut.androlib.res.util.ExtXmlSerializer; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.wrapper.XmlPullParserWrapper; import org.xmlpull.v1.wrapper.XmlPullWrapperFactory; import org.xmlpull.v1.wrapper.XmlSerializerWrapper; import org.xmlpull.v1.wrapper.classic.StaticXmlSerializerWrapper; import java.io.*; public class XmlPullStreamDecoder implements ResStreamDecoder { public XmlPullStreamDecoder(AXmlResourceParser parser, ExtXmlSerializer serializer) { this.mParser = parser; this.mSerial = serializer; } @Override public void decode(InputStream in, OutputStream out) throws AndrolibException { try { XmlPullWrapperFactory factory = XmlPullWrapperFactory.newInstance(); XmlPullParserWrapper par = factory.newPullParserWrapper(mParser); final ResTable resTable = mParser.getResTable(); XmlSerializerWrapper ser = new StaticXmlSerializerWrapper(mSerial, factory) { boolean hideSdkInfo = false; boolean hidePackageInfo = false; @Override public void event(XmlPullParser pp) throws XmlPullParserException, IOException { int type = pp.getEventType(); if (type == XmlPullParser.START_TAG) { if ("manifest".equalsIgnoreCase(pp.getName())) { try { hidePackageInfo = parseManifest(pp); } catch (AndrolibException ignored) {} } else if ("uses-sdk".equalsIgnoreCase(pp.getName())) { try { hideSdkInfo = parseAttr(pp); if (hideSdkInfo) { return; } } catch (AndrolibException ignored) {} } } else if (hideSdkInfo && type == XmlPullParser.END_TAG && "uses-sdk".equalsIgnoreCase(pp.getName())) { return; } else if (hidePackageInfo && type == XmlPullParser.END_TAG && "manifest".equalsIgnoreCase(pp.getName())) { super.event(pp); return; } super.event(pp); } private boolean parseManifest(XmlPullParser pp) throws AndrolibException { String attr_name; // read <manifest> for package: for (int i = 0; i < pp.getAttributeCount(); i++) { attr_name = pp.getAttributeName(i); if (attr_name.equalsIgnoreCase(("package"))) { resTable.setPackageRenamed(pp.getAttributeValue(i)); } else if (attr_name.equalsIgnoreCase("versionCode")) { resTable.setVersionCode(pp.getAttributeValue(i)); } else if (attr_name.equalsIgnoreCase("versionName")) { resTable.setVersionName(pp.getAttributeValue(i)); } } return true; } private boolean parseAttr(XmlPullParser pp) throws AndrolibException { for (int i = 0; i < pp.getAttributeCount(); i++) { final String a_ns = "http://schemas.android.com/apk/res/android"; String ns = pp.getAttributeNamespace(i); if (a_ns.equalsIgnoreCase(ns)) { String name = pp.getAttributeName(i); String value = pp.getAttributeValue(i); if (name != null && value != null) { if (name.equalsIgnoreCase("minSdkVersion") || name.equalsIgnoreCase("targetSdkVersion") || name.equalsIgnoreCase("maxSdkVersion") || name.equalsIgnoreCase("compileSdkVersion")) { resTable.addSdkInfo(name, value); } else { resTable.clearSdkInfo(); return false; // Found unknown flags } } } else { resTable.clearSdkInfo(); if (i >= pp.getAttributeCount()) { return false; // Found unknown flags } } } return ! resTable.getAnalysisMode(); } }; par.setInput(in, null); ser.setOutput(out, null); while (par.nextToken() != XmlPullParser.END_DOCUMENT) { ser.event(par); } ser.flush(); } catch (XmlPullParserException ex) { throw new AXmlDecodingException("Could not decode XML", ex); } catch (IOException ex) { throw new RawXmlEncounteredException("Could not decode XML", ex); } } public void decodeManifest(InputStream in, OutputStream out) throws AndrolibException { decode(in, out); } private final AXmlResourceParser mParser; private final ExtXmlSerializer mSerial; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/util/ExtMXSerializer.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.util; import org.xmlpull.renamed.MXSerializer; import java.io.*; public class ExtMXSerializer extends MXSerializer implements ExtXmlSerializer { @Override public void startDocument(String encoding, Boolean standalone) throws IOException, IllegalArgumentException, IllegalStateException { super.startDocument(encoding != null ? encoding : mDefaultEncoding, standalone); this.newLine(); } @Override protected void writeAttributeValue(String value, Writer out) throws IOException { if (mIsDisabledAttrEscape) { out.write(value == null ? "" : value); return; } super.writeAttributeValue(value, out); } @Override public void setOutput(OutputStream os, String encoding) throws IOException { super.setOutput(os, encoding != null ? encoding : mDefaultEncoding); } @Override public Object getProperty(String name) throws IllegalArgumentException { if (PROPERTY_DEFAULT_ENCODING.equals(name)) { return mDefaultEncoding; } return super.getProperty(name); } @Override public void setProperty(String name, Object value) throws IllegalArgumentException, IllegalStateException { if (PROPERTY_DEFAULT_ENCODING.equals(name)) { mDefaultEncoding = (String) value; } else { super.setProperty(name, value); } } @Override public ExtXmlSerializer newLine() throws IOException { super.out.write(lineSeparator); return this; } @Override public void setDisabledAttrEscape(boolean disabled) { mIsDisabledAttrEscape = disabled; } private String mDefaultEncoding; private boolean mIsDisabledAttrEscape = false; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/util/ExtXmlSerializer.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.util; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; public interface ExtXmlSerializer extends XmlSerializer { ExtXmlSerializer newLine() throws IOException; void setDisabledAttrEscape(boolean disabled); String PROPERTY_SERIALIZER_INDENTATION = "http://xmlpull.org/v1/doc/properties.html#serializer-indentation"; String PROPERTY_SERIALIZER_LINE_SEPARATOR = "http://xmlpull.org/v1/doc/properties.html#serializer-line-separator"; String PROPERTY_DEFAULT_ENCODING = "DEFAULT_ENCODING"; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/xml/ResValuesXmlSerializable.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.xml; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.ResResource; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; public interface ResValuesXmlSerializable { void serializeToResValuesXml(XmlSerializer serializer, ResResource res) throws IOException, AndrolibException; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/xml/ResXmlEncodable.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.xml; import brut.androlib.exceptions.AndrolibException; public interface ResXmlEncodable { String encodeAsResXmlAttr() throws AndrolibException; String encodeAsResXmlValue() throws AndrolibException; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/xml/ResXmlEncoders.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.xml; import brut.util.Duo; import org.apache.commons.lang3.StringUtils; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; public final class ResXmlEncoders { public static String escapeXmlChars(String str) { return StringUtils.replace(StringUtils.replace(str, "&", "&amp;"), "<", "&lt;"); } public static String encodeAsResXmlAttr(String str) { if (str == null || str.isEmpty()) { return str; } char[] chars = str.toCharArray(); StringBuilder out = new StringBuilder(str.length() + 10); switch (chars[0]) { case '#': case '@': case '?': out.append('\\'); } for (char c : chars) { switch (c) { case '\\': out.append('\\'); break; case '"': out.append("&quot;"); continue; case '\n': out.append("\\n"); continue; default: if (!isPrintableChar(c)) { out.append(String.format("\\u%04x", (int) c)); continue; } } out.append(c); } return out.toString(); } public static String encodeAsXmlValue(String str) { if (str == null || str.isEmpty()) { return str; } char[] chars = str.toCharArray(); StringBuilder out = new StringBuilder(str.length() + 10); switch (chars[0]) { case '#': case '@': case '?': out.append('\\'); } boolean isInStyleTag = false; int startPos = 0; boolean enclose = false; boolean wasSpace = true; for (char c : chars) { if (isInStyleTag) { if (c == '>') { isInStyleTag = false; startPos = out.length() + 1; enclose = false; } } else if (c == ' ') { if (wasSpace) { enclose = true; } wasSpace = true; } else { wasSpace = false; switch (c) { case '\\': case '"': out.append('\\'); break; case '\'': case '\n': enclose = true; break; case '<': isInStyleTag = true; if (enclose) { out.insert(startPos, '"').append('"'); } break; default: if (!isPrintableChar(c)) { // let's not write trailing \u0000 if we are at end of string if ((out.length() + 1) == str.length() && c == '\u0000') { continue; } out.append(String.format("\\u%04x", (int) c)); continue; } } } out.append(c); } if (enclose || wasSpace) { out.insert(startPos, '"').append('"'); } return out.toString(); } public static boolean hasMultipleNonPositionalSubstitutions(String str) { Duo<List<Integer>, List<Integer>> tuple = findSubstitutions(str, 4); return ! tuple.m1.isEmpty() && tuple.m1.size() + tuple.m2.size() > 1; } public static String enumerateNonPositionalSubstitutionsIfRequired(String str) { Duo<List<Integer>, List<Integer>> tuple = findSubstitutions(str, 4); if (tuple.m1.isEmpty() || tuple.m1.size() + tuple.m2.size() < 2) { return str; } List<Integer> subs = tuple.m1; StringBuilder out = new StringBuilder(); int pos = 0; int count = 0; for (Integer sub : subs) { out.append(str, pos, ++sub).append(++count).append('$'); pos = sub; } out.append(str.substring(pos)); return out.toString(); } /** * It returns a tuple of: * - a list of offsets of non-positional substitutions. non-pos is defined as any "%" which isn't "%%" nor "%\d+\$" * - a list of offsets of positional substitutions */ private static Duo<List<Integer>, List<Integer>> findSubstitutions(String str, int nonPosMax) { if (nonPosMax == -1) { nonPosMax = Integer.MAX_VALUE; } int pos; int pos2 = 0; List<Integer> nonPositional = new ArrayList<>(); List<Integer> positional = new ArrayList<>(); if (str == null) { return new Duo<>(nonPositional, positional); } int length = str.length(); while ((pos = str.indexOf('%', pos2)) != -1) { pos2 = pos + 1; if (pos2 == length) { nonPositional.add(pos); break; } char c = str.charAt(pos2++); if (c == '%') { continue; } if (c >= '0' && c <= '9' && pos2 < length) { while ((c = str.charAt(pos2++)) >= '0' && c <= '9' && pos2 < length); if (c == '$') { positional.add(pos); continue; } } nonPositional.add(pos); if (nonPositional.size() >= nonPosMax) { break; } } return new Duo<>(nonPositional, positional); } private static boolean isPrintableChar(char c) { Character.UnicodeBlock block = Character.UnicodeBlock.of(c); return !Character.isISOControl(c) && c != KeyEvent.CHAR_UNDEFINED && block != null && block != Character.UnicodeBlock.SPECIALS; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/xml/ResXmlPatcher.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.xml; import brut.androlib.exceptions.AndrolibException; import org.w3c.dom.*; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; 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 javax.xml.xpath.*; import java.io.*; import java.util.logging.Logger; public final class ResXmlPatcher { /** * Removes "debug" tag from file * * @param file AndroidManifest file * @throws AndrolibException Error reading Manifest file */ public static void removeApplicationDebugTag(File file) throws AndrolibException { if (file.exists()) { try { Document doc = loadDocument(file); Node application = doc.getElementsByTagName("application").item(0); // load attr NamedNodeMap attr = application.getAttributes(); Node debugAttr = attr.getNamedItem("android:debuggable"); // remove application:debuggable if (debugAttr != null) { attr.removeNamedItem("android:debuggable"); } saveDocument(file, doc); } catch (SAXException | ParserConfigurationException | IOException | TransformerException ignored) { } } } /** * Sets "debug" tag in the file to true * * @param file AndroidManifest file */ public static void setApplicationDebugTagTrue(File file) { if (file.exists()) { try { Document doc = loadDocument(file); Node application = doc.getElementsByTagName("application").item(0); // load attr NamedNodeMap attr = application.getAttributes(); Node debugAttr = attr.getNamedItem("android:debuggable"); if (debugAttr == null) { debugAttr = doc.createAttribute("android:debuggable"); attr.setNamedItem(debugAttr); } // set application:debuggable to 'true debugAttr.setNodeValue("true"); saveDocument(file, doc); } catch (SAXException | ParserConfigurationException | IOException | TransformerException ignored) { } } } /** * Sets the value of the network security config in the AndroidManifest file * * @param file AndroidManifest file */ public static void setNetworkSecurityConfig(File file) { if (file.exists()) { try { Document doc = loadDocument(file); Node application = doc.getElementsByTagName("application").item(0); // load attr NamedNodeMap attr = application.getAttributes(); Node netSecConfAttr = attr.getNamedItem("android:networkSecurityConfig"); if (netSecConfAttr == null) { // there is not an already existing network security configuration netSecConfAttr = doc.createAttribute("android:networkSecurityConfig"); attr.setNamedItem(netSecConfAttr); } // whether it already existed or it was created now set it to the proper value netSecConfAttr.setNodeValue("@xml/network_security_config"); saveDocument(file, doc); } catch (SAXException | ParserConfigurationException | IOException | TransformerException ignored) { } } } /** * Creates a modified network security config file that is more permissive * * @param file network security config file * @throws TransformerException XML file could not be edited * @throws IOException XML file could not be located * @throws SAXException XML file could not be read * @throws ParserConfigurationException XML nodes could be written */ public static void modNetworkSecurityConfig(File file) throws ParserConfigurationException, TransformerException, IOException, SAXException { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element root = document.createElement("network-security-config"); document.appendChild(root); Element baseConfig = document.createElement("base-config"); root.appendChild(baseConfig); Element trustAnchors = document.createElement("trust-anchors"); baseConfig.appendChild(trustAnchors); Element certSystem = document.createElement("certificates"); Attr attrSystem = document.createAttribute("src"); attrSystem.setValue("system"); certSystem.setAttributeNode(attrSystem); trustAnchors.appendChild(certSystem); Element certUser = document.createElement("certificates"); Attr attrUser = document.createAttribute("src"); attrUser.setValue("user"); certUser.setAttributeNode(attrUser); trustAnchors.appendChild(certUser); saveDocument(file, document); } /** * Any @string reference in a provider value in AndroidManifest.xml will break on * build, thus preventing the application from installing. This is from a bug/error * in AOSP where public resources cannot be part of an authorities attribute within * a provider tag. * <p> * This finds any reference and replaces it with the literal value found in the * res/values/strings.xml file. * * @param file File for AndroidManifest.xml */ public static void fixingPublicAttrsInProviderAttributes(File file) { boolean saved = false; if (file.exists()) { try { Document doc = loadDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xPath.compile("/manifest/application/provider"); Object result = expression.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); NamedNodeMap attrs = node.getAttributes(); Node provider = attrs.getNamedItem("android:authorities"); if (provider != null) { saved = isSaved(file, saved, provider); } } // android:scheme xPath = XPathFactory.newInstance().newXPath(); expression = xPath.compile("/manifest/application/activity/intent-filter/data"); result = expression.evaluate(doc, XPathConstants.NODESET); nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); NamedNodeMap attrs = node.getAttributes(); Node provider = attrs.getNamedItem("android:scheme"); if (provider != null) { saved = isSaved(file, saved, provider); } } if (saved) { saveDocument(file, doc); } } catch (SAXException | ParserConfigurationException | IOException | XPathExpressionException | TransformerException ignored) { } } } /** * Checks if the replacement was properly made to a node. * * @param file File we are searching for value * @param saved boolean on whether we need to save * @param provider Node we are attempting to replace * @return boolean */ private static boolean isSaved(File file, boolean saved, Node provider) { String reference = provider.getNodeValue(); String replacement = pullValueFromStrings(file.getParentFile(), reference); if (replacement != null) { provider.setNodeValue(replacement); saved = true; } return saved; } /** * Finds key in strings.xml file and returns text value * * @param directory Root directory of apk * @param key String reference (ie @string/foo) * @return String|null */ public static String pullValueFromStrings(File directory, String key) { if (key == null || ! key.contains("@")) { return null; } File file = new File(directory, "/res/values/strings.xml"); key = key.replace("@string/", ""); if (file.exists()) { try { Document doc = loadDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xPath.compile("/resources/string[@name=" + '"' + key + "\"]/text()"); Object result = expression.evaluate(doc, XPathConstants.STRING); if (result != null) { return (String) result; } } catch (SAXException | ParserConfigurationException | IOException | XPathExpressionException ignored) { } } return null; } /** * Finds key in integers.xml file and returns text value * * @param directory Root directory of apk * @param key Integer reference (ie @integer/foo) * @return String|null */ public static String pullValueFromIntegers(File directory, String key) { if (key == null || ! key.contains("@")) { return null; } File file = new File(directory, "/res/values/integers.xml"); key = key.replace("@integer/", ""); if (file.exists()) { try { Document doc = loadDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xPath.compile("/resources/integer[@name=" + '"' + key + "\"]/text()"); Object result = expression.evaluate(doc, XPathConstants.STRING); if (result != null) { return (String) result; } } catch (SAXException | ParserConfigurationException | IOException | XPathExpressionException ignored) { } } return null; } /** * Removes attributes like "versionCode" and "versionName" from file. * * @param file File representing AndroidManifest.xml */ public static void removeManifestVersions(File file) { if (file.exists()) { try { Document doc = loadDocument(file); Node manifest = doc.getFirstChild(); NamedNodeMap attr = manifest.getAttributes(); Node vCode = attr.getNamedItem("android:versionCode"); Node vName = attr.getNamedItem("android:versionName"); if (vCode != null) { attr.removeNamedItem("android:versionCode"); } if (vName != null) { attr.removeNamedItem("android:versionName"); } saveDocument(file, doc); } catch (SAXException | ParserConfigurationException | IOException | TransformerException ignored) { } } } /** * Replaces package value with passed packageOriginal string * * @param file File for AndroidManifest.xml * @param packageOriginal Package name to replace */ public static void renameManifestPackage(File file, String packageOriginal) { try { Document doc = loadDocument(file); // Get the manifest line Node manifest = doc.getFirstChild(); // update package attribute NamedNodeMap attr = manifest.getAttributes(); Node nodeAttr = attr.getNamedItem("package"); nodeAttr.setNodeValue(packageOriginal); saveDocument(file, doc); } catch (SAXException | ParserConfigurationException | IOException | TransformerException ignored) { } } /** * * @param file File to load into Document * @return Document * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ private static Document loadDocument(File file) throws IOException, SAXException, ParserConfigurationException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setFeature(FEATURE_DISABLE_DOCTYPE_DECL, true); docFactory.setFeature(FEATURE_LOAD_DTD, false); try { docFactory.setAttribute(ACCESS_EXTERNAL_DTD, " "); docFactory.setAttribute(ACCESS_EXTERNAL_SCHEMA, " "); } catch (IllegalArgumentException ex) { LOGGER.warning("JAXP 1.5 Support is required to validate XML"); } DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // Not using the parse(File) method on purpose, so that we can control when // to close it. Somehow parse(File) does not seem to close the file in all cases. try (FileInputStream inputStream = new FileInputStream(file)) { return docBuilder.parse(inputStream); } } /** * * @param file File to save Document to (ie AndroidManifest.xml) * @param doc Document being saved * @throws IOException * @throws SAXException * @throws ParserConfigurationException * @throws TransformerException */ private static void saveDocument(File file, Document doc) throws IOException, SAXException, ParserConfigurationException, TransformerException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(file); transformer.transform(source, result); } private static final String ACCESS_EXTERNAL_DTD = "http://javax.xml.XMLConstants/property/accessExternalDTD"; private static final String ACCESS_EXTERNAL_SCHEMA = "http://javax.xml.XMLConstants/property/accessExternalSchema"; private static final String FEATURE_LOAD_DTD = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; private static final String FEATURE_DISABLE_DOCTYPE_DECL = "http://apache.org/xml/features/disallow-doctype-decl"; private static final Logger LOGGER = Logger.getLogger(ResXmlPatcher.class.getName()); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/src/SmaliBuilder.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.src; import brut.androlib.exceptions.AndrolibException; import brut.androlib.mod.SmaliMod; import brut.directory.DirectoryException; import brut.directory.ExtFile; import org.antlr.runtime.RecognitionException; import com.android.tools.smali.dexlib2.Opcodes; import com.android.tools.smali.dexlib2.writer.builder.DexBuilder; import com.android.tools.smali.dexlib2.writer.io.FileDataStore; import java.io.*; import java.nio.file.Files; import java.util.logging.Logger; public class SmaliBuilder { public static void build(ExtFile smaliDir, File dexFile, int apiLevel) throws AndrolibException { new SmaliBuilder(smaliDir, dexFile, apiLevel).build(); } private SmaliBuilder(ExtFile smaliDir, File dexFile, int apiLevel) { mSmaliDir = smaliDir; mDexFile = dexFile; mApiLevel = apiLevel; } private void build() throws AndrolibException { try { DexBuilder dexBuilder; if (mApiLevel > 0) { dexBuilder = new DexBuilder(Opcodes.forApi(mApiLevel)); } else { dexBuilder = new DexBuilder(Opcodes.getDefault()); } for (String fileName : mSmaliDir.getDirectory().getFiles(true)) { buildFile(fileName, dexBuilder); } dexBuilder.writeTo(new FileDataStore( new File(mDexFile.getAbsolutePath()))); } catch (IOException | DirectoryException ex) { throw new AndrolibException(ex); } } private void buildFile(String fileName, DexBuilder dexBuilder) throws AndrolibException, IOException { File inFile = new File(mSmaliDir, fileName); InputStream inStream = Files.newInputStream(inFile.toPath()); if (fileName.endsWith(".smali")) { try { if (!SmaliMod.assembleSmaliFile(inFile, dexBuilder, mApiLevel, false, false)) { throw new AndrolibException("Could not smali file: " + fileName); } } catch (IOException | RecognitionException ex) { throw new AndrolibException(ex); } } else { LOGGER.warning("Unknown file type, ignoring: " + inFile); } inStream.close(); } private final ExtFile mSmaliDir; private final File mDexFile; private final int mApiLevel; private final static Logger LOGGER = Logger.getLogger(SmaliBuilder.class.getName()); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/src/SmaliDecoder.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.src; import brut.androlib.exceptions.AndrolibException; import com.android.tools.smali.baksmali.Baksmali; import com.android.tools.smali.baksmali.BaksmaliOptions; import com.android.tools.smali.dexlib2.DexFileFactory; import com.android.tools.smali.dexlib2.Opcodes; import com.android.tools.smali.dexlib2.dexbacked.DexBackedDexFile; import com.android.tools.smali.dexlib2.dexbacked.DexBackedOdexFile; import com.android.tools.smali.dexlib2.analysis.InlineMethodResolver; import com.android.tools.smali.dexlib2.iface.DexFile; import com.android.tools.smali.dexlib2.iface.MultiDexContainer; import java.io.*; public class SmaliDecoder { public static DexFile decode(File apkFile, File outDir, String dexName, boolean bakDeb, int apiLevel) throws AndrolibException { return new SmaliDecoder(apkFile, outDir, dexName, bakDeb, apiLevel).decode(); } private SmaliDecoder(File apkFile, File outDir, String dexName, boolean bakDeb, int apiLevel) { mApkFile = apkFile; mOutDir = outDir; mDexFile = dexName; mBakDeb = bakDeb; mApiLevel = apiLevel; } private DexFile decode() throws AndrolibException { try { final BaksmaliOptions options = new BaksmaliOptions(); // options options.deodex = false; options.implicitReferences = false; options.parameterRegisters = true; options.localsDirective = true; options.sequentialLabels = true; options.debugInfo = mBakDeb; options.codeOffsets = false; options.accessorComments = false; options.registerInfo = 0; options.inlineResolver = null; // set jobs automatically int jobs = Runtime.getRuntime().availableProcessors(); if (jobs > 6) { jobs = 6; } // create the container MultiDexContainer<? extends DexBackedDexFile> container = DexFileFactory.loadDexContainer(mApkFile, mApiLevel > 0 ? Opcodes.forApi(mApiLevel) : null); MultiDexContainer.DexEntry<? extends DexBackedDexFile> dexEntry; DexBackedDexFile dexFile; // If we have 1 item, ignore the passed file. Pull the DexFile we need. if (container.getDexEntryNames().size() == 1) { dexEntry = container.getEntry(container.getDexEntryNames().get(0)); } else { dexEntry = container.getEntry(mDexFile); } // Double-check the passed param exists if (dexEntry == null) { dexEntry = container.getEntry(container.getDexEntryNames().get(0)); } assert dexEntry != null; dexFile = dexEntry.getDexFile(); if (dexFile.supportsOptimizedOpcodes()) { throw new AndrolibException("Warning: You are disassembling an odex file without deodexing it."); } if (dexFile instanceof DexBackedOdexFile) { options.inlineResolver = InlineMethodResolver.createInlineMethodResolver(((DexBackedOdexFile)dexFile).getOdexVersion()); } Baksmali.disassembleDexFile(dexFile, mOutDir, jobs, options); return dexFile; } catch (IOException ex) { throw new AndrolibException(ex); } } private final File mApkFile; private final File mOutDir; private final String mDexFile; private final boolean mBakDeb; private final int mApiLevel; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/org/xmlpull/renamed/MXSerializer.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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.xmlpull.renamed; import org.xmlpull.v1.XmlSerializer; import java.io.*; import java.util.HashSet; import java.util.Objects; import java.util.Set; /** * Implementation of XmlSerializer interface from XmlPull V1 API. This * implementation is optimized for performance and low memory footprint. * * <p> * Implemented features: * <ul> * <li>FEATURE_NAMES_INTERNED - when enabled all returned names (namespaces, * prefixes) will be interned and it is required that all names passed as * arguments MUST be interned * <li>FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE * </ul> * <p> * Implemented properties: * <ul> * <li>PROPERTY_SERIALIZER_INDENTATION * <li>PROPERTY_SERIALIZER_LINE_SEPARATOR * </ul> * */ public class MXSerializer implements XmlSerializer { protected final static String XML_URI = "http://www.w3.org/XML/1998/namespace"; protected final static String XMLNS_URI = "http://www.w3.org/2000/xmlns/"; private static final boolean TRACE_SIZING = false; private static final boolean TRACE_ESCAPING = false; protected final String FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE = "http://xmlpull.org/v1/doc/features.html#serializer-attvalue-use-apostrophe"; protected final String FEATURE_NAMES_INTERNED = "http://xmlpull.org/v1/doc/features.html#names-interned"; protected final String PROPERTY_SERIALIZER_INDENTATION = "http://xmlpull.org/v1/doc/properties.html#serializer-indentation"; protected final String PROPERTY_SERIALIZER_LINE_SEPARATOR = "http://xmlpull.org/v1/doc/properties.html#serializer-line-separator"; protected final static String PROPERTY_LOCATION = "http://xmlpull.org/v1/doc/properties.html#location"; // properties/features protected boolean namesInterned; protected boolean attributeUseApostrophe; protected String indentationString = null; // " "; protected String lineSeparator = "\n"; protected String location; protected Writer out; protected int autoDeclaredPrefixes; protected int depth = 0; // element stack protected String[] elNamespace = new String[2]; protected String[] elName = new String[elNamespace.length]; protected String[] elPrefix = new String[elNamespace.length]; protected int[] elNamespaceCount = new int[elNamespace.length]; // namespace stack protected int namespaceEnd = 0; protected String[] namespacePrefix = new String[8]; protected String[] namespaceUri = new String[namespacePrefix.length]; protected boolean finished; protected boolean pastRoot; protected boolean setPrefixCalled; protected boolean startTagIncomplete; protected boolean doIndent; protected boolean seenTag; protected boolean seenBracket; protected boolean seenBracketBracket; // buffer output if needed to write escaped String see text(String) private static final int BUF_LEN = Runtime.getRuntime().freeMemory() > 1000000L ? 8 * 1024 : 256; protected char[] buf = new char[BUF_LEN]; protected static final String[] precomputedPrefixes; static { precomputedPrefixes = new String[32]; // arbitrary number ... for (int i = 0; i < precomputedPrefixes.length; i++) { precomputedPrefixes[i] = ("n" + i).intern(); } } private final boolean checkNamesInterned = false; private void checkInterning(String name) { if (namesInterned && !Objects.equals(name, name.intern())) { throw new IllegalArgumentException("all names passed as arguments must be interned" + "when NAMES INTERNED feature is enabled"); } } protected void reset() { location = null; out = null; autoDeclaredPrefixes = 0; depth = 0; // nullify references on all levels to allow it to be GCed for (int i = 0; i < elNamespaceCount.length; i++) { elName[i] = null; elPrefix[i] = null; elNamespace[i] = null; elNamespaceCount[i] = 2; } namespaceEnd = 0; // TODO: how to prevent from reporting this namespace? // this is special namespace declared for consistency with XML infoset namespacePrefix[namespaceEnd] = "xmlns"; namespaceUri[namespaceEnd] = XMLNS_URI; ++namespaceEnd; namespacePrefix[namespaceEnd] = "xml"; namespaceUri[namespaceEnd] = XML_URI; ++namespaceEnd; finished = false; pastRoot = false; setPrefixCalled = false; startTagIncomplete = false; seenTag = false; seenBracket = false; seenBracketBracket = false; } protected void ensureElementsCapacity() { final int elStackSize = elName.length; final int newSize = (depth >= 7 ? 2 * depth : 8) + 2; if (TRACE_SIZING) { System.err.println(getClass().getName() + " elStackSize " + elStackSize + " ==> " + newSize); } final boolean needsCopying = elStackSize > 0; String[] arr; // reuse arr local variable slot arr = new String[newSize]; if (needsCopying) System.arraycopy(elName, 0, arr, 0, elStackSize); elName = arr; arr = new String[newSize]; if (needsCopying) System.arraycopy(elPrefix, 0, arr, 0, elStackSize); elPrefix = arr; arr = new String[newSize]; if (needsCopying) System.arraycopy(elNamespace, 0, arr, 0, elStackSize); elNamespace = arr; final int[] iarr = new int[newSize]; if (needsCopying) { System.arraycopy(elNamespaceCount, 0, iarr, 0, elStackSize); } else { // special initialization iarr[0] = 0; } elNamespaceCount = iarr; } protected void ensureNamespacesCapacity() { // int size) { final int newSize = namespaceEnd > 7 ? 2 * namespaceEnd : 8; if (TRACE_SIZING) { System.err.println(getClass().getName() + " namespaceSize " + namespacePrefix.length + " ==> " + newSize); } final String[] newNamespacePrefix = new String[newSize]; final String[] newNamespaceUri = new String[newSize]; if (namespacePrefix != null) { System.arraycopy(namespacePrefix, 0, newNamespacePrefix, 0, namespaceEnd); System.arraycopy(namespaceUri, 0, newNamespaceUri, 0, namespaceEnd); } namespacePrefix = newNamespacePrefix; namespaceUri = newNamespaceUri; } @Override public void setFeature(String name, boolean state) throws IllegalArgumentException, IllegalStateException { if (name == null) { throw new IllegalArgumentException("feature name can not be null"); } if (FEATURE_NAMES_INTERNED.equals(name)) { namesInterned = state; } else if (FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE.equals(name)) { attributeUseApostrophe = state; } else { throw new IllegalStateException("unsupported feature " + name); } } @Override public boolean getFeature(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException("feature name can not be null"); } if (FEATURE_NAMES_INTERNED.equals(name)) { return namesInterned; } else if (FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE.equals(name)) { return attributeUseApostrophe; } else { return false; } } // precomputed variables to simplify writing indentation protected int offsetNewLine; protected int indentationJump; protected char[] indentationBuf; protected int maxIndentLevel; protected boolean writeLineSepartor; // should end-of-line be written protected boolean writeIndentation; // is indentation used? /** * For maximum efficiency when writing indents the required output is * pre-computed This is internal function that recomputes buffer after user * requested chnages. */ protected void rebuildIndentationBuf() { if (!doIndent) return; final int maxIndent = 65; // hardcoded maximum indentation size in characters int bufSize = 0; offsetNewLine = 0; if (writeLineSepartor) { offsetNewLine = lineSeparator.length(); bufSize += offsetNewLine; } maxIndentLevel = 0; if (writeIndentation) { indentationJump = indentationString.length(); maxIndentLevel = maxIndent / indentationJump; bufSize += maxIndentLevel * indentationJump; } if (indentationBuf == null || indentationBuf.length < bufSize) { indentationBuf = new char[bufSize + 8]; } int bufPos = 0; if (writeLineSepartor) { for (int i = 0; i < lineSeparator.length(); i++) { indentationBuf[bufPos++] = lineSeparator.charAt(i); } } if (writeIndentation) { for (int i = 0; i < maxIndentLevel; i++) { for (int j = 0; j < indentationString.length(); j++) { indentationBuf[bufPos++] = indentationString.charAt(j); } } } } protected void writeIndent() throws IOException { final int start = writeLineSepartor ? 0 : offsetNewLine; final int level = Math.min(depth, maxIndentLevel); out.write(indentationBuf, start, ((level - 1) * indentationJump) + offsetNewLine); } @Override public void setProperty(String name, Object value) throws IllegalArgumentException, IllegalStateException { if (name == null) { throw new IllegalArgumentException("property name can not be null"); } switch (name) { case PROPERTY_SERIALIZER_INDENTATION: indentationString = (String) value; break; case PROPERTY_SERIALIZER_LINE_SEPARATOR: lineSeparator = (String) value; break; case PROPERTY_LOCATION: location = (String) value; break; default: throw new IllegalStateException("unsupported property " + name); } writeLineSepartor = lineSeparator != null && lineSeparator.length() > 0; writeIndentation = indentationString != null && indentationString.length() > 0; // optimize - do not write when nothing to write ... doIndent = indentationString != null && (writeLineSepartor || writeIndentation); // NOTE: when indentationString == null there is no indentation // (even though writeLineSeparator may be true ...) rebuildIndentationBuf(); seenTag = false; // for consistency } @Override public Object getProperty(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException("property name can not be null"); } switch (name) { case PROPERTY_SERIALIZER_INDENTATION: return indentationString; case PROPERTY_SERIALIZER_LINE_SEPARATOR: return lineSeparator; case PROPERTY_LOCATION: return location; default: return null; } } private String getLocation() { return location != null ? " @" + location : ""; } // this is special method that can be accessed directly to retrieve Writer // serializer is using public Writer getWriter() { return out; } @Override public void setOutput(Writer writer) { reset(); out = writer; } @Override public void setOutput(OutputStream os, String encoding) throws IOException { if (os == null) throw new IllegalArgumentException("output stream can not be null"); reset(); if (encoding != null) { out = new OutputStreamWriter(os, encoding); } else { out = new OutputStreamWriter(os); } } @Override public void startDocument(String encoding, Boolean standalone) throws IOException { if (attributeUseApostrophe) { out.write("<?xml version='1.0'"); } else { out.write("<?xml version=\"1.0\""); } if (encoding != null) { out.write(" encoding="); out.write(attributeUseApostrophe ? '\'' : '"'); out.write(encoding); out.write(attributeUseApostrophe ? '\'' : '"'); } if (standalone != null) { out.write(" standalone="); out.write(attributeUseApostrophe ? '\'' : '"'); if (standalone) { out.write("yes"); } else { out.write("no"); } out.write(attributeUseApostrophe ? '\'' : '"'); } out.write("?>"); } @Override public void endDocument() throws IOException { // close all unclosed tag; while (depth > 0) { endTag(elNamespace[depth], elName[depth]); } finished = pastRoot = startTagIncomplete = true; out.flush(); } @Override public void setPrefix(String prefix, String namespace) throws IOException { if (startTagIncomplete) closeStartTag(); if (prefix == null) { prefix = ""; } if (!namesInterned) { prefix = prefix.intern(); // will throw NPE if prefix==null } else if (checkNamesInterned) { checkInterning(prefix); } else if (prefix == null) { throw new IllegalArgumentException("prefix must be not null" + getLocation()); } if (!namesInterned) { namespace = namespace.intern(); } else if (checkNamesInterned) { checkInterning(namespace); } else if (namespace == null) { throw new IllegalArgumentException("namespace must be not null" + getLocation()); } if (namespaceEnd >= namespacePrefix.length) { ensureNamespacesCapacity(); } namespacePrefix[namespaceEnd] = prefix; namespaceUri[namespaceEnd] = namespace; ++namespaceEnd; setPrefixCalled = true; } protected String lookupOrDeclarePrefix(String namespace) { return getPrefix(namespace, true); } @Override public String getPrefix(String namespace, boolean generatePrefix) { return getPrefix(namespace, generatePrefix, false); } protected String getPrefix(String namespace, boolean generatePrefix, boolean nonEmpty) { if (!namesInterned) { // when String is interned we can do much faster namespace stack lookups ... namespace = namespace.intern(); } else if (checkNamesInterned) { checkInterning(namespace); } if (namespace == null) { throw new IllegalArgumentException("namespace must be not null" + getLocation()); } else if (namespace.length() == 0) { throw new IllegalArgumentException("default namespace cannot have prefix" + getLocation()); } // first check if namespace is already in scope for (int i = namespaceEnd - 1; i >= 0; --i) { if (namespace.equals(namespaceUri[i])) { final String prefix = namespacePrefix[i]; if (nonEmpty && prefix.length() == 0) { continue; } return prefix; } } // so not found it ... if (!generatePrefix) { return null; } return generatePrefix(namespace); } private String generatePrefix(String namespace) { ++autoDeclaredPrefixes; // fast lookup uses table that was pre-initialized in static{} .... final String prefix = autoDeclaredPrefixes < precomputedPrefixes.length ? precomputedPrefixes[autoDeclaredPrefixes] : ("n" + autoDeclaredPrefixes).intern(); // declare prefix if (namespaceEnd >= namespacePrefix.length) { ensureNamespacesCapacity(); } namespacePrefix[namespaceEnd] = prefix; namespaceUri[namespaceEnd] = namespace; ++namespaceEnd; return prefix; } @Override public int getDepth() { return depth; } @Override public String getNamespace() { return elNamespace[depth]; } @Override public String getName() { return elName[depth]; } @Override public XmlSerializer startTag(String namespace, String name) throws IOException { if (startTagIncomplete) { closeStartTag(); } seenBracket = seenBracketBracket = false; ++depth; if (doIndent && depth > 0 && seenTag) { writeIndent(); } seenTag = true; setPrefixCalled = false; startTagIncomplete = true; if ((depth + 1) >= elName.length) { ensureElementsCapacity(); } if (checkNamesInterned && namesInterned) checkInterning(namespace); elNamespace[depth] = (namesInterned || namespace == null) ? namespace : namespace.intern(); if (checkNamesInterned && namesInterned) checkInterning(name); elName[depth] = (namesInterned || name == null) ? name : name.intern(); if (out == null) { throw new IllegalStateException("setOutput() must called set before serialization can start"); } out.write('<'); if (namespace != null) { if (namespace.length() > 0) { // in future make this algo a feature on serializer String prefix = null; if (depth > 0 && (namespaceEnd - elNamespaceCount[depth - 1]) == 1) { // if only one prefix was declared un-declare it if the // prefix is already declared on parent el with the same URI String uri = namespaceUri[namespaceEnd - 1]; if (uri == namespace || uri.equals(namespace)) { String elPfx = namespacePrefix[namespaceEnd - 1]; for (int pos = elNamespaceCount[depth - 1] - 1; pos >= 2; --pos) { String pf = namespacePrefix[pos]; if (pf == elPfx || pf.equals(elPfx)) { String n = namespaceUri[pos]; if (n == uri || n.equals(uri)) { --namespaceEnd; // un-declare namespace: this is kludge! prefix = elPfx; } break; } } } } if (prefix == null) { prefix = lookupOrDeclarePrefix(namespace); } // make sure that default ("") namespace to not print ":" if (prefix.length() > 0) { elPrefix[depth] = prefix; out.write(prefix); out.write(':'); } else { elPrefix[depth] = ""; } } else { // make sure that default namespace can be declared for (int i = namespaceEnd - 1; i >= 0; --i) { if (namespacePrefix[i] == "") { final String uri = namespaceUri[i]; if (uri == null) { setPrefix("", ""); } else if (uri.length() > 0) { throw new IllegalStateException("start tag can not be written in empty default namespace " + "as default namespace is currently bound to '" + uri + "'" + getLocation()); } break; } } elPrefix[depth] = ""; } } else { elPrefix[depth] = ""; } out.write(name); return this; } @Override public XmlSerializer attribute(String namespace, String name, String value) throws IOException { if (!startTagIncomplete) { throw new IllegalArgumentException("startTag() must be called before attribute()" + getLocation()); } out.write(' '); if (namespace != null && namespace.length() > 0) { if (!namesInterned) { namespace = namespace.intern(); } else if (checkNamesInterned) { checkInterning(namespace); } String prefix = getPrefix(namespace, false, true); if (prefix == null) { // needs to declare prefix to hold default namespace // NOTE: attributes such as a='b' are in NO namespace prefix = generatePrefix(namespace); } out.write(prefix); out.write(':'); } out.write(name); out.write('='); out.write(attributeUseApostrophe ? '\'' : '"'); writeAttributeValue(value, out); out.write(attributeUseApostrophe ? '\'' : '"'); return this; } protected void closeStartTag() throws IOException { if (finished) { throw new IllegalArgumentException("trying to write past already finished output" + getLocation()); } if (seenBracket) { seenBracket = seenBracketBracket = false; } if (startTagIncomplete || setPrefixCalled) { if (setPrefixCalled) { throw new IllegalArgumentException("startTag() must be called immediately after setPrefix()" + getLocation()); } if (!startTagIncomplete) { throw new IllegalArgumentException("trying to close start tag that is not opened" + getLocation()); } // write all namespace declarations! writeNamespaceDeclarations(); out.write('>'); elNamespaceCount[depth] = namespaceEnd; startTagIncomplete = false; } } protected void writeNamespaceDeclarations() throws IOException { Set<String> uniqueNamespaces = new HashSet<>(); for (int i = elNamespaceCount[depth - 1]; i < namespaceEnd; i++) { String prefix = namespacePrefix[i]; String uri = namespaceUri[i]; // Some applications as seen in #2664 have duplicated namespaces. // AOSP doesn't care, but the parser does. So we filter them out. if (uniqueNamespaces.contains(prefix + uri)) { continue; } if (doIndent && uri.length() > 40) { writeIndent(); out.write(" "); } if (prefix != "") { out.write(" xmlns:"); out.write(prefix); out.write('='); } else { out.write(" xmlns="); } out.write(attributeUseApostrophe ? '\'' : '"'); // NOTE: escaping of namespace value the same way as attributes!!!! writeAttributeValue(uri, out); out.write(attributeUseApostrophe ? '\'' : '"'); uniqueNamespaces.add(prefix + uri); } } @Override public XmlSerializer endTag(String namespace, String name) throws IOException { seenBracket = seenBracketBracket = false; if (namespace != null) { if (!namesInterned) { namespace = namespace.intern(); } else if (checkNamesInterned) { checkInterning(namespace); } } if (namespace != elNamespace[depth]) { throw new IllegalArgumentException("expected namespace " + printable(elNamespace[depth]) + " and not " + printable(namespace) + getLocation()); } if (name == null) { throw new IllegalArgumentException("end tag name can not be null" + getLocation()); } if (checkNamesInterned && namesInterned) { checkInterning(name); } String startTagName = elName[depth]; if ((!namesInterned && !name.equals(startTagName)) || (namesInterned && name != startTagName)) { throw new IllegalArgumentException("expected element name " + printable(elName[depth]) + " and not " + printable(name) + getLocation()); } if (startTagIncomplete) { writeNamespaceDeclarations(); out.write(" />"); // space is added to make it easier to work in XHTML!!! } else { if (doIndent && seenTag) { writeIndent(); } out.write("</"); String startTagPrefix = elPrefix[depth]; if (startTagPrefix.length() > 0) { out.write(startTagPrefix); out.write(':'); } out.write(name); out.write('>'); } --depth; namespaceEnd = elNamespaceCount[depth]; startTagIncomplete = false; seenTag = true; return this; } @Override public XmlSerializer text(String text) throws IOException { if (startTagIncomplete || setPrefixCalled) closeStartTag(); if (doIndent && seenTag) seenTag = false; writeElementContent(text, out); return this; } @Override public XmlSerializer text(char[] buf, int start, int len) throws IOException { if (startTagIncomplete || setPrefixCalled) closeStartTag(); if (doIndent && seenTag) seenTag = false; writeElementContent(buf, start, len, out); return this; } @Override public void cdsect(String text) throws IOException { if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); if (doIndent && seenTag) seenTag = false; out.write("<![CDATA["); out.write(text); // escape? out.write("]]>"); } @Override public void entityRef(String text) throws IOException { if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); if (doIndent && seenTag) seenTag = false; out.write('&'); out.write(text); // escape? out.write(';'); } @Override public void processingInstruction(String text) throws IOException { if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); if (doIndent && seenTag) seenTag = false; out.write("<?"); out.write(text); // escape? out.write("?>"); } @Override public void comment(String text) throws IOException { if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); if (doIndent && seenTag) seenTag = false; out.write("<!--"); out.write(text); // escape? out.write("-->"); } @Override public void docdecl(String text) throws IOException { if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); if (doIndent && seenTag) seenTag = false; out.write("<!DOCTYPE"); out.write(text); // escape? out.write(">"); } @Override public void ignorableWhitespace(String text) throws IOException { if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); if (doIndent && seenTag) seenTag = false; if (text.length() == 0) { throw new IllegalArgumentException("empty string is not allowed for ignorable whitespace" + getLocation()); } out.write(text); // no escape? } @Override public void flush() throws IOException { if (!finished && startTagIncomplete) closeStartTag(); out.flush(); } // --- utility methods protected void writeAttributeValue(String value, Writer out) throws IOException { // .[apostrophe and <, & escaped], final char quot = attributeUseApostrophe ? '\'' : '"'; final String quotEntity = attributeUseApostrophe ? "&apos;" : "&quot;"; int pos = 0; for (int i = 0; i < value.length(); i++) { char ch = value.charAt(i); if (ch == '&') { if (i > pos) out.write(value.substring(pos, i)); out.write("&amp;"); pos = i + 1; } if (ch == '<') { if (i > pos) out.write(value.substring(pos, i)); out.write("&lt;"); pos = i + 1; } else if (ch == quot) { if (i > pos) out.write(value.substring(pos, i)); out.write(quotEntity); pos = i + 1; } else if (ch < 32) { // in XML 1.0 only legal character are #x9 | #xA | #xD // and they must be escaped otherwise in attribute value they // are normalized to spaces if (ch == 13 || ch == 10 || ch == 9) { if (i > pos) out.write(value.substring(pos, i)); out.write("&#"); out.write(Integer.toString(ch)); out.write(';'); pos = i + 1; } else { if (TRACE_ESCAPING) System.err.println(getClass().getName() + " DEBUG ATTR value.len=" + value.length() + " " + printable(value)); throw new IllegalStateException( "character " + printable(ch) + " (" + Integer.toString(ch) + ") is not allowed in output" + getLocation() + " (attr value=" + printable(value) + ")"); } } } if (pos > 0) { out.write(value.substring(pos)); } else { out.write(value); // this is shortcut to the most common case } } protected void writeElementContent(String text, Writer out) throws IOException { // For some reason, some non-empty, empty characters are surviving this far and getting filtered out // So we are left with null, which causes an NPE if (text == null) { return; } // escape '<', '&', ']]>', <32 if necessary int pos = 0; for (int i = 0; i < text.length(); i++) { // TODO: check if doing char[] text.getChars() would be faster than // getCharAt(i) ... char ch = text.charAt(i); if (ch == ']') { if (seenBracket) { seenBracketBracket = true; } else { seenBracket = true; } } else { if (ch == '&') { if (!(i < text.length() - 3 && text.charAt(i+1) == 'l' && text.charAt(i+2) == 't' && text.charAt(i+3) == ';')) { if (i > pos) out.write(text.substring(pos, i)); out.write("&amp;"); pos = i + 1; } } else if (ch == '<') { if (i > pos) out.write(text.substring(pos, i)); out.write("&lt;"); pos = i + 1; } else if (seenBracketBracket && ch == '>') { if (i > pos) out.write(text.substring(pos, i)); out.write("&gt;"); pos = i + 1; } else if (ch < 32) { // in XML 1.0 only legal character are #x9 | #xA | #xD if (ch == 9 || ch == 10 || ch == 13) { // pass through } else { if (TRACE_ESCAPING) System.err.println(getClass().getName() + " DEBUG TEXT value.len=" + text.length() + " " + printable(text)); throw new IllegalStateException("character " + Integer.toString(ch) + " is not allowed in output" + getLocation() + " (text value=" + printable(text) + ")"); } } if (seenBracket) { seenBracketBracket = seenBracket = false; } } } if (pos > 0) { out.write(text.substring(pos)); } else { out.write(text); // this is shortcut to the most common case } } protected void writeElementContent(char[] buf, int off, int len, Writer out) throws IOException { // escape '<', '&', ']]>' final int end = off + len; int pos = off; for (int i = off; i < end; i++) { final char ch = buf[i]; if (ch == ']') { if (seenBracket) { seenBracketBracket = true; } else { seenBracket = true; } } else { if (ch == '&') { if (i > pos) { out.write(buf, pos, i - pos); } out.write("&amp;"); pos = i + 1; } else if (ch == '<') { if (i > pos) { out.write(buf, pos, i - pos); } out.write("&lt;"); pos = i + 1; } else if (seenBracketBracket && ch == '>') { if (i > pos) { out.write(buf, pos, i - pos); } out.write("&gt;"); pos = i + 1; } else if (ch < 32) { // in XML 1.0 only legal character are #x9 | #xA | #xD if (ch == 9 || ch == 10 || ch == 13) { // pass through } else { if (TRACE_ESCAPING) System.err.println(getClass().getName() + " DEBUG TEXT value.len=" + len + " " + printable(new String(buf, off, len))); throw new IllegalStateException("character " + printable(ch) + " (" + Integer.toString(ch) + ") is not allowed in output" + getLocation()); } } if (seenBracket) { seenBracketBracket = seenBracket = false; } } } if (end > pos) { out.write(buf, pos, end - pos); } } protected static String printable(String s) { if (s == null) { return "null"; } StringBuffer retval = new StringBuffer(s.length() + 16); retval.append("'"); for (int i = 0; i < s.length(); i++) { addPrintable(retval, s.charAt(i)); } retval.append("'"); return retval.toString(); } protected static String printable(char ch) { StringBuffer retval = new StringBuffer(); addPrintable(retval, ch); return retval.toString(); } private static void addPrintable(StringBuffer retval, char ch) { switch (ch) { case '\b': retval.append("\\b"); break; case '\t': retval.append("\\t"); break; case '\n': retval.append("\\n"); break; case '\f': retval.append("\\f"); break; case '\r': retval.append("\\r"); break; case '\"': retval.append("\\\""); break; case '\'': retval.append("\\'"); break; case '\\': retval.append("\\\\"); break; default: if (ch < 0x20 || ch > 0x7e) { final String ss = "0000" + Integer.toString(ch, 16); retval.append("\\u").append(ss.substring(ss.length() - 4)); } else { retval.append(ch); } } } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/BaseTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib; import brut.androlib.apk.ApkInfo; import brut.common.BrutException; import brut.directory.ExtFile; import brut.directory.FileDirectory; import org.custommonkey.xmlunit.*; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; import static org.junit.Assert.*; public class BaseTest { protected void compareUnknownFiles() throws BrutException { ApkInfo control = ApkInfo.load(sTestOrigDir); ApkInfo test = ApkInfo.load(sTestNewDir); assertNotNull(control.unknownFiles); assertNotNull(test.unknownFiles); Map<String, String> controlFiles = control.unknownFiles; Map<String, String> testFiles = test.unknownFiles; assertEquals(controlFiles.size(), testFiles.size()); // Make sure that the compression methods are still the same for (Map.Entry<String, String> controlEntry : controlFiles.entrySet()) { assertEquals(controlEntry.getValue(), testFiles.get(controlEntry.getKey())); } } protected void compareBinaryFolder(String path, boolean res) throws BrutException, IOException { boolean exists = true; String prefixPath = ""; if (res) { prefixPath = File.separatorChar + "res" + File.separatorChar; } String location = prefixPath + path; FileDirectory fileDirectory = new FileDirectory(sTestOrigDir, location); Set<String> files = fileDirectory.getFiles(true); for (String filename : files) { File control = new File((sTestOrigDir + location), filename); File test = new File((sTestNewDir + location), filename); if (! test.isFile() || ! control.isFile()) { exists = false; } } assertTrue(exists); } protected void compareResFolder(String path) throws BrutException, IOException { compareBinaryFolder(path, true); } protected void compareLibsFolder(String path) throws BrutException, IOException { compareBinaryFolder(File.separatorChar + path, false); } protected void compareAssetsFolder(String path) throws BrutException, IOException { compareBinaryFolder(File.separatorChar + "assets" + File.separatorChar + path, false); } protected void compareValuesFiles(String path) throws BrutException { compareXmlFiles("res/" + path, new ElementNameAndAttributeQualifier("name")); } protected void compareXmlFiles(String path) throws BrutException { compareXmlFiles(path, null); } protected void checkFolderExists(String path) { File f = new File(sTestNewDir, path); assertTrue(f.isDirectory()); } protected boolean isTransparent(int pixel) { return pixel >> 24 == 0x00; } private void compareXmlFiles(String path, ElementQualifier qualifier) throws BrutException { DetailedDiff diff; try { Reader control = new FileReader(new File(sTestOrigDir, path)); Reader test = new FileReader(new File(sTestNewDir, path)); XMLUnit.setEnableXXEProtection(true); if (qualifier == null) { XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); XMLUnit.setCompareUnmatched(false); assertXMLEqual(control, test); return; } diff = new DetailedDiff(new Diff(control, test)); } catch (SAXException | IOException ex) { throw new BrutException(ex); } diff.overrideElementQualifier(qualifier); assertTrue(path + ": " + diff.getAllDifferences().toString(), diff.similar()); } protected static Document loadDocument(File file) throws IOException, SAXException, ParserConfigurationException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setFeature(FEATURE_DISABLE_DOCTYPE_DECL, true); docFactory.setFeature(FEATURE_LOAD_DTD, false); try { docFactory.setAttribute(ACCESS_EXTERNAL_DTD, " "); docFactory.setAttribute(ACCESS_EXTERNAL_SCHEMA, " "); } catch (IllegalArgumentException ex) { LOGGER.warning("JAXP 1.5 Support is required to validate XML"); } DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // Not using the parse(File) method on purpose, so that we can control when // to close it. Somehow parse(File) does not seem to close the file in all cases. try (FileInputStream inputStream = new FileInputStream(file)) { return docBuilder.parse(inputStream); } } protected static ExtFile sTmpDir; protected static ExtFile sTestOrigDir; protected static ExtFile sTestNewDir; protected final static Logger LOGGER = Logger.getLogger(BaseTest.class.getName()); private static final String ACCESS_EXTERNAL_DTD = "http://javax.xml.XMLConstants/property/accessExternalDTD"; private static final String ACCESS_EXTERNAL_SCHEMA = "http://javax.xml.XMLConstants/property/accessExternalSchema"; private static final String FEATURE_LOAD_DTD = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; private static final String FEATURE_DISABLE_DOCTYPE_DECL = "http://apache.org/xml/features/disallow-doctype-decl"; }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/TestUtils.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.Framework; import brut.common.BrutException; import brut.directory.DirUtil; import brut.directory.Directory; import brut.directory.FileDirectory; import brut.util.OS; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.*; import java.net.URL; import java.net.URLDecoder; import java.nio.file.Files; import java.util.HashMap; import java.util.Map; public abstract class TestUtils { public static Map<String, String> parseStringsXml(File file) throws BrutException { try { XmlPullParser xpp = XmlPullParserFactory.newInstance().newPullParser(); xpp.setInput(new FileReader(file)); int eventType; String key = null; Map<String, String> map = new HashMap<>(); while ((eventType = xpp.next()) != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: if ("string".equals(xpp.getName())) { int attrCount = xpp.getAttributeCount(); for (int i = 0; i < attrCount; i++) { if ("name".equals(xpp.getAttributeName(i))) { key = xpp.getAttributeValue(i); break; } } } break; case XmlPullParser.END_TAG: if ("string".equals(xpp.getName())) { key = null; } break; case XmlPullParser.TEXT: if (key != null) { map.put(key, xpp.getText()); } break; } } return map; } catch (IOException | XmlPullParserException ex) { throw new BrutException(ex); } } public static void copyResourceDir(Class<?> class_, String dirPath, File out) throws BrutException { if (!out.exists()) { out.mkdirs(); } copyResourceDir(class_, dirPath, new FileDirectory(out)); } public static void copyResourceDir(Class<?> class_, String dirPath, Directory out) throws BrutException { if (class_ == null) { class_ = Class.class; } URL dirURL = class_.getClassLoader().getResource(dirPath); if (dirURL != null && dirURL.getProtocol().equals("file")) { try { DirUtil.copyToDir(new FileDirectory(dirURL.getFile()), out); } catch (UnsupportedEncodingException ex) { throw new BrutException(ex); } return; } if (dirURL == null) { String className = class_.getName().replace(".", "/") + ".class"; dirURL = class_.getClassLoader().getResource(className); } if (dirURL.getProtocol().equals("jar")) { String jarPath; try { jarPath = URLDecoder.decode(dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")), "UTF-8"); DirUtil.copyToDir(new FileDirectory(jarPath), out); } catch (UnsupportedEncodingException ex) { throw new BrutException(ex); } } } public static void cleanFrameworkFile() throws BrutException { File framework = new File(getFrameworkDirectory(), "1.apk"); if (Files.exists(framework.toPath())) { OS.rmfile(framework.getAbsolutePath()); } } public static byte[] readHeaderOfFile(File file, int size) throws IOException { byte[] buffer = new byte[size]; InputStream inputStream = Files.newInputStream(file.toPath()); if (inputStream.read(buffer) != buffer.length) { throw new IOException("File size too small for buffer length: " + size); } inputStream.close(); return buffer; } static File getFrameworkDirectory() throws AndrolibException { Config config = Config.getDefaultConfig(); Framework framework = new Framework(config); return framework.getFrameworkDirectory(); } public static String replaceNewlines(String value) { return value.replace("\n", "").replace("\r", ""); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt1/AndroidOreoNotSparseTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt1; import brut.androlib.*; import brut.androlib.Config; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertTrue; public class AndroidOreoNotSparseTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "issue1594-orig"); sTestNewDir = new ExtFile(sTmpDir, "issue1594-new"); LOGGER.info("Unpacking not_sparse.apk..."); TestUtils.copyResourceDir(AndroidOreoNotSparseTest.class, "aapt1/issue1594", sTestOrigDir); File testApk = new File(sTestOrigDir, "not_sparse.apk"); LOGGER.info("Decoding not_sparse.apk..."); ApkDecoder apkDecoder = new ApkDecoder(testApk); apkDecoder.decode(sTestNewDir); LOGGER.info("Building not_sparse.apk..."); Config config = Config.getDefaultConfig(); new ApkBuilder(config, sTestNewDir).build(testApk); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void buildAndDecodeTest() { assertTrue(sTestNewDir.isDirectory()); assertTrue(sTestOrigDir.isDirectory()); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt1/AndroidOreoSparseTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt1; import brut.androlib.*; import brut.androlib.Config; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertTrue; public class AndroidOreoSparseTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "issue1594-orig"); sTestNewDir = new ExtFile(sTmpDir, "issue1594-new"); LOGGER.info("Unpacking sparse.apk..."); TestUtils.copyResourceDir(AndroidOreoSparseTest.class, "aapt1/issue1594", sTestOrigDir); File testApk = new File(sTestOrigDir, "sparse.apk"); LOGGER.info("Decoding sparse.apk..."); ApkDecoder apkDecoder = new ApkDecoder(testApk); apkDecoder.decode(sTestNewDir); LOGGER.info("Building sparse.apk..."); Config config = Config.getDefaultConfig(); new ApkBuilder(config, sTestNewDir).build(testApk); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void buildAndDecodeTest() { assertTrue(sTestNewDir.isDirectory()); assertTrue(sTestOrigDir.isDirectory()); } @Test public void ensureStringsOreoTest() { assertTrue((new File(sTestNewDir, "res/values-v26/strings.xml").isFile())); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt1/BuildAndDecodeJarTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt1; import brut.androlib.ApkBuilder; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertTrue; public class BuildAndDecodeJarTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "testjar-orig"); sTestNewDir = new ExtFile(sTmpDir, "testjar-new"); LOGGER.info("Unpacking testjar..."); TestUtils.copyResourceDir(BuildAndDecodeJarTest.class, "aapt1/testjar/", sTestOrigDir); LOGGER.info("Building testjar.jar..."); File testJar = new File(sTmpDir, "testjar.jar"); new ApkBuilder(sTestOrigDir).build(testJar); LOGGER.info("Decoding testjar.jar..."); ApkDecoder apkDecoder = new ApkDecoder(testJar); apkDecoder.decode(sTestNewDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void buildAndDecodeTest() { assertTrue(sTestNewDir.isDirectory()); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt1/BuildAndDecodeTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt1; import brut.androlib.ApkBuilder; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.androlib.apk.ApkInfo; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import brut.util.OSDetection; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Map; import static org.junit.Assert.*; import static org.junit.Assume.assumeTrue; public class BuildAndDecodeTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "testapp-orig"); sTestNewDir = new ExtFile(sTmpDir, "testapp-new"); LOGGER.info("Unpacking testapp..."); TestUtils.copyResourceDir(BuildAndDecodeTest.class, "aapt1/testapp/", sTestOrigDir); LOGGER.info("Building testapp.apk..."); File testApk = new File(sTmpDir, "testapp.apk"); new ApkBuilder(sTestOrigDir).build(testApk); LOGGER.info("Decoding testapp.apk..."); ApkDecoder apkDecoder = new ApkDecoder(testApk); apkDecoder.decode(sTestNewDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void buildAndDecodeTest() { assertTrue(sTestNewDir.isDirectory()); } @Test public void manifestTaggingNotSupressed() throws BrutException { compareXmlFiles("AndroidManifest.xml"); } @Test public void valuesAnimsTest() throws BrutException { compareValuesFiles("values-mcc001/anims.xml"); } @Test public void valuesArraysTest() throws BrutException { compareValuesFiles("values-mcc001/arrays.xml"); } @Test public void valuesArraysCastingTest() throws BrutException { compareValuesFiles("values-mcc002/arrays.xml"); compareValuesFiles("values-mcc003/arrays.xml"); } @Test public void valuesAttrsTest() throws BrutException { compareValuesFiles("values/attrs.xml"); } @Test public void valuesBoolsTest() throws BrutException { compareValuesFiles("values-mcc001/bools.xml"); } @Test public void valuesColorsTest() throws BrutException { compareValuesFiles("values-mcc001/colors.xml"); } @Test public void bug702Test() throws BrutException { compareValuesFiles("values-mcc001-mnc00/strings.xml"); } @Test public void valuesDimensTest() throws BrutException { compareValuesFiles("values-mcc001/dimens.xml"); } @Test public void valuesDrawablesTest() throws BrutException { compareValuesFiles("values-mcc001/drawables.xml"); } @Test public void valuesIdsTest() throws BrutException { compareValuesFiles("values-mcc001/ids.xml"); } @Test public void valuesIntegersTest() throws BrutException { compareValuesFiles("values-mcc001/integers.xml"); } @Test public void valuesLayoutsTest() throws BrutException { compareValuesFiles("values-mcc001/layouts.xml"); } @Test public void xmlPluralsTest() throws BrutException { compareValuesFiles("values-mcc001/plurals.xml"); } @Test public void valuesStringsTest() throws BrutException { compareValuesFiles("values-mcc001/strings.xml"); } @Test public void valuesStylesTest() throws BrutException { compareValuesFiles("values-mcc001/styles.xml"); } @Test public void valuesReferencesTest() throws BrutException { compareValuesFiles("values-mcc002/strings.xml"); } @Test public void valuesExtraLongTest() throws BrutException { compareValuesFiles("values-en/strings.xml"); } @Test public void valuesExtraLongExactLengthTest() throws BrutException { Map<String, String> strs = TestUtils.parseStringsXml(new File(sTestNewDir, "res/values-en/strings.xml")); // long_string6 should be exactly 0x8888 chars of "a" // the valuesExtraLongTest() should handle this // but such an edge case, want a specific test String aaaa = strs.get("long_string6"); assertEquals(0x8888, aaaa.length()); } @Test public void storedMp3FilesAreNotCompressedTest() throws BrutException { ExtFile extFile = new ExtFile(sTmpDir, "testapp.apk"); Integer built = extFile.getDirectory().getCompressionLevel("res/raw/rain.mp3"); assertEquals(Integer.valueOf(0), built); } @Test public void crossTypeTest() throws BrutException { compareValuesFiles("values-mcc003/strings.xml"); compareValuesFiles("values-mcc003/integers.xml"); compareValuesFiles("values-mcc003/bools.xml"); } @Test public void xmlLiteralsTest() throws BrutException { compareXmlFiles("res/xml/literals.xml"); } @Test public void xmlReferencesTest() throws BrutException { compareXmlFiles("res/xml/references.xml"); } @Test public void xmlXsdFileTest() throws BrutException { compareXmlFiles("res/xml/ww_box_styles_schema.xsd"); } @Test public void xmlIdsEmptyTest() throws BrutException { compareXmlFiles("res/values/ids.xml"); } @Test public void xmlReferenceAttributeTest() throws BrutException { compareXmlFiles("res/layout/issue1040.xml"); } @Test public void xmlCustomAttributeTest() throws BrutException { compareXmlFiles("res/layout/issue1063.xml"); } @Test public void xmlSmallNumbersDontEscapeTest() throws BrutException { compareXmlFiles("res/layout/issue1130.xml"); } @Test public void xmlUniformAutoTextTest() throws BrutException { compareXmlFiles("res/layout/issue1674.xml"); } @Test(expected = AssertionError.class) public void xmlFillParentBecomesMatchTest() throws BrutException { compareXmlFiles("res/layout/issue1274.xml"); } @Test public void xmlCustomAttrsNotAndroidTest() throws BrutException { compareXmlFiles("res/layout/issue1157.xml"); } @Test public void qualifiersTest() throws BrutException { compareValuesFiles("values-mcc004-mnc4-en-rUS-ldrtl-sw100dp-w200dp-h300dp" + "-long-round-highdr-land-desk-night-xhdpi-finger-keyssoft-12key" + "-navhidden-dpad-v26/strings.xml"); } @Test public void shortendedMncTest() throws BrutException { compareValuesFiles("values-mcc001-mnc1/strings.xml"); } @Test public void shortMncHtcTest() throws BrutException { compareValuesFiles("values-mnc1/strings.xml"); } @Test public void shortMncv2Test() throws BrutException { compareValuesFiles("values-mcc238-mnc6/strings.xml"); } @Test public void longMncTest() throws BrutException { compareValuesFiles("values-mcc238-mnc870/strings.xml"); } @Test public void anyDpiTest() throws BrutException { compareValuesFiles("values-watch/strings.xml"); } @Test public void packed3CharsTest() throws BrutException { compareValuesFiles("values-ast-rES/strings.xml"); } @Test public void rightToLeftTest() throws BrutException { compareValuesFiles("values-ldrtl/strings.xml"); } @Test public void scriptBcp47Test() throws BrutException { compareValuesFiles("values-b+en+Latn+US/strings.xml"); } @Test public void threeLetterLangBcp47Test() throws BrutException { compareValuesFiles("values-ast/strings.xml"); } @Test public void androidOStringTest() throws BrutException { compareValuesFiles("values-ast/strings.xml"); } @Test public void twoLetterNotHandledAsBcpTest() { checkFolderExists("res/values-fr"); } @Test public void twoLetterLangBcp47Test() throws BrutException { compareValuesFiles("values-en-rUS/strings.xml"); } @Test public void variantBcp47Test() throws BrutException { compareValuesFiles("values-b+en+US+POSIX/strings.xml"); } @Test public void fourpartBcp47Test() throws BrutException { compareValuesFiles("values-b+ast+Latn+IT+AREVELA/strings.xml"); } @Test public void RegionLocaleBcp47Test() throws BrutException { compareValuesFiles("values-b+en+Latn+419/strings.xml"); } @Test public void numericalRegionBcp47Test() throws BrutException { compareValuesFiles("values-b+eng+419/strings.xml"); } @Test public void api23ConfigurationsTest() throws BrutException { compareValuesFiles("values-round/strings.xml"); compareValuesFiles("values-notround/strings.xml"); } @Test public void api26ConfigurationsTest() throws BrutException { compareValuesFiles("values-widecg-v26/strings.xml"); compareValuesFiles("values-lowdr-v26/strings.xml"); compareValuesFiles("values-nowidecg-v26/strings.xml"); compareValuesFiles("values-vrheadset-v26/strings.xml"); } @Test public void fontTest() throws BrutException { File fontXml = new File((sTestNewDir + "/res/font"), "lobster.xml"); File fontFile = new File((sTestNewDir + "/res/font"), "lobster_regular.otf"); // Per #1662, ensure font file is not encoded. assertTrue(fontXml.isFile()); compareXmlFiles("/res/font/lobster.xml"); // If we properly skipped decoding the font (otf) file, this file should not exist assertFalse((new File((sTestNewDir + "/res/values"), "fonts.xml")).isFile()); assertTrue(fontFile.isFile()); } @Test public void drawableNoDpiTest() throws BrutException, IOException { compareResFolder("drawable-nodpi"); } @Test public void drawableAnyDpiTest() throws BrutException, IOException { compareResFolder("drawable-anydpi"); } @Test public void drawableNumberedDpiTest() throws BrutException, IOException { compareResFolder("drawable-534dpi"); } @Test public void drawableLdpiTest() throws BrutException, IOException { compareResFolder("drawable-ldpi"); } @Test public void drawableMdpiTest() throws BrutException, IOException { compareResFolder("drawable-mdpi"); } @Test public void drawableTvdpiTest() throws BrutException, IOException { compareResFolder("drawable-tvdpi"); } @Test public void drawableXhdpiTest() throws BrutException, IOException { compareResFolder("drawable-xhdpi"); } @Test public void ninePatchImageColorTest() throws IOException { char slash = File.separatorChar; String location = slash + "res" + slash + "drawable-xhdpi" + slash; File control = new File((sTestOrigDir + location), "9patch.9.png"); File test = new File((sTestNewDir + location), "9patch.9.png"); BufferedImage controlImage = ImageIO.read(control); BufferedImage testImage = ImageIO.read(test); // lets start with 0,0 - empty assertEquals(controlImage.getRGB(0, 0), testImage.getRGB(0, 0)); // then with 30, 0 - black assertEquals(controlImage.getRGB(30, 0), testImage.getRGB(30, 0)); // then 30, 30 - blue assertEquals(controlImage.getRGB(30, 30), testImage.getRGB(30, 30)); } @Test public void issue1508Test() throws IOException { char slash = File.separatorChar; String location = slash + "res" + slash + "drawable-xhdpi" + slash; File control = new File((sTestOrigDir + location), "btn_zoom_up_normal.9.png"); File test = new File((sTestNewDir + location), "btn_zoom_up_normal.9.png"); BufferedImage controlImage = ImageIO.read(control); BufferedImage testImage = ImageIO.read(test); // 0, 0 = clear assertEquals(controlImage.getRGB(0, 0), testImage.getRGB(0, 0)); // 30, 0 = black line assertEquals(controlImage.getRGB(0, 30), testImage.getRGB(0, 30)); // 30, 30 = greyish button assertEquals(controlImage.getRGB(30, 30), testImage.getRGB(30, 30)); } @Test public void issue1511Test() throws IOException { char slash = File.separatorChar; String location = slash + "res" + slash + "drawable-xxhdpi" + slash; File control = new File((sTestOrigDir + location), "textfield_activated_holo_dark.9.png"); File test = new File((sTestNewDir + location), "textfield_activated_holo_dark.9.png"); BufferedImage controlImage = ImageIO.read(control); BufferedImage testImage = ImageIO.read(test); // Check entire image as we cannot mess this up final int w = controlImage.getWidth(), h = controlImage.getHeight(); final int[] controlImageGrid = controlImage.getRGB(0, 0, w, h, null, 0, w); final int[] testImageGrid = testImage.getRGB(0, 0, w, h, null, 0, w); for (int i = 0; i < controlImageGrid.length; i++) { assertEquals("Image lost Optical Bounds at i = " + i, controlImageGrid[i], testImageGrid[i]); } } @Test public void robust9patchTest() throws IOException { String[] ninePatches = {"ic_notification_overlay.9.png", "status_background.9.png", "search_bg_transparent.9.png", "screenshot_panel.9.png", "recents_lower_gradient.9.png"}; char slash = File.separatorChar; String location = slash + "res" + slash + "drawable-xxhdpi" + slash; for (String ninePatch : ninePatches) { File control = new File((sTestOrigDir + location), ninePatch); File test = new File((sTestNewDir + location), ninePatch); BufferedImage controlImage = ImageIO.read(control); BufferedImage testImage = ImageIO.read(test); int w = controlImage.getWidth(), h = controlImage.getHeight(); // Check the entire horizontal line for (int i = 1; i < w; i++) { if (isTransparent(controlImage.getRGB(i, 0))) { assertTrue(isTransparent(testImage.getRGB(i, 0))); } else { assertEquals("Image lost npTc chunk on image " + ninePatch + " at (x, y) (" + i + "," + 0 + ")", controlImage.getRGB(i, 0), testImage.getRGB(i, 0)); } } // Check the entire vertical line for (int i = 1; i < h; i++) { if (isTransparent(controlImage.getRGB(0, i))) { assertTrue(isTransparent(testImage.getRGB(0, i))); } else { assertEquals("Image lost npTc chunk on image " + ninePatch + " at (x, y) (" + 0 + "," + i + ")", controlImage.getRGB(0, i), testImage.getRGB(0, i)); } } } } @Test public void confirmZeroByteFileExtensionIsNotStored() throws BrutException { ApkInfo apkInfo = ApkInfo.load(sTestNewDir); for (String item : apkInfo.doNotCompress) { assertNotEquals("jpg", item); } } @Test public void confirmZeroByteFileIsStored() throws BrutException { ApkInfo apkInfo = ApkInfo.load(sTestNewDir); assertTrue(apkInfo.doNotCompress.contains("assets/0byte_file.jpg")); } @Test public void drawableXxhdpiTest() throws BrutException, IOException { compareResFolder("drawable-xxhdpi"); } @Test public void drawableQualifierXxhdpiTest() throws BrutException, IOException { compareResFolder("drawable-xxhdpi-v4"); } @Test public void drawableXxxhdpiTest() throws BrutException, IOException { compareResFolder("drawable-xxxhdpi"); } @Test public void resRawTest() throws BrutException, IOException { compareResFolder("raw"); } @Test public void libsTest() throws BrutException, IOException { compareLibsFolder("libs"); compareLibsFolder("lib"); } @Test public void unknownFolderTest() throws BrutException { compareUnknownFiles(); } @Test public void fileAssetTest() throws BrutException, IOException { compareAssetsFolder("txt"); } @Test public void unicodeAssetTest() throws BrutException, IOException { assumeTrue(! OSDetection.isWindows()); compareAssetsFolder("unicode-txt"); } @Test public void multipleDexTest() throws BrutException, IOException { compareBinaryFolder("/smali_classes2", false); compareBinaryFolder("/smali_classes3", false); File classes2Dex = new File(sTestOrigDir, "build/apk/classes2.dex"); File classes3Dex = new File(sTestOrigDir, "build/apk/classes3.dex"); assertTrue(classes2Dex.isFile()); assertTrue(classes3Dex.isFile()); } @Test public void singleDexTest() throws BrutException, IOException { compareBinaryFolder("/smali", false); File classesDex = new File(sTestOrigDir, "build/apk/classes.dex"); assertTrue(classesDex.isFile()); } @Test public void confirmKotlinFolderPersistsTest() { checkFolderExists("/kotlin"); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt1/DebugTagRetainedTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt1; import brut.androlib.*; import brut.androlib.Config; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.custommonkey.xmlunit.XMLUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.junit.Assert.assertTrue; import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; public class DebugTagRetainedTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "issue1235-orig"); sTestNewDir = new ExtFile(sTmpDir, "issue1235-new"); LOGGER.info("Unpacking issue1235..."); TestUtils.copyResourceDir(DebugTagRetainedTest.class, "aapt1/issue1235/", sTestOrigDir); LOGGER.info("Building issue1235.apk..."); Config config = Config.getDefaultConfig(); config.debugMode = true; File testApk = new File(sTmpDir, "issue1235.apk"); new ApkBuilder(config, sTestOrigDir).build(testApk); LOGGER.info("Decoding issue1235.apk..."); ApkDecoder apkDecoder = new ApkDecoder(testApk); apkDecoder.decode(sTestNewDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void buildAndDecodeTest() { assertTrue(sTestNewDir.isDirectory()); } @Test public void DebugIsTruePriorToBeingFalseTest() throws IOException, SAXException { String apk = "issue1235-new"; String expected = TestUtils.replaceNewlines("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" android:compileSdkVersion=\"23\" " + "android:compileSdkVersionCodename=\"6.0-2438415\" package=\"com.ibotpeaches.issue1235\" platformBuildVersionCode=\"20\" " + "platformBuildVersionName=\"4.4W.2-1537038\"> <application android:debuggable=\"true\"/></manifest>"); byte[] encoded = Files.readAllBytes(Paths.get(sTmpDir + File.separator + apk + File.separator + "AndroidManifest.xml")); String obtained = TestUtils.replaceNewlines(new String(encoded)); XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); XMLUnit.setCompareUnmatched(false); assertXMLEqual(expected, obtained); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt1/DefaultBaksmaliVariableTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt1; import brut.androlib.ApkBuilder; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; public class DefaultBaksmaliVariableTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "testjar-orig"); sTestNewDir = new ExtFile(sTmpDir, "testjar-new"); LOGGER.info("Unpacking testjar..."); TestUtils.copyResourceDir(DefaultBaksmaliVariableTest.class, "aapt1/issue1481/", sTestOrigDir); LOGGER.info("Building issue1481.jar..."); File testJar = new File(sTmpDir, "issue1481.jar"); new ApkBuilder(sTestOrigDir).build(testJar); LOGGER.info("Decoding issue1481.jar..."); ApkDecoder apkDecoder = new ApkDecoder(testJar); apkDecoder.decode(sTestNewDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void confirmBaksmaliParamsAreTheSame() throws BrutException, IOException { String expected = TestUtils.replaceNewlines(".class public final Lcom/ibotpeaches/issue1481/BuildConfig;\n" + ".super Ljava/lang/Object;\n" + ".source \"BuildConfig.java\"\n" + "\n" + "\n" + "# static fields\n" + ".field public static final APPLICATION_ID:Ljava/lang/String; = \"com.ibotpeaches.issue1481\"\n" + "\n" + ".field public static final BUILD_TYPE:Ljava/lang/String; = \"debug\"\n" + "\n" + ".field public static final DEBUG:Z\n" + "\n" + ".field public static final FLAVOR:Ljava/lang/String; = \"\"\n" + "\n" + ".field public static final VERSION_CODE:I = 0x1\n" + "\n" + ".field public static final VERSION_NAME:Ljava/lang/String; = \"1.0\"\n" + "\n" + "\n" + "# direct methods\n" + ".method static constructor <clinit>()V\n" + " .locals 1\n" + "\n" + " .prologue\n" + " .line 7\n" + " const-string v0, \"true\"\n" + "\n" + " invoke-static {v0}, Ljava/lang/Boolean;->parseBoolean(Ljava/lang/String;)Z\n" + "\n" + " move-result v0\n" + "\n" + " sput-boolean v0, Lcom/ibotpeaches/issue1481/BuildConfig;->DEBUG:Z\n" + "\n" + " return-void\n" + ".end method\n" + "\n" + ".method public constructor <init>()V\n" + " .locals 0\n" + "\n" + " .prologue\n" + " .line 6\n" + " invoke-direct {p0}, Ljava/lang/Object;-><init>()V\n" + "\n" + " return-void\n" + ".end method"); byte[] encoded = Files.readAllBytes(Paths.get(sTestNewDir + File.separator + "smali" + File.separator + "com" + File.separator + "ibotpeaches" + File.separator + "issue1481" + File.separator + "BuildConfig.smali")); String obtained = TestUtils.replaceNewlines(new String(encoded)); assertEquals(expected, obtained); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt1/EmptyResourcesArscTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt1; import brut.androlib.ApkBuilder; import brut.androlib.ApkDecoder; import brut.androlib.Config; import brut.androlib.TestUtils; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.util.logging.Logger; import static org.junit.Assert.assertTrue; public class EmptyResourcesArscTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "issue1730-orig"); sTestNewDir = new ExtFile(sTmpDir, "issue1730-new"); LOGGER.info("Unpacking issue1730.apk..."); TestUtils.copyResourceDir(EmptyResourcesArscTest.class, "aapt1/issue1730", sTestOrigDir); File testApk = new File(sTestOrigDir, "issue1730.apk"); LOGGER.info("Decoding issue1730.apk..."); ApkDecoder apkDecoder = new ApkDecoder(testApk); apkDecoder.decode(sTestNewDir); LOGGER.info("Building issue1730.apk..."); Config config = Config.getDefaultConfig(); new ApkBuilder(config, sTestNewDir).build(testApk); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void buildAndDecodeTest() { assertTrue(sTestNewDir.isDirectory()); assertTrue(sTestOrigDir.isDirectory()); } private static ExtFile sTmpDir; private static ExtFile sTestOrigDir; private static ExtFile sTestNewDir; private final static Logger LOGGER = Logger.getLogger(EmptyResourcesArscTest.class.getName()); }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt1/LargeIntsInManifestTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt1; import brut.androlib.ApkBuilder; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import java.io.File; import java.io.IOException; import org.junit.*; public class LargeIntsInManifestTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(LargeIntsInManifestTest.class, "aapt1/issue767/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void checkIfLargeIntsAreHandledTest() throws BrutException, IOException { String apk = "issue767.apk"; // decode issue767.apk ApkDecoder apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + apk)); sTestOrigDir = new ExtFile(sTmpDir + File.separator + apk + ".out"); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); // build issue767 ExtFile testApk = new ExtFile(sTmpDir, apk + ".out"); new ApkBuilder(testApk).build(null); String newApk = apk + ".out" + File.separator + "dist" + File.separator + apk; // decode issue767 again apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + newApk)); sTestNewDir = new ExtFile(sTmpDir + File.separator + apk + ".out.two"); outDir = new File(sTmpDir + File.separator + apk + ".out.two"); apkDecoder.decode(outDir); compareXmlFiles("AndroidManifest.xml"); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt1/ProviderAttributeTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt1; import brut.androlib.ApkBuilder; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.custommonkey.xmlunit.XMLUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; import static org.junit.Assert.assertTrue; public class ProviderAttributeTest extends BaseTest { @BeforeClass public static void beforeClass() throws BrutException { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(ProviderAttributeTest.class, "aapt1/issue636/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void isProviderStringReplacementWorking() throws BrutException, IOException, SAXException { String apk = "issue636.apk"; // decode issue636.apk ApkDecoder apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + apk)); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); // build issue636 ExtFile testApk = new ExtFile(sTmpDir, apk + ".out"); new ApkBuilder(testApk).build(null); String newApk = apk + ".out" + File.separator + "dist" + File.separator + apk; assertTrue(fileExists(newApk)); // decode issues636 again apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + newApk)); outDir = new File(sTmpDir + File.separator + apk + ".out.two"); apkDecoder.decode(outDir); String expected = TestUtils.replaceNewlines("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n" + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" android:compileSdkVersion=\"23\" android:compileSdkVersionCodename=\"6.0-2438415\" package=\"com.ibotpeaches.issue636\" platformBuildVersionCode=\"22\" platformBuildVersionName=\"5.1-1756733\">\n" + " <application android:allowBackup=\"true\" android:debuggable=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:theme=\"@style/AppTheme\">\n" + " <provider android:authorities=\"com.ibotpeaches.issue636.Provider\" android:exported=\"false\" android:grantUriPermissions=\"true\" android:label=\"@string/app_name\" android:multiprocess=\"false\" android:name=\"com.ibotpeaches.issue636.Provider\"/>\n" + " <provider android:authorities=\"com.ibotpeaches.issue636.ProviderTwo\" android:exported=\"false\" android:grantUriPermissions=\"true\" android:label=\"@string/app_name\" android:multiprocess=\"false\" android:name=\"com.ibotpeaches.issue636.ProviderTwo\"/>\n" + " </application>\n" + "</manifest>"); byte[] encoded = Files.readAllBytes(Paths.get(sTmpDir + File.separator + apk + ".out.two" + File.separator + "AndroidManifest.xml")); String obtained = TestUtils.replaceNewlines(new String(encoded)); XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); XMLUnit.setCompareUnmatched(false); assertXMLEqual(expected, obtained); } private boolean fileExists(String filepath) { return Files.exists(Paths.get(sTmpDir.getAbsolutePath() + File.separator + filepath)); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt1/ReferenceVersionCodeTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt1; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.androlib.apk.ApkInfo; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertEquals; public class ReferenceVersionCodeTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(ReferenceVersionCodeTest.class, "aapt1/issue1234/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void referenceBecomesLiteralTest() throws BrutException, IOException { String apk = "issue1234.apk"; // decode issue1234.apk ApkDecoder apkDecoder = new ApkDecoder(new ExtFile(sTmpDir + File.separator + apk)); ExtFile decodedApk = new ExtFile(sTmpDir + File.separator + apk + ".out"); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); ApkInfo apkInfo = ApkInfo.load(decodedApk); assertEquals("v1.0.0", apkInfo.versionInfo.versionName); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt1/SharedLibraryTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt1; import brut.androlib.*; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.Framework; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.junit.Assert.assertTrue; public class SharedLibraryTest extends BaseTest { @BeforeClass public static void beforeClass() throws BrutException { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(SharedLibraryTest.class, "aapt1/shared_libraries/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void isFrameworkTaggingWorking() throws AndrolibException { String apkName = "library.apk"; Config config = Config.getDefaultConfig(); config.frameworkDirectory = sTmpDir.getAbsolutePath(); config.frameworkTag = "building"; new Framework(config).installFramework(new File(sTmpDir + File.separator + apkName)); assertTrue(fileExists("2-building.apk")); } @Test public void isFrameworkInstallingWorking() throws AndrolibException { String apkName = "library.apk"; Config config = Config.getDefaultConfig(); config.frameworkDirectory = sTmpDir.getAbsolutePath(); new Framework(config).installFramework(new File(sTmpDir + File.separator + apkName)); assertTrue(fileExists("2.apk")); } @Test public void isSharedResourceDecodingAndRebuildingWorking() throws IOException, BrutException { String library = "library.apk"; String client = "client.apk"; // setup apkOptions Config config = Config.getDefaultConfig(); config.frameworkDirectory = sTmpDir.getAbsolutePath(); config.frameworkTag = "shared"; // install library/framework new Framework(config).installFramework(new File(sTmpDir + File.separator + library)); assertTrue(fileExists("2-shared.apk")); // decode client.apk ApkDecoder apkDecoder = new ApkDecoder(config, new ExtFile(sTmpDir + File.separator + client)); File outDir = new File(sTmpDir + File.separator + client + ".out"); apkDecoder.decode(outDir); // decode library.apk ApkDecoder libraryDecoder = new ApkDecoder(config, new ExtFile(sTmpDir + File.separator + library)); outDir = new File(sTmpDir + File.separator + library + ".out"); libraryDecoder.decode(outDir); // build client.apk ExtFile clientApk = new ExtFile(sTmpDir, client + ".out"); new ApkBuilder(config, clientApk).build(null); assertTrue(fileExists(client + ".out" + File.separator + "dist" + File.separator + client)); // build library.apk (shared library) ExtFile libraryApk = new ExtFile(sTmpDir, library + ".out"); new ApkBuilder(config, libraryApk).build(null); assertTrue(fileExists(library + ".out" + File.separator + "dist" + File.separator + library)); } private boolean fileExists(String filepath) { return Files.exists(Paths.get(sTmpDir.getAbsolutePath() + File.separator + filepath)); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt1/SkipAssetTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt1; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.Config; import brut.androlib.TestUtils; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import java.io.File; import java.io.IOException; import org.junit.*; import static org.junit.Assert.*; public class SkipAssetTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(SkipAssetTest.class, "aapt1/issue1605/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void checkIfEnablingSkipAssetWorks() throws BrutException, IOException { String apk = "issue1605.apk"; Config config = Config.getDefaultConfig(); config.decodeAssets = Config.DECODE_ASSETS_NONE; config.forceDelete = true; // decode issue1605.apk ApkDecoder apkDecoder = new ApkDecoder(config, new ExtFile(sTmpDir + File.separator + apk)); sTestOrigDir = new ExtFile(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(sTestOrigDir); checkFileDoesNotExist("assets" + File.separator + "kotlin.kotlin_builtins"); checkFileDoesNotExist("assets" + File.separator + "ranges" + File.separator + "ranges.kotlin_builtins"); } @Test public void checkControl() throws BrutException, IOException { String apk = "issue1605.apk"; Config config = Config.getDefaultConfig(); config.decodeAssets = Config.DECODE_ASSETS_FULL; config.forceDelete = true; // decode issue1605.apk ApkDecoder apkDecoder = new ApkDecoder(config, new ExtFile(sTmpDir + File.separator + apk)); sTestOrigDir = new ExtFile(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(sTestOrigDir); checkFileDoesExist("assets" + File.separator + "kotlin.kotlin_builtins"); checkFileDoesExist("assets" + File.separator + "ranges" + File.separator + "ranges.kotlin_builtins"); } private void checkFileDoesNotExist(String path) { File f = new File(sTestOrigDir, path); assertFalse(f.isFile()); } private void checkFileDoesExist(String path) { File f = new File(sTestOrigDir, path); assertTrue(f.isFile()); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt1/UnknownCompressionTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt1; import brut.androlib.*; import brut.androlib.Config; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; public class UnknownCompressionTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(UnknownCompressionTest.class, "aapt1/unknown_compression/", sTmpDir); String apk = "deflated_unknowns.apk"; Config config = Config.getDefaultConfig(); config.frameworkDirectory = sTmpDir.getAbsolutePath(); sTestOrigDir = new ExtFile(sTmpDir, apk); // decode deflated_unknowns.apk // need new ExtFile because closed in decode() ApkDecoder apkDecoder = new ApkDecoder(new ExtFile(sTestOrigDir)); File outDir = new File(sTestOrigDir.getAbsolutePath() + ".out"); apkDecoder.decode(outDir); // build deflated_unknowns ExtFile clientApkFolder = new ExtFile(sTestOrigDir.getAbsolutePath() + ".out"); new ApkBuilder(config, clientApkFolder).build(null); sTestNewDir = new ExtFile(clientApkFolder, "dist" + File.separator + apk); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void pkmExtensionDeflatedTest() throws BrutException, IOException { Integer control = sTestOrigDir.getDirectory().getCompressionLevel("assets/bin/Data/test.pkm"); Integer rebuilt = sTestNewDir.getDirectory().getCompressionLevel("assets/bin/Data/test.pkm"); // Check that control = rebuilt (both deflated) // Add extra check for checking not equal to 0, just in case control gets broken assertEquals(control, rebuilt); assertNotSame(0, rebuilt); } @Test public void doubleExtensionStoredTest() throws BrutException, IOException { Integer control = sTestOrigDir.getDirectory().getCompressionLevel("assets/bin/Data/two.extension.file"); Integer rebuilt = sTestNewDir.getDirectory().getCompressionLevel("assets/bin/Data/two.extension.file"); // Check that control = rebuilt (both stored) // Add extra check for checking = 0 to enforce check for stored just in case control breaks assertEquals(control, rebuilt); assertEquals(Integer.valueOf(0), rebuilt); } @Test public void confirmJsonFileIsDeflatedTest() throws BrutException, IOException { Integer control = sTestOrigDir.getDirectory().getCompressionLevel("test.json"); Integer rebuilt = sTestNewDir.getDirectory().getCompressionLevel("test.json"); assertEquals(control, rebuilt); assertEquals(Integer.valueOf(8), rebuilt); } @Test public void confirmPngFileIsCorrectlyDeflatedTest() throws BrutException, IOException { Integer control = sTestOrigDir.getDirectory().getCompressionLevel("950x150.png"); Integer rebuilt = sTestNewDir.getDirectory().getCompressionLevel("950x150.png"); assertEquals(control, rebuilt); assertEquals(Integer.valueOf(8), rebuilt); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt2/BuildAndDecodeTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt2; import brut.androlib.*; import brut.androlib.apk.ApkInfo; import brut.androlib.Config; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import static org.junit.Assert.*; public class BuildAndDecodeTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "testapp-orig"); sTestNewDir = new ExtFile(sTmpDir, "testapp-new"); LOGGER.info("Unpacking testapp..."); TestUtils.copyResourceDir(BuildAndDecodeTest.class, "aapt2/testapp/", sTestOrigDir); Config config = Config.getDefaultConfig(); config.useAapt2 = true; config.verbose = true; LOGGER.info("Building testapp.apk..."); File testApk = new File(sTmpDir, "testapp.apk"); new ApkBuilder(config, sTestOrigDir).build(testApk); LOGGER.info("Decoding testapp.apk..."); ApkDecoder apkDecoder = new ApkDecoder(testApk); apkDecoder.decode(sTestNewDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void buildAndDecodeTest() { assertTrue(sTestNewDir.isDirectory()); } @Test public void valuesStringsTest() throws BrutException { compareValuesFiles("values/strings.xml"); } @Test public void valuesMaxLengthTest() throws BrutException { compareValuesFiles("values-es/strings.xml"); } @Test public void valuesBcp47LanguageVariantTest() throws BrutException { compareValuesFiles("values-b+iw+660/strings.xml"); } @Test public void valuesBcp47LanguageScriptRegionVariantTest() throws BrutException { compareValuesFiles("values-b+ast+Latn+IT+AREVELA/strings.xml"); compareValuesFiles("values-b+ast+Hant+IT+ARABEXT/strings.xml"); } @Test public void confirmZeroByteFileExtensionIsNotStored() throws BrutException { ApkInfo apkInfo = ApkInfo.load(sTestNewDir); assertFalse(apkInfo.doNotCompress.contains("jpg")); } @Test public void confirmZeroByteFileIsStored() throws BrutException { ApkInfo apkInfo = ApkInfo.load(sTestNewDir); assertTrue(apkInfo.doNotCompress.contains("assets/0byte_file.jpg")); } @Test public void navigationResourceTest() throws BrutException { compareXmlFiles("res/navigation/nav_graph.xml"); } @Test public void xmlIdsEmptyTest() throws BrutException { compareXmlFiles("res/values/ids.xml"); } @Test public void leadingDollarSignResourceNameTest() throws BrutException { compareXmlFiles("res/drawable/$avd_hide_password__0.xml"); compareXmlFiles("res/drawable/$avd_show_password__0.xml"); compareXmlFiles("res/drawable/$avd_show_password__1.xml"); compareXmlFiles("res/drawable/$avd_show_password__2.xml"); compareXmlFiles("res/drawable/avd_show_password.xml"); } @Test public void samsungQmgFilesHandledTest() throws IOException, BrutException { compareBinaryFolder("drawable-xhdpi", true); } @Test public void confirmManifestStructureTest() throws BrutException { compareXmlFiles("AndroidManifest.xml"); } @Test public void xmlXsdFileTest() throws BrutException { compareXmlFiles("res/xml/ww_box_styles_schema.xsd"); } @Test public void multipleDexTest() throws BrutException, IOException { compareBinaryFolder("/smali_classes2", false); compareBinaryFolder("/smali_classes3", false); File classes2Dex = new File(sTestOrigDir, "build/apk/classes2.dex"); File classes3Dex = new File(sTestOrigDir, "build/apk/classes3.dex"); assertTrue(classes2Dex.isFile()); assertTrue(classes3Dex.isFile()); } @Test public void singleDexTest() throws BrutException, IOException { compareBinaryFolder("/smali", false); File classesDex = new File(sTestOrigDir, "build/apk/classes.dex"); assertTrue(classesDex.isFile()); } @Test public void unknownFolderTest() throws BrutException { compareUnknownFiles(); } @Test public void confirmPlatformManifestValuesTest() throws IOException, SAXException, ParserConfigurationException { Document doc = loadDocument(new File(sTestNewDir + "/AndroidManifest.xml")); Node application = doc.getElementsByTagName("manifest").item(0); NamedNodeMap attr = application.getAttributes(); Node platformBuildVersionNameAttr = attr.getNamedItem("platformBuildVersionName"); assertEquals("6.0-2438415", platformBuildVersionNameAttr.getNodeValue()); Node platformBuildVersionCodeAttr = attr.getNamedItem("platformBuildVersionCode"); assertEquals("23", platformBuildVersionCodeAttr.getNodeValue()); Node compileSdkVersionAttr = attr.getNamedItem("compileSdkVersion"); assertNull("compileSdkVersion should be stripped via aapt2", compileSdkVersionAttr); Node compileSdkVersionCodenameAttr = attr.getNamedItem("compileSdkVersionCodename"); assertNull("compileSdkVersionCodename should be stripped via aapt2", compileSdkVersionCodenameAttr); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt2/DebuggableFalseChangeToTrueTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt2; import brut.androlib.*; import brut.androlib.Config; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.custommonkey.xmlunit.XMLUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; import static org.junit.Assert.assertTrue; public class DebuggableFalseChangeToTrueTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "issue2328-debuggable-false-orig"); sTestNewDir = new ExtFile(sTmpDir, "issue2328-debuggable-flase-new"); LOGGER.info("Unpacking issue2328-debuggable-flase..."); TestUtils.copyResourceDir(DebuggableFalseChangeToTrueTest.class, "aapt2/issue2328/debuggable-false", sTestOrigDir); LOGGER.info("Building issue2328-debuggable-flase.apk..."); Config config = Config.getDefaultConfig(); config.debugMode = true; config.useAapt2 = true; config.verbose = true; File testApk = new File(sTmpDir, "issue2328-debuggable-flase.apk"); new ApkBuilder(config, sTestOrigDir).build(testApk); LOGGER.info("Decoding issue2328-debuggable-flase.apk..."); ApkDecoder apkDecoder = new ApkDecoder(testApk); apkDecoder.decode(sTestNewDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void buildAndDecodeTest() { assertTrue(sTestNewDir.isDirectory()); } @Test public void DebugIsTruePriorToBeingFalseTest() throws IOException, SAXException { String apk = "issue2328-debuggable-flase-new"; String expected = TestUtils.replaceNewlines("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" " + "package=\"com.ibotpeaches.issue2328\" platformBuildVersionCode=\"20\" " + "platformBuildVersionName=\"4.4W.2-1537038\"> <application android:debuggable=\"true\"/></manifest>"); byte[] encoded = Files.readAllBytes(Paths.get(sTmpDir + File.separator + apk + File.separator + "AndroidManifest.xml")); String obtained = TestUtils.replaceNewlines(new String(encoded)); XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); XMLUnit.setCompareUnmatched(false); assertXMLEqual(expected, obtained); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt2/DebuggableTrueAddedTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt2; import brut.androlib.*; import brut.androlib.Config; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.custommonkey.xmlunit.XMLUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; import static org.junit.Assert.assertTrue; public class DebuggableTrueAddedTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "issue2328-debuggable-missing-orig"); sTestNewDir = new ExtFile(sTmpDir, "issue2328-debuggable-missing-new"); LOGGER.info("Unpacking issue2328-debuggable-missing..."); TestUtils.copyResourceDir(DebuggableTrueAddedTest.class, "aapt2/issue2328/debuggable-missing", sTestOrigDir); LOGGER.info("Building issue2328-debuggable-missing.apk..."); Config config = Config.getDefaultConfig(); config.debugMode = true; config.useAapt2 = true; config.verbose = true; File testApk = new File(sTmpDir, "issue2328-debuggable-missing.apk"); new ApkBuilder(config, sTestOrigDir).build(testApk); LOGGER.info("Decoding issue2328-debuggable-missing.apk..."); ApkDecoder apkDecoder = new ApkDecoder(testApk); apkDecoder.decode(sTestNewDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void buildAndDecodeTest() { assertTrue(sTestNewDir.isDirectory()); } @Test public void DebugIsTruePriorToBeingFalseTest() throws IOException, SAXException { String apk = "issue2328-debuggable-missing-new"; String expected = TestUtils.replaceNewlines("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" " + "package=\"com.ibotpeaches.issue2328\" platformBuildVersionCode=\"20\" " + "platformBuildVersionName=\"4.4W.2-1537038\"> <application android:debuggable=\"true\"/></manifest>"); byte[] encoded = Files.readAllBytes(Paths.get(sTmpDir + File.separator + apk + File.separator + "AndroidManifest.xml")); String obtained = TestUtils.replaceNewlines(new String(encoded)); XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); XMLUnit.setCompareUnmatched(false); assertXMLEqual(expected, obtained); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt2/DebuggableTrueRetainedTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt2; import brut.androlib.*; import brut.androlib.Config; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.custommonkey.xmlunit.XMLUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; import static org.junit.Assert.assertTrue; public class DebuggableTrueRetainedTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "issue2328-debuggable-true-orig"); sTestNewDir = new ExtFile(sTmpDir, "issue2328-debuggable-true-new"); LOGGER.info("Unpacking issue2328-debuggable-true..."); TestUtils.copyResourceDir(DebuggableTrueRetainedTest.class, "aapt2/issue2328/debuggable-true", sTestOrigDir); LOGGER.info("Building issue2328-debuggable-true.apk..."); Config config = Config.getDefaultConfig(); config.debugMode = true; config.useAapt2 = true; config.verbose = true; File testApk = new File(sTmpDir, "issue2328-debuggable-true.apk"); new ApkBuilder(config, sTestOrigDir).build(testApk); LOGGER.info("Decoding issue2328-debuggable-true.apk..."); ApkDecoder apkDecoder = new ApkDecoder(testApk); apkDecoder.decode(sTestNewDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void buildAndDecodeTest() { assertTrue(sTestNewDir.isDirectory()); } @Test public void DebugIsTruePriorToBeingFalseTest() throws IOException, SAXException { String apk = "issue2328-debuggable-true-new"; String expected = TestUtils.replaceNewlines("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" " + "package=\"com.ibotpeaches.issue2328\" platformBuildVersionCode=\"20\" " + "platformBuildVersionName=\"4.4W.2-1537038\"> <application android:debuggable=\"true\"/></manifest>"); byte[] encoded = Files.readAllBytes(Paths.get(sTmpDir + File.separator + apk + File.separator + "AndroidManifest.xml")); String obtained = TestUtils.replaceNewlines(new String(encoded)); XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); XMLUnit.setCompareUnmatched(false); assertXMLEqual(expected, obtained); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt2/NetworkConfigTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt2; import brut.androlib.*; import brut.androlib.Config; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.custommonkey.xmlunit.XMLUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; import static org.junit.Assert.*; public class NetworkConfigTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "testapp-orig"); sTestNewDir = new ExtFile(sTmpDir, "testapp-new"); LOGGER.info("Unpacking testapp..."); TestUtils.copyResourceDir(NetworkConfigTest.class, "aapt2/network_config/", sTestOrigDir); LOGGER.info("Building testapp.apk..."); Config config = Config.getDefaultConfig(); config.netSecConf = true; config.useAapt2 = true; File testApk = new File(sTmpDir, "testapp.apk"); new ApkBuilder(config, sTestOrigDir).build(testApk); LOGGER.info("Decoding testapp.apk..."); ApkDecoder apkDecoder = new ApkDecoder(testApk); apkDecoder.decode(sTestNewDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void buildAndDecodeTest() { assertTrue(sTestNewDir.isDirectory()); } @Test public void netSecConfGeneric() throws IOException, SAXException { LOGGER.info("Comparing network security configuration file..."); String expected = TestUtils.replaceNewlines("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + "<network-security-config><base-config><trust-anchors><certificates src=\"system\"/><certificates src=\"us" + "er\"/></trust-anchors></base-config></network-security-config>"); byte[] encoded = Files.readAllBytes(Paths.get(String.valueOf(sTestNewDir), "res/xml/network_security_config.xml")); String obtained = TestUtils.replaceNewlines(new String(encoded)); XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); XMLUnit.setCompareUnmatched(false); assertXMLEqual(expected, obtained); } @Test public void netSecConfInManifest() throws IOException, ParserConfigurationException, SAXException { LOGGER.info("Validating network security config in Manifest..."); Document doc = loadDocument(new File(sTestNewDir + "/AndroidManifest.xml")); Node application = doc.getElementsByTagName("application").item(0); NamedNodeMap attr = application.getAttributes(); Node debugAttr = attr.getNamedItem("android:networkSecurityConfig"); assertEquals("@xml/network_security_config", debugAttr.getNodeValue()); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt2/NoNetworkConfigTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt2; import brut.androlib.*; import brut.androlib.Config; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.custommonkey.xmlunit.XMLUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class NoNetworkConfigTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "testapp-orig"); sTestNewDir = new ExtFile(sTmpDir, "testapp-new"); LOGGER.info("Unpacking testapp..."); TestUtils.copyResourceDir(NoNetworkConfigTest.class, "aapt2/testapp/", sTestOrigDir); LOGGER.info("Building testapp.apk..."); Config config = Config.getDefaultConfig(); config.netSecConf = true; config.useAapt2 = true; File testApk = new File(sTmpDir, "testapp.apk"); new ApkBuilder(config, sTestOrigDir).build(testApk); LOGGER.info("Decoding testapp.apk..."); ApkDecoder apkDecoder = new ApkDecoder(testApk); apkDecoder.decode(sTestNewDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void buildAndDecodeTest() { assertTrue(sTestNewDir.isDirectory()); } @Test public void netSecConfGeneric() throws IOException, SAXException { LOGGER.info("Comparing network security configuration file..."); String expected = TestUtils.replaceNewlines("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + "<network-security-config><base-config><trust-anchors><certificates src=\"system\"/><certificates src=\"us" + "er\"/></trust-anchors></base-config></network-security-config>"); byte[] encoded = Files.readAllBytes(Paths.get(String.valueOf(sTestNewDir), "res/xml/network_security_config.xml")); String obtained = TestUtils.replaceNewlines(new String(encoded)); XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); XMLUnit.setCompareUnmatched(false); assertXMLEqual(expected, obtained); } @Test public void netSecConfInManifest() throws IOException, ParserConfigurationException, SAXException { LOGGER.info("Validating network security config in Manifest..."); Document doc = loadDocument(new File(sTestNewDir + "/AndroidManifest.xml")); Node application = doc.getElementsByTagName("application").item(0); NamedNodeMap attr = application.getAttributes(); Node debugAttr = attr.getNamedItem("android:networkSecurityConfig"); assertEquals("@xml/network_security_config", debugAttr.getNodeValue()); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/aapt2/NonStandardPkgIdTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.aapt2; import brut.androlib.*; import brut.androlib.apk.ApkInfo; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.ResourcesDecoder; import brut.androlib.res.data.ResTable; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class NonStandardPkgIdTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTmpDir.deleteOnExit(); sTestOrigDir = new ExtFile(sTmpDir, "pkgid8-orig"); sTestNewDir = new ExtFile(sTmpDir, "pkgid8-new"); LOGGER.info("Unpacking pkgid8..."); TestUtils.copyResourceDir(BuildAndDecodeTest.class, "aapt2/pkgid8/", sTestOrigDir); Config config = Config.getDefaultConfig(); config.useAapt2 = true; config.verbose = true; LOGGER.info("Building pkgid8.apk..."); ExtFile testApk = new ExtFile(sTmpDir, "pkgid8.apk"); new ApkBuilder(config, sTestOrigDir).build(testApk); LOGGER.info("Decoding pkgid8.apk..."); ApkInfo testInfo = new ApkInfo(testApk); ResourcesDecoder resourcesDecoder = new ResourcesDecoder(Config.getDefaultConfig(), testInfo); sTestNewDir.mkdirs(); resourcesDecoder.decodeResources(sTestNewDir); resourcesDecoder.decodeManifest(sTestNewDir); mResTable = resourcesDecoder.getResTable(); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void buildAndDecodeTest() { assertTrue(sTestNewDir.isDirectory()); } @Test public void valuesStringsTest() throws BrutException { compareValuesFiles("values/strings.xml"); } @Test public void confirmManifestStructureTest() throws BrutException { compareXmlFiles("AndroidManifest.xml"); } @Test public void confirmResourcesAreFromPkgId8() throws AndrolibException { assertEquals(0x80, mResTable.getPackageId()); assertEquals(0x80, mResTable.getResSpec(0x80020000).getPackage().getId()); assertEquals(0x80, mResTable.getResSpec(0x80020001).getPackage().getId()); assertEquals(0x80, mResTable.getResSpec(0x80030000).getPackage().getId()); } private static ResTable mResTable; }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/apk/ApkInfoReaderTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.apk; import brut.androlib.exceptions.AndrolibException; import org.junit.Test; import static org.junit.Assert.*; public class ApkInfoReaderTest { private void checkStandard(ApkInfo apkInfo) { assertEquals("standard.apk", apkInfo.apkFileName); assertFalse(apkInfo.resourcesAreCompressed); assertEquals(1, apkInfo.doNotCompress.size()); assertEquals("resources.arsc", apkInfo.doNotCompress.iterator().next()); assertFalse(apkInfo.isFrameworkApk); assertNotNull(apkInfo.packageInfo); assertEquals("127", apkInfo.packageInfo.forcedPackageId); assertNull(apkInfo.packageInfo.renameManifestPackage); assertNotNull(apkInfo.getSdkInfo()); assertEquals(2, apkInfo.getSdkInfo().size()); assertEquals("25", apkInfo.getSdkInfo().get("minSdkVersion")); assertEquals("30", apkInfo.getSdkInfo().get("targetSdkVersion")); assertFalse(apkInfo.sharedLibrary); assertFalse(apkInfo.sparseResources); assertNotNull(apkInfo.usesFramework); assertNotNull(apkInfo.usesFramework.ids); assertEquals(1, apkInfo.usesFramework.ids.size()); assertEquals(1, (long)apkInfo.usesFramework.ids.get(0)); assertNull(apkInfo.usesFramework.tag); assertNotNull(apkInfo.versionInfo); assertNull(apkInfo.versionInfo.versionCode); assertNull(apkInfo.versionInfo.versionName); } @Test public void testStandard() throws AndrolibException { ApkInfo apkInfo = ApkInfo.load( this.getClass().getResourceAsStream("/apk/standard.yml")); checkStandard(apkInfo); assertEquals("2.8.1", apkInfo.version); } @Test public void testUnknownFields() throws AndrolibException { ApkInfo apkInfo = ApkInfo.load( this.getClass().getResourceAsStream("/apk/unknown_fields.yml")); checkStandard(apkInfo); assertEquals("2.8.1", apkInfo.version); } @Test public void testSkipIncorrectIndent() throws AndrolibException { ApkInfo apkInfo = ApkInfo.load( this.getClass().getResourceAsStream("/apk/skip_incorrect_indent.yml")); checkStandard(apkInfo); assertNotEquals("2.0.0", apkInfo.version); } @Test public void testFirstIncorrectIndent() throws AndrolibException { ApkInfo apkInfo = ApkInfo.load( this.getClass().getResourceAsStream("/apk/first_incorrect_indent.yml")); checkStandard(apkInfo); assertNotEquals("2.0.0", apkInfo.version); } @Test public void testUnknownFiles() throws AndrolibException { ApkInfo apkInfo = ApkInfo.load( this.getClass().getResourceAsStream("/apk/unknown_files.yml")); assertEquals("2.0.0", apkInfo.version); assertEquals("testapp.apk", apkInfo.apkFileName); assertFalse(apkInfo.isFrameworkApk); assertNotNull(apkInfo.usesFramework); assertEquals(1, apkInfo.usesFramework.ids.size()); assertEquals(1, (long)apkInfo.usesFramework.ids.get(0)); assertNotNull(apkInfo.packageInfo); assertEquals("127", apkInfo.packageInfo.forcedPackageId); assertNotNull(apkInfo.versionInfo); assertEquals("1", apkInfo.versionInfo.versionCode); assertEquals("1.0", apkInfo.versionInfo.versionName); assertFalse(apkInfo.resourcesAreCompressed); assertNotNull(apkInfo.doNotCompress); assertEquals(4, apkInfo.doNotCompress.size()); assertEquals("assets/0byte_file.jpg", apkInfo.doNotCompress.get(0)); assertEquals("arsc", apkInfo.doNotCompress.get(1)); assertEquals("png", apkInfo.doNotCompress.get(2)); assertEquals("mp3", apkInfo.doNotCompress.get(3)); assertNotNull(apkInfo.unknownFiles); assertEquals(7, apkInfo.unknownFiles.size()); assertEquals("8", apkInfo.unknownFiles.get("AssetBundle/assets/a.txt")); assertEquals("8", apkInfo.unknownFiles.get("AssetBundle/b.txt")); assertEquals("8", apkInfo.unknownFiles.get("hidden.file")); assertEquals("8", apkInfo.unknownFiles.get("non\u007Fprintable.file")); assertEquals("0", apkInfo.unknownFiles.get("stored.file")); assertEquals("8", apkInfo.unknownFiles.get("unk_folder/unknown_file")); assertEquals("8", apkInfo.unknownFiles.get("lib_bug603/bug603")); } @Test public void testUlist_with_indent() throws AndrolibException { ApkInfo apkInfo = ApkInfo.load( this.getClass().getResourceAsStream("/apk/list_with_indent.yml")); assertEquals("2.8.0", apkInfo.version); assertEquals("basic.apk", apkInfo.apkFileName); assertFalse(apkInfo.isFrameworkApk); assertNotNull(apkInfo.usesFramework); assertEquals(1, apkInfo.usesFramework.ids.size()); assertEquals(1, (long)apkInfo.usesFramework.ids.get(0)); assertEquals("tag", apkInfo.usesFramework.tag); assertNotNull(apkInfo.packageInfo); assertEquals("127", apkInfo.packageInfo.forcedPackageId); assertEquals("com.test.basic", apkInfo.packageInfo.renameManifestPackage); assertNotNull(apkInfo.getSdkInfo()); assertEquals(3, apkInfo.getSdkInfo().size()); assertEquals("4", apkInfo.getSdkInfo().get("minSdkVersion")); assertEquals("30", apkInfo.getSdkInfo().get("maxSdkVersion")); assertEquals("22", apkInfo.getSdkInfo().get("targetSdkVersion")); assertFalse(apkInfo.sharedLibrary); assertTrue(apkInfo.sparseResources); assertNotNull(apkInfo.unknownFiles); assertEquals(1, apkInfo.unknownFiles.size()); assertEquals("1", apkInfo.unknownFiles.get("hidden.file")); assertNotNull(apkInfo.versionInfo); assertEquals("71", apkInfo.versionInfo.versionCode); assertEquals("1.0.70", apkInfo.versionInfo.versionName); assertNotNull(apkInfo.doNotCompress); assertEquals(2, apkInfo.doNotCompress.size()); assertEquals("resources.arsc", apkInfo.doNotCompress.get(0)); assertEquals("png", apkInfo.doNotCompress.get(1)); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/apk/ApkInfoSerializationTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.apk; import brut.androlib.exceptions.AndrolibException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.*; import static org.junit.Assert.*; public class ApkInfoSerializationTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void checkApkInfoSerialization() throws IOException, AndrolibException { ApkInfo control = ApkInfo.load( this.getClass().getResourceAsStream("/apk/unknown_files.yml")); check(control); File savedApkInfo = folder.newFile( "saved.yml" ); control.save(savedApkInfo); try (FileInputStream fis = new FileInputStream(savedApkInfo)) { ApkInfo saved = ApkInfo.load(fis); check(saved); } } private void check(ApkInfo apkInfo) { assertEquals("2.0.0", apkInfo.version); assertEquals("testapp.apk", apkInfo.apkFileName); assertFalse(apkInfo.isFrameworkApk); assertNotNull(apkInfo.usesFramework); assertEquals(1, apkInfo.usesFramework.ids.size()); assertEquals(1, (long)apkInfo.usesFramework.ids.get(0)); assertNotNull(apkInfo.packageInfo); assertEquals("127", apkInfo.packageInfo.forcedPackageId); assertNotNull(apkInfo.versionInfo); assertEquals("1", apkInfo.versionInfo.versionCode); assertEquals("1.0", apkInfo.versionInfo.versionName); assertFalse(apkInfo.resourcesAreCompressed); assertNotNull(apkInfo.doNotCompress); assertEquals(4, apkInfo.doNotCompress.size()); assertEquals("assets/0byte_file.jpg", apkInfo.doNotCompress.get(0)); assertEquals("arsc", apkInfo.doNotCompress.get(1)); assertEquals("png", apkInfo.doNotCompress.get(2)); assertEquals("mp3", apkInfo.doNotCompress.get(3)); assertNotNull(apkInfo.unknownFiles); assertEquals(7, apkInfo.unknownFiles.size()); assertEquals("8", apkInfo.unknownFiles.get("AssetBundle/assets/a.txt")); assertEquals("8", apkInfo.unknownFiles.get("AssetBundle/b.txt")); assertEquals("8", apkInfo.unknownFiles.get("hidden.file")); assertEquals("8", apkInfo.unknownFiles.get("non\u007Fprintable.file")); assertEquals("0", apkInfo.unknownFiles.get("stored.file")); assertEquals("8", apkInfo.unknownFiles.get("unk_folder/unknown_file")); assertEquals("8", apkInfo.unknownFiles.get("lib_bug603/bug603")); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/apk/ConsistentPropertyTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.apk; import brut.androlib.exceptions.AndrolibException; import org.junit.Test; import static org.junit.Assert.*; public class ConsistentPropertyTest { @Test public void testAssertingAllKnownApkInfoProperties() throws AndrolibException { ApkInfo apkInfo = ApkInfo.load( this.getClass().getResourceAsStream("/apk/basic.yml")); assertEquals("2.8.0", apkInfo.version); assertEquals("basic.apk", apkInfo.apkFileName); assertFalse(apkInfo.isFrameworkApk); assertEquals(1, apkInfo.usesFramework.ids.size()); assertEquals("tag", apkInfo.usesFramework.tag); assertEquals("4", apkInfo.getMinSdkVersion()); assertEquals("22", apkInfo.getTargetSdkVersion()); assertEquals("30", apkInfo.getMaxSdkVersion()); assertEquals("127", apkInfo.packageInfo.forcedPackageId); assertEquals("com.test.basic", apkInfo.packageInfo.renameManifestPackage); assertEquals("71", apkInfo.versionInfo.versionCode); assertEquals("1.0.70", apkInfo.versionInfo.versionName); assertFalse(apkInfo.resourcesAreCompressed); assertFalse(apkInfo.sharedLibrary); assertTrue(apkInfo.sparseResources); assertEquals(1, apkInfo.unknownFiles.size()); assertEquals(2, apkInfo.doNotCompress.size()); assertFalse(apkInfo.compressionType); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/apk/DoNotCompressHieroglyphTest.java
/* * Copyright (C) 2010 Ryszard Wiśniewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.apk; import brut.androlib.exceptions.AndrolibException; import org.junit.Test; import static org.junit.Assert.*; public class DoNotCompressHieroglyphTest { @Test public void testHieroglyph() throws AndrolibException { ApkInfo apkInfo = ApkInfo.load( this.getClass().getResourceAsStream("/apk/donotcompress_with_hieroglyph.yml")); assertEquals("2.0.0", apkInfo.version); assertEquals("testapp.apk", apkInfo.apkFileName); assertEquals(2, apkInfo.doNotCompress.size()); assertEquals("assets/AllAssetBundles/Andriod/tx_1001_冰原1", apkInfo.doNotCompress.get(0)); assertEquals("assets/AllAssetBundles/Andriod/tx_1001_冰原1.manifest", apkInfo.doNotCompress.get(1)); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/apk/InvalidSdkBoundingTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.apk; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class InvalidSdkBoundingTest { @Test public void checkIfInvalidValuesPass() { ApkInfo apkInfo = new ApkInfo(); Map<String, String> sdkInfo = new LinkedHashMap<>(); sdkInfo.put("minSdkVersion", "15"); sdkInfo.put("targetSdkVersion", "25"); sdkInfo.put("maxSdkVersion", "19"); apkInfo.setSdkInfo(sdkInfo); assertEquals("19", apkInfo.checkTargetSdkVersionBounds()); } @Test public void checkIfMissingMinPasses() { ApkInfo apkInfo = new ApkInfo(); Map<String, String> sdkInfo = new LinkedHashMap<>(); sdkInfo.put("targetSdkVersion", "25"); sdkInfo.put("maxSdkVersion", "19"); apkInfo.setSdkInfo(sdkInfo); assertEquals("19", apkInfo.checkTargetSdkVersionBounds()); } @Test public void checkIfMissingMaxPasses() { ApkInfo apkInfo = new ApkInfo(); Map<String, String> sdkInfo = new LinkedHashMap<>(); sdkInfo.put("minSdkVersion", "15"); sdkInfo.put("targetSdkVersion", "25"); apkInfo.setSdkInfo(sdkInfo); assertEquals("25", apkInfo.checkTargetSdkVersionBounds()); } @Test public void checkIfMissingBothPasses() { ApkInfo apkInfo = new ApkInfo(); Map<String, String> sdkInfo = new LinkedHashMap<>(); sdkInfo.put("targetSdkVersion", "25"); apkInfo.setSdkInfo(sdkInfo); assertEquals("25", apkInfo.checkTargetSdkVersionBounds()); } @Test public void checkForShortHandSTag() { ApkInfo apkInfo = new ApkInfo(); Map<String, String> sdkInfo = new LinkedHashMap<>(); sdkInfo.put("targetSdkVersion", "S"); apkInfo.setSdkInfo(sdkInfo); assertEquals("31", apkInfo.checkTargetSdkVersionBounds()); } @Test public void checkForShortHandSdkTag() { ApkInfo apkInfo = new ApkInfo(); Map<String, String> sdkInfo = new LinkedHashMap<>(); sdkInfo.put("targetSdkVersion", "O"); apkInfo.setSdkInfo(sdkInfo); assertEquals("26", apkInfo.checkTargetSdkVersionBounds()); } @Test public void checkForSdkDevelopmentInsaneTestValue() { ApkInfo apkInfo = new ApkInfo(); Map<String, String> sdkInfo = new LinkedHashMap<>(); sdkInfo.put("targetSdkVersion", "VANILLAICECREAM"); apkInfo.setSdkInfo(sdkInfo); assertEquals("10000", apkInfo.checkTargetSdkVersionBounds()); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/apk/MaliciousYamlTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.apk; import brut.androlib.exceptions.AndrolibException; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MaliciousYamlTest { @Test public void testMaliciousYaml() throws AndrolibException { ApkInfo apkInfo = ApkInfo.load( this.getClass().getResourceAsStream("/apk/cve20220476.yml")); assertEquals("2.6.1-ddc4bb-SNAPSHOT", apkInfo.version); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/apk/YamlLineTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.apk; import org.junit.Test; import static org.junit.Assert.*; public class YamlLineTest { @Test public void testEmptyLine() { YamlLine line = new YamlLine(""); assertEquals(0, line.indent); assertTrue(line.isEmpty); line = new YamlLine(" "); assertEquals(0, line.indent); assertTrue(line.isEmpty); } @Test public void testComment() { YamlLine line = new YamlLine("!ApkInfo.class"); assertTrue(line.isComment); line = new YamlLine("# This is comment"); assertEquals(0, line.indent); assertTrue(line.isComment); assertEquals("", line.getKey()); assertEquals("This is comment", line.getValue()); line = new YamlLine(" # This is comment"); assertEquals(2, line.indent); assertTrue(line.isComment); assertEquals("", line.getKey()); assertEquals("This is comment", line.getValue()); } @Test public void testKeyLine() { YamlLine line = new YamlLine("name:"); assertFalse(line.isComment); assertEquals(0, line.indent); assertEquals("name", line.getKey()); assertEquals("", line.getValue()); line = new YamlLine(" name:"); assertFalse(line.isComment); assertEquals(2, line.indent); assertEquals("name", line.getKey()); assertEquals("", line.getValue()); line = new YamlLine(":value"); assertFalse(line.isComment); assertEquals(0, line.indent); assertEquals("", line.getKey()); assertEquals("value", line.getValue()); line = new YamlLine(" : value "); assertFalse(line.isComment); assertEquals(2, line.indent); assertEquals("", line.getKey()); assertEquals("value", line.getValue()); line = new YamlLine("name : value "); assertFalse(line.isComment); assertEquals(0, line.indent); assertEquals("name", line.getKey()); assertEquals("value", line.getValue()); line = new YamlLine(" name : value "); assertFalse(line.isComment); assertEquals(2, line.indent); assertEquals("name", line.getKey()); assertEquals("value", line.getValue()); line = new YamlLine(" name : value ::"); assertFalse(line.isComment); assertEquals(2, line.indent); assertEquals("name", line.getKey()); assertEquals("value", line.getValue()); // split this gives parts.length = 0!! line = new YamlLine(":::"); assertFalse(line.isComment); assertEquals(0, line.indent); assertEquals("", line.getKey()); assertEquals("", line.getValue()); } @Test public void testItemLine() { YamlLine line = new YamlLine("- val1"); assertTrue(line.isItem); assertEquals(0, line.indent); assertEquals("", line.getKey()); assertEquals("val1", line.getValue()); line = new YamlLine(" - val1: ff"); assertTrue(line.isItem); assertEquals(2, line.indent); assertEquals("", line.getKey()); assertEquals("val1: ff", line.getValue()); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/AndResGuardTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.Config; import brut.androlib.TestUtils; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import java.io.File; import java.io.IOException; import org.junit.*; import static org.junit.Assert.*; public class AndResGuardTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(AndResGuardTest.class, "decode/issue1170/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void checkifAndResDecodeRemapsRFolder() throws BrutException, IOException { String apk = "issue1170.apk"; // decode issue1170.apk ApkDecoder apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + apk)); sTestOrigDir = new ExtFile(sTmpDir + File.separator + apk + ".out"); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); File aPng = new File(sTestOrigDir,"res/mipmap-hdpi-v4/a.png"); assertTrue(aPng.isFile()); } @Test public void checkIfAndResDecodeRemapsRFolderInRawMode() throws BrutException, IOException { Config config = Config.getDefaultConfig(); config.forceDelete = true; config.decodeResources = Config.DECODE_RESOURCES_NONE; String apk = "issue1170.apk"; ApkDecoder apkDecoder = new ApkDecoder(config, new File(sTmpDir + File.separator + apk)); sTestOrigDir = new ExtFile(sTmpDir + File.separator + apk + ".raw.out"); File outDir = new File(sTmpDir + File.separator + apk + ".raw.out"); apkDecoder.decode(outDir); File aPng = new File(sTestOrigDir,"r/a/a.png"); assertTrue(aPng.isFile()); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/DecodeArrayTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.BaseTest; import brut.androlib.Config; import brut.androlib.TestUtils; import brut.androlib.apk.ApkInfo; import brut.androlib.res.ResourcesDecoder; import brut.androlib.res.data.ResTable; import brut.androlib.res.data.value.ResArrayValue; import brut.androlib.res.data.value.ResValue; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertTrue; public class DecodeArrayTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(MissingVersionManifestTest.class, "decode/issue1994/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void decodeStringArray() throws BrutException { ExtFile apkFile = new ExtFile(sTmpDir, "issue1994.apk"); ApkInfo apkInfo = new ApkInfo(apkFile); ResourcesDecoder resourcesDecoder = new ResourcesDecoder(Config.getDefaultConfig(), apkInfo); resourcesDecoder.loadMainPkg(); ResTable resTable = resourcesDecoder.getResTable(); ResValue value = resTable.getResSpec(0x7f020001).getDefaultResource().getValue(); assertTrue("Not a ResArrayValue. Found: " + value.getClass(), value instanceof ResArrayValue); } @Test public void decodeArray() throws BrutException { ExtFile apkFile = new ExtFile(sTmpDir, "issue1994.apk"); ApkInfo apkInfo = new ApkInfo(apkFile); ResourcesDecoder resourcesDecoder = new ResourcesDecoder(Config.getDefaultConfig(), apkInfo); resourcesDecoder.loadMainPkg(); ResTable resTable = resourcesDecoder.getResTable(); ResValue value = resTable.getResSpec(0x7f020000).getDefaultResource().getValue(); assertTrue("Not a ResArrayValue. Found: " + value.getClass(), value instanceof ResArrayValue); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/DecodeKotlinCoroutinesTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.*; import brut.androlib.exceptions.AndrolibException; import brut.common.BrutException; import brut.directory.DirectoryException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.junit.Assert.assertTrue; public class DecodeKotlinCoroutinesTest extends BaseTest { private static final String apk = "test-kotlin-coroutines.apk"; @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(DecodeKotlinCoroutinesTest.class, "decode/kotlin-coroutines/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void kotlinCoroutinesDecodeTest() throws IOException, AndrolibException, DirectoryException { Config config = Config.getDefaultConfig(); config.forceDelete = true; // decode kotlin coroutines ApkDecoder apkDecoder = new ApkDecoder(config, new File(sTmpDir + File.separator + apk)); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); File coroutinesExceptionHandler = new File(sTmpDir + File.separator + apk + ".out" + File.separator + "META-INF" + File.separator + "services", "kotlinx.coroutines.CoroutineExceptionHandler"); File coroutinesMainDispatcherHandler = new File(sTmpDir + File.separator + apk + ".out" + File.separator + "META-INF" + File.separator + "services", "kotlinx.coroutines.internal.MainDispatcherFactory"); assert (coroutinesExceptionHandler.exists()); assert (coroutinesMainDispatcherHandler.exists()); } @Test public void kotlinCoroutinesEncodeAfterDecodeTest() throws IOException, BrutException { Config config = Config.getDefaultConfig(); config.forceDelete = true; // decode kotlin coroutines ApkDecoder apkDecoder = new ApkDecoder(config, new File(sTmpDir + File.separator + apk)); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); // build kotlin coroutines ExtFile testApk = new ExtFile(sTmpDir, apk + ".out"); new ApkBuilder(config, testApk).build(null); String newApk = apk + ".out" + File.separator + "dist" + File.separator + apk; assertTrue(fileExists(newApk)); // decode kotlin coroutines again apkDecoder = new ApkDecoder(config, new File(sTmpDir + File.separator + newApk)); outDir = new File(sTmpDir + File.separator + apk + ".out.two"); apkDecoder.decode(outDir); Files.readAllBytes(Paths.get(sTmpDir + File.separator + apk + ".out.two" + File.separator + "AndroidManifest.xml")); File coroutinesExceptionHandler = new File(sTmpDir + File.separator + apk + ".out.two" + File.separator + "META-INF" + File.separator + "services", "kotlinx.coroutines.CoroutineExceptionHandler"); File coroutinesMainDispatcherHandler = new File(sTmpDir + File.separator + apk + ".out.two" + File.separator + "META-INF" + File.separator + "services", "kotlinx.coroutines.internal.MainDispatcherFactory"); assert (coroutinesExceptionHandler.exists()); assert (coroutinesMainDispatcherHandler.exists()); } private boolean fileExists(String filepath) { return Files.exists(Paths.get(sTmpDir.getAbsolutePath() + File.separator + filepath)); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/DecodeKotlinTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.apache.commons.io.FileUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertTrue; public class DecodeKotlinTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(DecodeKotlinTest.class, "decode/testkotlin/", sTmpDir); String apk = "testkotlin.apk"; // decode testkotlin.apk ApkDecoder apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + apk)); sTestNewDir = new ExtFile(sTmpDir + File.separator + apk + ".out"); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void kotlinFolderExistsTest() { assertTrue(sTestNewDir.isDirectory()); File testKotlinFolder = new File(sTestNewDir, "kotlin"); assertTrue(testKotlinFolder.isDirectory()); } @Test public void kotlinDecodeTest() throws IOException { File kotlinActivity = new File(sTestNewDir, "smali/org/example/kotlin/mixed/KotlinActivity.smali"); assertTrue(FileUtils.readFileToString(kotlinActivity, "UTF-8").contains("KotlinActivity.kt")); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/DoubleExtensionUnknownFileTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.androlib.apk.ApkInfo; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.apache.commons.lang3.StringUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertTrue; public class DoubleExtensionUnknownFileTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(DoubleExtensionUnknownFileTest.class, "decode/issue1244/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void multipleExtensionUnknownFileTest() throws BrutException, IOException { String apk = "issue1244.apk"; // decode issue1244.apk ApkDecoder apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + apk)); ExtFile decodedApk = new ExtFile(sTmpDir + File.separator + apk + ".out"); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); ApkInfo apkInfo = ApkInfo.load(decodedApk); for (String string : apkInfo.doNotCompress) { if (StringUtils.countMatches(string, ".") > 1) { assertTrue(string.equalsIgnoreCase("assets/bin/Data/sharedassets1.assets.split0")); } } } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/DuplicateDexTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.*; import brut.androlib.exceptions.AndrolibException; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.*; import java.io.File; import java.io.IOException; public class DuplicateDexTest extends BaseTest { @Before public void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "duplicatedex-orig"); sTestNewDir = new ExtFile(sTmpDir, "duplicatedex-new"); LOGGER.info("Unpacking duplicatedex.apk..."); TestUtils.copyResourceDir(DuplicateDexTest.class, "decode/duplicatedex", sTestOrigDir); } @After public void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test(expected = AndrolibException.class) public void decodeAllSourcesShouldThrowException() throws BrutException, IOException { File testApk = new File(sTestOrigDir, "duplicatedex.apk"); LOGGER.info("Decoding duplicatedex.apk..."); ApkDecoder apkDecoder = new ApkDecoder(testApk); apkDecoder.decode(sTestNewDir); LOGGER.info("Building duplicatedex.apk..."); Config config = Config.getDefaultConfig(); new ApkBuilder(config, sTestNewDir).build(testApk); } @Test public void decodeUsingOnlyMainClassesMode() throws BrutException, IOException { File testApk = new File(sTestOrigDir, "duplicatedex.apk"); LOGGER.info("Decoding duplicatedex.apk..."); Config config = Config.getDefaultConfig(); config.decodeSources = Config.DECODE_SOURCES_SMALI_ONLY_MAIN_CLASSES; ApkDecoder apkDecoder = new ApkDecoder(config, testApk); apkDecoder.decode(sTestNewDir); LOGGER.info("Building duplicatedex.apk..."); new ApkBuilder(config, sTestNewDir).build(testApk); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/Empty9PatchTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class Empty9PatchTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(Empty9PatchTest.class, "decode/empty9patch/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void decodeWithEmpty9PatchFile() throws BrutException, IOException { String apk = "empty9patch.apk"; // decode empty9patch.apk ApkDecoder apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + apk)); sTestOrigDir = new ExtFile(sTmpDir + File.separator + apk + ".out"); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); File aPng = new File(sTestOrigDir,"res/drawable-xhdpi/empty.9.png"); assertTrue(aPng.isFile()); assertEquals(0, aPng.length()); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/EmptyArscTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertTrue; public class EmptyArscTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(EmptyArscTest.class, "decode/issue2701/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void decodeWithEmptyArscFile() throws BrutException, IOException { String apk = "test.apk"; // decode test.apk ApkDecoder apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + apk)); sTestOrigDir = new ExtFile(sTmpDir + File.separator + apk + ".out"); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); File publicXmlFile = new File(sTestOrigDir,"res/values/public.xml"); assertTrue(publicXmlFile.isFile()); File androidManifestXmlFile = new File(sTestOrigDir,"AndroidManifest.xml"); assertTrue(androidManifestXmlFile.isFile()); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/ExternalEntityTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.ApkBuilder; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; public class ExternalEntityTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { sTestOrigDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(ExternalEntityTest.class, "decode/doctype/", sTestOrigDir); LOGGER.info("Building doctype.apk..."); File testApk = new File(sTestOrigDir, "doctype.apk"); new ApkBuilder(sTestOrigDir).build(testApk); LOGGER.info("Decoding doctype.apk..."); ApkDecoder apkDecoder = new ApkDecoder(testApk); File outDir = new File(sTestOrigDir + File.separator + "output"); apkDecoder.decode(outDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTestOrigDir); } @Test public void doctypeTest() throws IOException { String expected = TestUtils.replaceNewlines("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<manifest android:versionCode=\"1\" android:versionName=\"1.0\" android:compileSdkVersion=\"23\" android:compileSdkVersionCodename=\"6.0-2438415\" " + "hardwareAccelerated=\"true\" package=\"com.ibotpeaches.doctype\" platformBuildVersionCode=\"24\" platformBuildVersionName=\"6.0-2456767\" " + "xmlns:android=\"http://schemas.android.com/apk/res/android\"> <supports-screens android:anyDensity=\"true\" android:smallScreens=\"true\" " + "android:normalScreens=\"true\" android:largeScreens=\"true\" android:resizeable=\"true\" android:xlargeScreens=\"true\" /></manifest>"); byte[] encoded = Files.readAllBytes(Paths.get(sTestOrigDir + File.separator + "output" + File.separator + "AndroidManifest.xml")); String obtained = TestUtils.replaceNewlines(new String(encoded)); assertEquals(expected, obtained); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/ForceManifestDecodeNoResourcesTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.Config; import brut.androlib.TestUtils; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.Arrays; import static org.junit.Assert.*; public class ForceManifestDecodeNoResourcesTest extends BaseTest { private final byte[] xmlHeader = new byte[] { 0x3C, // < 0x3F, // ? 0x78, // x 0x6D, // m 0x6C, // l 0x20, // (empty) }; @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(ForceManifestDecodeNoResourcesTest.class, "decode/issue1680/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void checkIfForceManifestWithNoResourcesWorks() throws BrutException, IOException { String apk = "issue1680.apk"; String output = sTmpDir + File.separator + apk + ".out"; // decode issue1680.apk decodeFile(sTmpDir + File.separator + apk, Config.DECODE_RESOURCES_NONE, Config.FORCE_DECODE_MANIFEST_FULL, output); // let's probe filetype of manifest, we should detect XML File manifestFile = new File(output + File.separator + "AndroidManifest.xml"); byte[] magic = TestUtils.readHeaderOfFile(manifestFile, 6); assertArrayEquals(this.xmlHeader, magic); // confirm resources.arsc still exists, as its raw File resourcesArsc = new File(output + File.separator + "resources.arsc"); assertTrue(resourcesArsc.isFile()); } @Test public void checkIfForceManifestWorksWithNoChangeToResources() throws BrutException, IOException { String apk = "issue1680.apk"; String output = sTmpDir + File.separator + apk + ".out"; // decode issue1680.apk decodeFile(sTmpDir + File.separator + apk, Config.DECODE_RESOURCES_FULL, Config.FORCE_DECODE_MANIFEST_FULL, output); // let's probe filetype of manifest, we should detect XML File manifestFile = new File(output + File.separator + "AndroidManifest.xml"); byte[] magic = TestUtils.readHeaderOfFile(manifestFile, 6); assertArrayEquals(this.xmlHeader, magic); // confirm resources.arsc does not exist File resourcesArsc = new File(output + File.separator + "resources.arsc"); assertFalse(resourcesArsc.isFile()); } @Test public void checkForceManifestToFalseWithResourcesEnabledIsIgnored() throws BrutException, IOException { String apk = "issue1680.apk"; String output = sTmpDir + File.separator + apk + ".out"; // decode issue1680.apk decodeFile(sTmpDir + File.separator + apk, Config.DECODE_RESOURCES_FULL, Config.FORCE_DECODE_MANIFEST_NONE, output); // lets probe filetype of manifest, we should detect XML File manifestFile = new File(output + File.separator + "AndroidManifest.xml"); byte[] magic = TestUtils.readHeaderOfFile(manifestFile, 6); assertArrayEquals(this.xmlHeader, magic); // confirm resources.arsc does not exist File resourcesArsc = new File(output + File.separator + "resources.arsc"); assertFalse(resourcesArsc.isFile()); } @Test public void checkBothManifestAndResourcesSetToNone() throws BrutException, IOException { String apk = "issue1680.apk"; String output = sTmpDir + File.separator + apk + ".out"; // decode issue1680.apk decodeFile(sTmpDir + File.separator + apk, Config.DECODE_RESOURCES_NONE, Config.FORCE_DECODE_MANIFEST_NONE, output); // lets probe filetype of manifest, we should not detect XML File manifestFile = new File(output + File.separator + "AndroidManifest.xml"); byte[] magic = TestUtils.readHeaderOfFile(manifestFile, 6); assertFalse(Arrays.equals(this.xmlHeader, magic)); // confirm resources.arsc exists File resourcesArsc = new File(output + File.separator + "resources.arsc"); assertTrue(resourcesArsc.isFile()); } private void decodeFile(String apk, short decodeResources, short decodeManifest, String output) throws BrutException, IOException { Config config = Config.getDefaultConfig(); config.forceDelete = true; config.decodeResources = decodeResources; config.forceDecodeManifest = decodeManifest; ApkDecoder apkDecoder = new ApkDecoder(config, new File(apk)); apkDecoder.decode(new File(output)); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/MinifiedArscTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.Config; import brut.androlib.TestUtils; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; public class MinifiedArscTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(MinifiedArscTest.class, "decode/issue1157/", sTmpDir); String apk = "issue1157.apk"; sTestNewDir = new ExtFile(sTmpDir, "issue1157"); Config config = Config.getDefaultConfig(); config.forceDelete = true; // decode issue1157.apk ApkDecoder apkDecoder = new ApkDecoder(config, new ExtFile(sTmpDir, apk)); // this should not raise an exception: apkDecoder.decode(sTestNewDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void checkIfMinifiedArscLayoutFileMatchesTest() throws IOException { String expected = TestUtils.replaceNewlines("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<LinearLayout n1:orientation=\"vertical\" n1:layout_width=\"fill_parent\" n1:layout_height=\"fill_parent\"\n" + " xmlns:n1=\"http://schemas.android.com/apk/res/android\">\n" + " <com.ibotpeaches.issue1157.MyCustomView n1:max=\"100\" n2:default_value=\"1.0\" n2:max_value=\"5.0\" n2:min_value=\"0.2\" xmlns:n2=\"http://schemas.android.com/apk/res-auto\" />\n" + "</LinearLayout>"); byte[] encoded = Files.readAllBytes(Paths.get(sTestNewDir + File.separator + "res" + File.separator + "xml" + File.separator + "custom.xml")); String obtained = TestUtils.replaceNewlines(new String(encoded)); assertEquals(expected, obtained); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/MissingDiv9PatchTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.androlib.res.decoder.Res9patchStreamDecoder; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import static org.junit.Assert.*; public class MissingDiv9PatchTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(MissingDiv9PatchTest.class, "decode/issue1522/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void assertMissingDivAdded() throws Exception { InputStream inputStream = getFileInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Res9patchStreamDecoder decoder = new Res9patchStreamDecoder(); decoder.decode(inputStream, outputStream); BufferedImage image = ImageIO.read(new ByteArrayInputStream(outputStream.toByteArray())); int height = image.getHeight() - 1; // First and last pixel will be invisible, so lets check the first column and ensure its all black for (int y = 1; y < height; y++) { assertEquals("y coordinate failed at: " + y, NP_COLOR, image.getRGB(0, y)); } } private FileInputStream getFileInputStream() throws IOException { File file = new File(sTmpDir, "pip_dismiss_scrim.9.png"); return new FileInputStream(file.toPath().toString()); } private static final int NP_COLOR = 0xff000000; }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/MissingVersionManifestTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.androlib.apk.ApkInfo; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertNull; public class MissingVersionManifestTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(MissingVersionManifestTest.class, "decode/issue1264/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void missingVersionParsesCorrectlyTest() throws BrutException, IOException { String apk = "issue1264.apk"; // decode issue1264.apk ApkDecoder apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + apk)); ExtFile decodedApk = new ExtFile(sTmpDir + File.separator + apk + ".out"); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); ApkInfo apkInfo = ApkInfo.load(decodedApk); assertNull(apkInfo.versionInfo.versionName); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/OutsideOfDirectoryEntryTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class OutsideOfDirectoryEntryTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(OutsideOfDirectoryEntryTest.class, "decode/issue1589/", sTmpDir); String apk = "issue1589.apk"; // decode issue1589.apk ApkDecoder apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + apk)); sTestNewDir = new ExtFile(sTmpDir + File.separator + apk + ".out"); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void skippedDecodingOfInvalidFileTest() { assertTrue(sTestNewDir.isDirectory()); File testAssetFolder = new File(sTestNewDir, "assets"); assertFalse(testAssetFolder.isDirectory()); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/ParentDirectoryTraversalTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.Config; import brut.androlib.TestUtils; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; public class ParentDirectoryTraversalTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(ParentDirectoryTraversalTest.class, "decode/issue1498/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void checkIfDrawableFileDecodesProperly() throws BrutException, IOException { String apk = "issue1498.apk"; Config config = Config.getDefaultConfig(); config.forceDelete = true; config.decodeResources = Config.DECODE_RESOURCES_NONE; // decode issue1498.apk ApkDecoder apkDecoder = new ApkDecoder(config, new File(sTmpDir + File.separator + apk)); File outDir = new File(sTmpDir + File.separator + apk + ".out"); // this should not raise an exception: apkDecoder.decode(outDir); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/ProtectedApkTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import java.io.File; import java.io.IOException; import org.junit.*; import static org.junit.Assert.*; public class ProtectedApkTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(ProtectedApkTest.class, "decode/protected-chunks/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void checkIfDecodeWorksWithoutCrash() throws BrutException, IOException { String apk = "protected-v1.apk"; // decode protected-v1.apk ApkDecoder apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + apk)); sTestOrigDir = new ExtFile(sTmpDir + File.separator + apk + ".out"); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); File stringsXml = new File(sTestOrigDir,"res/values/strings.xml"); assertTrue(stringsXml.isFile()); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/SparseFlagTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.*; import brut.androlib.apk.ApkInfo; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class SparseFlagTest extends BaseTest { @Before public void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "sparse-orig"); sTestNewDir = new ExtFile(sTmpDir, "sparse-new"); LOGGER.info("Unpacking sparse.apk && not-sparse.apk..."); TestUtils.copyResourceDir(SparseFlagTest.class, "decode/sparse", sTestOrigDir); } @After public void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void decodeWithExpectationOfSparseResources() throws BrutException, IOException { File testApk = new File(sTestOrigDir, "sparse.apk"); LOGGER.info("Decoding sparse.apk..."); Config config = Config.getDefaultConfig(); ApkDecoder apkDecoder = new ApkDecoder(config, testApk); ApkInfo apkInfo = apkDecoder.decode(sTestNewDir); assertTrue("Expecting sparse resources", apkInfo.sparseResources); LOGGER.info("Building sparse.apk..."); new ApkBuilder(config, sTestNewDir).build(testApk); } @Test public void decodeWithExpectationOfNoSparseResources() throws BrutException, IOException { File testApk = new File(sTestOrigDir, "not-sparse.apk"); LOGGER.info("Decoding not-sparse.apk..."); Config config = Config.getDefaultConfig(); ApkDecoder apkDecoder = new ApkDecoder(config, testApk); ApkInfo apkInfo = apkDecoder.decode(sTestNewDir); assertFalse("Expecting not-sparse resources", apkInfo.sparseResources); LOGGER.info("Building not-sparse.apk..."); new ApkBuilder(config, sTestNewDir).build(testApk); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/decode/VectorDrawableTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.decode; import brut.androlib.ApkDecoder; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertTrue; public class VectorDrawableTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(VectorDrawableTest.class, "decode/issue1456/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void checkIfDrawableFileDecodesProperly() throws BrutException, IOException { String apk = "issue1456.apk"; // decode issue1456.apk ApkDecoder apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + apk)); sTestOrigDir = new ExtFile(sTmpDir + File.separator + apk + ".out"); File outDir = new File(sTmpDir + File.separator + apk + ".out"); apkDecoder.decode(outDir); checkFileExists("res/drawable/ic_arrow_drop_down_black_24dp.xml"); checkFileExists("res/drawable/ic_android_black_24dp.xml"); } private void checkFileExists(String path) { File f = new File(sTestOrigDir, path); assertTrue(f.isFile()); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/encoders/PositionalEnumerationTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.encoders; import brut.androlib.BaseTest; import brut.androlib.res.xml.ResXmlEncoders; import org.junit.Test; import static org.junit.Assert.assertEquals; public class PositionalEnumerationTest extends BaseTest { @Test public void noArgumentsTest() { assertEquals("test", enumerateArguments("test")); } @Test public void twoArgumentsTest() { assertEquals("%1$s, %2$s, and 1 other.", enumerateArguments("%s, %s, and 1 other.")); } @Test public void twoPositionalArgumentsTest() { assertEquals("%1$s, %2$s and 1 other", enumerateArguments("%1$s, %2$s and 1 other")); } @Test public void threeArgumentsTest() { assertEquals("%1$s, %2$s, and %3$d other.", enumerateArguments("%s, %s, and %d other.")); } @Test public void threePositionalArgumentsTest() { assertEquals(" %1$s, %2$s and %3$d other", enumerateArguments(" %1$s, %2$s and %3$d other")); } @Test public void fourArgumentsTest() { assertEquals("%1$s, %2$s, and %3$d other and %4$d.", enumerateArguments("%s, %s, and %d other and %d.")); } @Test public void fourPositionalArgumentsTest() { assertEquals(" %1$s, %2$s and %3$d other and %4$d.", enumerateArguments(" %1$s, %2$s and %3$d other and %4$d.")); } private String enumerateArguments(String value) { return ResXmlEncoders.enumerateNonPositionalSubstitutionsIfRequired(value); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/res/decoder/StringBlockWithSurrogatePairInUtf8Test.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.decoder; import org.junit.Test; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertEquals; public class StringBlockWithSurrogatePairInUtf8Test { @Test public void decodeSingleOctet() { final String actual = new StringBlock("abcDEF123".getBytes(StandardCharsets.UTF_8), true).decodeString(0, 9); assertEquals("Incorrect decoding", "abcDEF123", actual); } @Test public void decodeTwoOctets() { final String actual0 = new StringBlock(new byte[] { (byte) 0xC2, (byte) 0x80}, true).decodeString(0, 2); assertEquals("Incorrect decoding", "\u0080", actual0); final String actual1 = new StringBlock(new byte[] { (byte) 0xDF, (byte) 0xBF}, true).decodeString(0, 2); assertEquals("Incorrect decoding", "\u07FF", actual1); } @Test public void decodeThreeOctets() { final String actual0 = new StringBlock(new byte[] { (byte) 0xE0, (byte) 0xA0, (byte) 0x80}, true).decodeString(0, 3); assertEquals("Incorrect decoding", "\u0800", actual0); final String actual1 = new StringBlock(new byte[] { (byte) 0xEF, (byte) 0xBF, (byte) 0xBF}, true).decodeString(0, 3); assertEquals("Incorrect decoding", "\uFFFF", actual1); } @Test public void decodeSurrogatePair_when_givesAsThreeOctetsFromInvalidRangeOfUtf8() { // See: https://github.com/iBotPeaches/Apktool/issues/2299 final String actual = new StringBlock(new byte[] { (byte) 0xED, (byte) 0xA0, (byte) 0xBD, (byte) 0xED, (byte) 0xB4, (byte) 0x86}, true).decodeString(0, 6); assertEquals("Incorrect decoding", "\uD83D\uDD06", actual); // See: https://github.com/iBotPeaches/Apktool/issues/2546 final byte[] bytesWithCharactersBeforeSurrogatePair = {'G', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g', '!', ' ', (byte) 0xED, (byte) 0xA0, (byte) 0xBD, (byte) 0xED, (byte) 0xB1, (byte) 0x8B, ' ', 'S', 'u', 'n', ' ', (byte) 0xED, (byte) 0xA0, (byte) 0xBC, (byte) 0xED, (byte) 0xBC, (byte) 0x9E }; final String actual2 = new StringBlock(bytesWithCharactersBeforeSurrogatePair, true).decodeString(0, 31); // D83D -> 0xED 0xA0 0xBD // DC4B -> 0xED 0xB1 0x8B // D83C -> 0xED 0xA0 0xBC // DF1E -> 0xED 0xBC 0x9E assertEquals("Incorrect decoding when there are valid characters before the surrogate pair", "Good morning! \uD83D\uDC4B Sun \uD83C\uDF1E", actual2); } @Test public void decodeSurrogatePair_when_givesAsThreeOctetsFromTheValidRangeOfUtf8() { // \u10FFFF is encoded in UTF-8 as "0xDBFF 0xDFFF" (4-byte encoding), // but when used in Android resources which are encoded in UTF-8, 3-byte encoding is used, // so each of these is encoded as 3-bytes final String actual = new StringBlock(new byte[] { (byte) 0xED, (byte) 0xAF, (byte) 0xBF, (byte) 0xED, (byte) 0xBF, (byte) 0xBF}, true).decodeString(0, 6); assertEquals("Incorrect decoding", "\uDBFF\uDFFF", actual); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/res/src/DexStaticFieldValueTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.res.src; import brut.androlib.*; import brut.androlib.aapt2.BuildAndDecodeTest; import brut.androlib.Config; import brut.common.BrutException; import brut.directory.ExtFile; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; public class DexStaticFieldValueTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); sTestOrigDir = new ExtFile(sTmpDir, "issue2543-orig"); sTestNewDir = new ExtFile(sTmpDir, "issue2543-new"); LOGGER.info("Unpacking issue2543..."); TestUtils.copyResourceDir(BuildAndDecodeTest.class, "decode/issue2543/", sTestOrigDir); Config config = Config.getDefaultConfig(); LOGGER.info("Building issue2543.apk..."); File testApk = new File(sTmpDir, "issue2543.apk"); new ApkBuilder(config, sTestOrigDir).build(testApk); LOGGER.info("Decoding issue2543.apk..."); config.baksmaliDebugMode = false; ApkDecoder apkDecoder = new ApkDecoder(config, new ExtFile(testApk)); apkDecoder.decode(sTestNewDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void disassembleDexFileToKeepDefaultParameters() throws IOException { String expected = TestUtils.replaceNewlines( ".class public LHelloWorld;\n" + ".super Ljava/lang/Object;\n" + "\n" + "\n" + "# static fields\n" + ".field private static b:Z = false\n" + "\n" + ".field private static c:Z = true\n" + "\n" + "\n" + "# direct methods\n" + ".method public static main([Ljava/lang/String;)V\n" + " .locals 1\n" + "\n" + " return-void\n" + ".end method"); byte[] encoded = Files.readAllBytes(Paths.get(sTestNewDir + File.separator + "smali" + File.separator + "HelloWorld.smali")); String obtained = TestUtils.replaceNewlines(new String(encoded)); assertEquals(expected, obtained); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/util/AaptVersionTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.util; import brut.common.BrutException; import brut.util.AaptManager; import org.junit.Test; import static org.junit.Assert.assertEquals; public class AaptVersionTest { @Test public void testAapt2Iterations() throws BrutException { assertEquals(2, AaptManager.getAppVersionFromString("Android Asset Packaging Tool (aapt) 2:17")); assertEquals(2, AaptManager.getAppVersionFromString("Android Asset Packaging Tool (aapt) 2.17")); assertEquals(1, AaptManager.getAppVersionFromString("Android Asset Packaging Tool, v0.9")); assertEquals(1, AaptManager.getAppVersionFromString("Android Asset Packaging Tool, v0.2-2679779")); } }
Java
Apktool/brut.apktool/apktool-lib/src/test/java/brut/androlib/util/UnknownDirectoryTraversalTest.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * 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 * * https://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 brut.androlib.util; import brut.androlib.BaseTest; import brut.androlib.TestUtils; import brut.common.BrutException; import brut.common.InvalidUnknownFileException; import brut.common.RootUnknownFileException; import brut.common.TraversalUnknownFileException; import brut.directory.ExtFile; import brut.util.BrutIO; import brut.util.OS; import brut.util.OSDetection; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class UnknownDirectoryTraversalTest extends BaseTest { @BeforeClass public static void beforeClass() throws Exception { sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(UnknownDirectoryTraversalTest.class, "util/traversal", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void validFileTest() throws IOException, BrutException { String validFilename = BrutIO.sanitizeUnknownFile(sTmpDir, "file"); assertEquals(validFilename, "file"); File validFile = new File(sTmpDir, validFilename); assertTrue(validFile.isFile()); } @Test(expected = TraversalUnknownFileException.class) public void invalidBackwardFileTest() throws IOException, BrutException { BrutIO.sanitizeUnknownFile(sTmpDir, "../file"); } @Test(expected = RootUnknownFileException.class) public void invalidRootFileTest() throws IOException, BrutException { String rootLocation = OSDetection.isWindows() ? "C:/" : File.separator; BrutIO.sanitizeUnknownFile(sTmpDir, rootLocation + "file"); } @Test(expected = InvalidUnknownFileException.class) public void noFilePassedTest() throws IOException, BrutException { BrutIO.sanitizeUnknownFile(sTmpDir, ""); } @Test(expected = TraversalUnknownFileException.class) public void invalidBackwardPathOnWindows() throws IOException, BrutException { String invalidPath; if (! OSDetection.isWindows()) { invalidPath = "../../app"; } else { invalidPath = "..\\..\\app.exe"; } BrutIO.sanitizeUnknownFile(sTmpDir, invalidPath); } @Test public void validDirectoryFileTest() throws IOException, BrutException { String validFilename = BrutIO.sanitizeUnknownFile(sTmpDir, "dir" + File.separator + "file"); assertEquals("dir" + File.separator + "file", validFilename); } }
YAML
Apktool/brut.apktool/apktool-lib/src/test/resources/aapt1/issue1235/apktool.yml
version: 2.0.0 apkFileName: issue1235.apk isFrameworkApk: false usesFramework: ids: - 1 packageInfo: forcedPackageId: '127' versionInfo: versionCode: '1' versionName: '1.0' compressionType: false
Apktool/brut.apktool/apktool-lib/src/test/resources/aapt1/issue1481/smali/com/ibotpeaches/issue1481/BuildConfig.smali
.class public final Lcom/ibotpeaches/issue1481/BuildConfig; .super Ljava/lang/Object; .source "BuildConfig.java" # static fields .field public static final APPLICATION_ID:Ljava/lang/String; = "com.ibotpeaches.issue1481" .field public static final BUILD_TYPE:Ljava/lang/String; = "debug" .field public static final DEBUG:Z .field public static final FLAVOR:Ljava/lang/String; = "" .field public static final VERSION_CODE:I = 0x1 .field public static final VERSION_NAME:Ljava/lang/String; = "1.0" # direct methods .method static constructor <clinit>()V .registers 1 .prologue .line 7 const-string v0, "true" invoke-static {v0}, Ljava/lang/Boolean;->parseBoolean(Ljava/lang/String;)Z move-result v0 sput-boolean v0, Lcom/ibotpeaches/issue1481/BuildConfig;->DEBUG:Z return-void .end method .method public constructor <init>()V .registers 1 .prologue .line 6 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method
YAML
Apktool/brut.apktool/apktool-lib/src/test/resources/aapt1/testapp/apktool.yml
version: 2.0.0 apkFileName: testapp.apk isFrameworkApk: false usesFramework: ids: - 1 packageInfo: forcedPackageId: '127' versionInfo: versionCode: '1' versionName: '1.0' compressionType: false doNotCompress: - assets/0byte_file.jpg - arsc - png - mp3 unknownFiles: AssetBundle/assets/a.txt: '8' AssetBundle/b.txt: '8' hidden.file: '8' non\u007Fprintable.file: '8' stored.file: '0' unk_folder/unknown_file: '8' lib_bug603/bug603: '8'
Apktool/brut.apktool/apktool-lib/src/test/resources/aapt1/testapp/res/xml/ww_box_styles_schema.xsd
<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="test"> <xs:complexType> <xs:sequence> <xs:element name="person" type="xs:string"/> <xs:element name="address"> <xs:complexType> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="address" type="xs:string"/> <xs:element name="city" type="xs:string"/> <xs:element name="country" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
Apktool/brut.apktool/apktool-lib/src/test/resources/aapt1/testapp/smali/HelloWorld.smali
.class public LHelloWorld; .super Ljava/lang/Object; .method public static main([Ljava/lang/String;)V .registers 2 sget-object v0, Ljava/lang/System;->out:Ljava/io/PrintStream; const/high16 v1, 0x7f020000 invoke-virtual {v0, v1}, Ljava/io/PrintStream;->println(Ljava/lang/String;)V return-void .end method
Apktool/brut.apktool/apktool-lib/src/test/resources/aapt1/testapp/smali_classes2/HelloDualDexSupport.smali
.class public LHelloDualDexSupport; .super Ljava/lang/Object; .method public static main([Ljava/lang/String;)V .registers 2 sget-object v0, Ljava/lang/System;->out:Ljava/io/PrintStream; const/high16 v1, 0x7f020000 invoke-virtual {v0, v1}, Ljava/io/PrintStream;->println(Ljava/lang/String;)V return-void .end method
Apktool/brut.apktool/apktool-lib/src/test/resources/aapt1/testapp/smali_classes3/HelloTripleDexSupport.smali
.class public LHelloTripleDexSupport; .super Ljava/lang/Object; .method public static main([Ljava/lang/String;)V .registers 2 sget-object v0, Ljava/lang/System;->out:Ljava/io/PrintStream; const/high16 v1, 0x7f020000 invoke-virtual {v0, v1}, Ljava/io/PrintStream;->println(Ljava/lang/String;)V return-void .end method
Apktool/brut.apktool/apktool-lib/src/test/resources/aapt1/testjar/smali/com/apktool/test/Test.smali
.class public LTest; .super Ljava/lang/Object; .method public static main([Ljava/lang/String;)V .registers 2 sget-object v0, Ljava/lang/System;->out:Ljava/io/PrintStream; const/high16 v1, 0x7f020000 invoke-virtual {v0, v1}, Ljava/io/PrintStream;->println(Ljava/lang/String;)V return-void .end method