brut.androlib.AndrolibException Java Examples

The following examples show how to use brut.androlib.AndrolibException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AndrolibResources.java    From ratel with Apache License 2.0 6 votes vote down vote up
public boolean detectWhetherAppIsFramework(File appDir)
        throws AndrolibException {
    File publicXml = new File(appDir, "res/values/public.xml");
    if (! publicXml.exists()) {
        return false;
    }

    Iterator<String> it;
    try {
        it = IOUtils.lineIterator(new FileReader(new File(appDir,
                "res/values/public.xml")));
    } catch (FileNotFoundException ex) {
        throw new AndrolibException(
                "Could not detect whether app is framework one", ex);
    }
    it.next();
    it.next();
    return it.next().contains("0x01");
}
 
Example #2
Source File: ResTable.java    From ratel with Apache License 2.0 6 votes vote down vote up
public void addPackage(ResPackage pkg, boolean main) throws AndrolibException {
    Integer id = pkg.getId();
    if (mPackagesById.containsKey(id)) {
        throw new AndrolibException("Multiple packages: id=" + id.toString());
    }
    String name = pkg.getName();
    if (mPackagesByName.containsKey(name)) {
        throw new AndrolibException("Multiple packages: name=" + name);
    }

    mPackagesById.put(id, pkg);
    mPackagesByName.put(name, pkg);
    if (main) {
        mMainPackages.add(pkg);
    } else {
        mFramePackages.add(pkg);
    }
}
 
Example #3
Source File: SmaliBuilder.java    From ratel with Apache License 2.0 6 votes vote down vote up
private void buildFile(String fileName, DexBuilder dexBuilder)
        throws AndrolibException, IOException {
    File inFile = new File(mSmaliDir, fileName);
    InputStream inStream = new FileInputStream(inFile);

    if (fileName.endsWith(".smali")) {
        try {
            if (!SmaliMod.assembleSmaliFile(inFile, dexBuilder, 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();
}
 
Example #4
Source File: ResValueFactory.java    From ratel with Apache License 2.0 6 votes vote down vote up
public ResBagValue bagFactory(int parent, Duo<Integer, ResScalarValue>[] items) 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);
    }
    // Android O Preview added an unknown enum for ResTable_map. This is hardcoded as 0 for now.
    if (key == ResArrayValue.BAG_KEY_ARRAY_START || key == 0) {
        return new ResArrayValue(parentVal, items);
    }
    if (key >= ResPluralsValue.BAG_KEY_PLURALS_START && key <= ResPluralsValue.BAG_KEY_PLURALS_END) {
        return new ResPluralsValue(parentVal, items);
    }
    return new ResStyleValue(parentVal, items, this);
}
 
Example #5
Source File: AndrolibResources.java    From ratel with Apache License 2.0 6 votes vote down vote up
public void emptyFrameworkDirectory() throws AndrolibException {
    File dir = getFrameworkDir();
    File apk;

    apk = new File(dir, "1.apk");

    if (! apk.exists()) {
        LOGGER.warning("Can't empty framework directory, no file found at: " + apk.getAbsolutePath());
    } else {
        try {
            if (apk.exists() && dir.listFiles().length > 1 && ! apkOptions.forceDeleteFramework) {
                LOGGER.warning("More than default framework detected. Please run command with `--force` parameter to wipe framework directory.");
            } else {
                for (File file : dir.listFiles()) {
                    if (file.isFile() && file.getName().endsWith(".apk")) {
                        LOGGER.info("Removing " + file.getName() + " framework file...");
                        file.delete();
                    }
                }
            }
        } catch (NullPointerException e) {
            throw new AndrolibException(e);
        }
    }
}
 
Example #6
Source File: AXmlResourceParser.java    From ratel with Apache License 2.0 6 votes vote down vote up
@Override
public String getAttributeName(int index) {
    int offset = getAttributeOffset(index);
    int name = m_attributes[offset + ATTRIBUTE_IX_NAME];
    if (name == -1) {
        return "";
    }

    String value = m_strings.getString(name);

    // some attributes will return "", we must rely on the resource_id and refer to the frameworks
    // to match the resource id to the name. ex: 0x101021C = versionName
    if (value.length() != 0) {
        return value;
    } else {
        try {
            value = mAttrDecoder.decodeManifestAttr(getAttributeNameResource(index));
        } catch (AndrolibException e) {
            value = "";
        }
        return value;
    }
}
 
Example #7
Source File: ResEnumAttr.java    From ratel with Apache License 2.0 6 votes vote down vote up
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) {
            value2 = ref.getReferent().getName();
            mItemsCache.put(value, value2);
        }
    }
    return value2;
}
 
Example #8
Source File: ResAttr.java    From ratel with Apache License 2.0 6 votes vote down vote up
@Override
public void serializeToResValuesXml(XmlSerializer serializer,
                                    ResResource res) throws IOException, AndrolibException {
    String type = getTypeAsString();

    serializer.startTag(null, "attr");
    serializer.attribute(null, "name", res.getResSpec().getName());
    if (type != null) {
        serializer.attribute(null, "format", type);
    }
    if (mMin != null) {
        serializer.attribute(null, "min", mMin.toString());
    }
    if (mMax != null) {
        serializer.attribute(null, "max", mMax.toString());
    }
    if (mL10n != null && mL10n) {
        serializer.attribute(null, "localization", "suggested");
    }
    serializeBody(serializer, res);
    serializer.endTag(null, "attr");
}
 
Example #9
Source File: ResBagValue.java    From ratel with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #10
Source File: ResArrayValue.java    From ratel with Apache License 2.0 6 votes vote down vote up
public String getType() throws AndrolibException {
    if (mItems.length == 0) {
        return null;
    }
    String type = mItems[0].getType();
    for (int i = 0; i < mItems.length; i++) {
        if (mItems[i].encodeAsResXmlItemValue().startsWith("@string")) {
            return "string";
        } else if (mItems[i].encodeAsResXmlItemValue().startsWith("@drawable")) {
            return null;
        } else if (mItems[i].encodeAsResXmlItemValue().startsWith("@integer")) {
            return "integer";
        } else if (!"string".equals(type) && !"integer".equals(type)) {
            return null;
        } else if (!type.equals(mItems[i].getType())) {
            return null;
        }
    }
    if (!Arrays.asList(AllowedArrayTypes).contains(type)) {
        return "string";
    }
    return type;
}
 
Example #11
Source File: ResPluralsValue.java    From ratel with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #12
Source File: AndrolibResources.java    From ratel with Apache License 2.0 6 votes vote down vote up
public void aaptPackage(File apkFile, File manifest, File resDir, File rawDir, File assetDir, File[] include)
        throws AndrolibException {

    String aaptPath = apkOptions.aaptPath;
    boolean customAapt = !aaptPath.isEmpty();
    List<String> cmd = new ArrayList<String>();

    try {
        String aaptCommand = AaptManager.getAaptExecutionCommand(aaptPath, getAaptBinaryFile());
        cmd.add(aaptCommand);
    } catch (BrutException ex) {
        LOGGER.warning("aapt: " + ex.getMessage() + " (defaulting to $PATH binary)");
        cmd.add(AaptManager.getAaptBinaryName(getAaptVersion()));
    }

    if (apkOptions.isAapt2()) {
        aapt2Package(apkFile, manifest, resDir, rawDir, assetDir, include, cmd);
        return;
    }
    aapt1Package(apkFile, manifest, resDir, rawDir, assetDir, include, cmd, customAapt);
}
 
Example #13
Source File: AndrolibResources.java    From ratel with Apache License 2.0 6 votes vote down vote up
public void decodeManifest(ResTable resTable, ExtFile apkFile, File outDir)
        throws AndrolibException {

    Duo<ResFileDecoder, AXmlResourceParser> duo = getManifestFileDecoder();
    ResFileDecoder fileDecoder = duo.m1;

    // Set ResAttrDecoder
    duo.m2.setAttrDecoder(new ResAttrDecoder());
    ResAttrDecoder attrDecoder = duo.m2.getAttrDecoder();

    // Fake ResPackage
    attrDecoder.setCurrentPackage(new ResPackage(resTable, 0, null));

    Directory inApk, out;
    try {
        inApk = apkFile.getDirectory();
        out = new FileDirectory(outDir);

        LOGGER.info("Decoding AndroidManifest.xml with only framework resources...");
        fileDecoder.decodeManifest(inApk, "AndroidManifest.xml", out, "AndroidManifest.xml");

    } catch (DirectoryException ex) {
        throw new AndrolibException(ex);
    }
}
 
Example #14
Source File: AndrolibResources.java    From ratel with Apache License 2.0 6 votes vote down vote up
public ResPackage loadFrameworkPkg(ResTable resTable, int id, String frameTag)
        throws AndrolibException {
    File apk = getFrameworkApk(id, frameTag);

    LOGGER.info("Loading resource table from file: " + apk);
    mFramework = new ExtFile(apk);
    ResPackage[] pkgs = getResPackagesFromApk(mFramework, resTable, true);

    ResPackage pkg;
    if (pkgs.length > 1) {
        pkg = selectPkgWithMostResSpecs(pkgs);
    } else if (pkgs.length == 0) {
        throw new AndrolibException("Arsc files with zero or multiple packages");
    } else {
        pkg = pkgs[0];
    }

    if (pkg.getId() != id) {
        throw new AndrolibException("Expected pkg of id: " + String.valueOf(id) + ", got: " + pkg.getId());
    }

    resTable.addPackage(pkg, false);
    return pkg;
}
 
Example #15
Source File: ResXmlPatcher.java    From ratel with Apache License 2.0 6 votes vote down vote up
/**
 * Removes attributes like "versionCode" and "versionName" from file.
 *
 * @param file File representing AndroidManifest.xml
 * @throws AndrolibException
 */
public static void removeManifestVersions(File file) throws AndrolibException {
    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) {
        }
    }
}
 
Example #16
Source File: AndrolibResources.java    From ratel with Apache License 2.0 6 votes vote down vote up
private ResPackage[] getResPackagesFromApk(ExtFile apkFile,ResTable resTable, boolean keepBroken)
        throws AndrolibException {
    try {
        Directory dir = apkFile.getDirectory();
        BufferedInputStream bfi = new BufferedInputStream(dir.getFileInput("resources.arsc"));
        try {
            return ARSCDecoder.decode(bfi, false, keepBroken, resTable).getPackages();
        } finally {
            try {
                bfi.close();
            } catch (IOException ignored) {}
        }
    } catch (DirectoryException ex) {
        throw new AndrolibException("Could not load resources.arsc from file: " + apkFile, ex);
    }
}
 
Example #17
Source File: AXmlResourceParser.java    From ratel with Apache License 2.0 6 votes vote down vote up
@Override
public String getAttributeValue(int index) {
    int offset = getAttributeOffset(index);
    int valueType = m_attributes[offset + ATTRIBUTE_IX_VALUE_TYPE];
    int valueData = m_attributes[offset + ATTRIBUTE_IX_VALUE_DATA];
    int valueRaw = m_attributes[offset + ATTRIBUTE_IX_VALUE_STRING];

    if (mAttrDecoder != null) {
        try {
            return mAttrDecoder.decode(
                    valueType,
                    valueData,
                    valueRaw == -1 ? null : ResXmlEncoders.escapeXmlChars(m_strings.getString(valueRaw)),
                    getAttributeNameResource(index));
        } 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);
}
 
Example #18
Source File: ResReferenceValue.java    From ratel with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #19
Source File: ResResSpec.java    From ratel with Apache License 2.0 5 votes vote down vote up
public ResResource getResource(ResConfigFlags config) throws AndrolibException {
    ResResource res = mResources.get(config);
    if (res == null) {
        throw new UndefinedResObject(String.format("resource: spec=%s, config=%s", this, config));
    }
    return res;
}
 
Example #20
Source File: ResTable.java    From ratel with Apache License 2.0 5 votes vote down vote up
public ResPackage getPackage(String name) throws AndrolibException {
    ResPackage pkg = mPackagesByName.get(name);
    if (pkg == null) {
        throw new UndefinedResObject("package: name=" + name);
    }
    return pkg;
}
 
Example #21
Source File: ResFileValue.java    From ratel with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #22
Source File: ARSCDecoder.java    From ratel with Apache License 2.0 5 votes vote down vote up
public ResPackage getOnePackage() throws AndrolibException {
    if (mPackages.length <= 0) {
        throw new AndrolibException("Arsc file contains zero packages");
    } else if (mPackages.length != 1) {
        int id = findPackageWithMostResSpecs();
        LOGGER.info("Arsc file contains multiple packages. Using package "
                + mPackages[id].getName() + " as default.");

        return mPackages[id];
    }
    return mPackages[0];
}
 
Example #23
Source File: ResTable.java    From ratel with Apache License 2.0 5 votes vote down vote up
public ResPackage getCurrentResPackage() throws AndrolibException {
    ResPackage pkg = mPackagesById.get(mPackageId);

    if (pkg != null) {
        return pkg;
    } else {
        if (mMainPackages.size() == 1) {
            return mMainPackages.iterator().next();
        }
        return getHighestSpecPackage();
    }
}
 
Example #24
Source File: ResReferenceValue.java    From ratel with Apache License 2.0 5 votes vote down vote up
public ResResSpec getReferent() throws AndrolibException {
    try {
        return mPackage.getResTable().getResSpec(getValue());
    } catch (UndefinedResObject ex) {
        return null;
    }
}
 
Example #25
Source File: ARSCDecoder.java    From ratel with Apache License 2.0 5 votes vote down vote up
private ResIntBasedValue readValue() throws IOException, AndrolibException {
/* size */mIn.skipCheckShort((short) 8);
/* zero */mIn.skipCheckByte((byte) 0);
      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);
  }
 
Example #26
Source File: ResPackage.java    From ratel with Apache License 2.0 5 votes vote down vote up
public ResType getConfig(ResConfigFlags flags) throws AndrolibException {
    ResType config = mConfigs.get(flags);
    if (config == null) {
        throw new UndefinedResObject("config: " + flags);
    }
    return config;
}
 
Example #27
Source File: ResScalarValue.java    From ratel with Apache License 2.0 5 votes vote down vote up
@Override
public String encodeAsResXmlAttr() throws AndrolibException {
    if (mRawValue != null) {
        return mRawValue;
    }
    return encodeAsResXml();
}
 
Example #28
Source File: ResScalarValue.java    From ratel with Apache License 2.0 5 votes vote down vote up
@Override
public String encodeAsResXmlValue() throws AndrolibException {
    if (mRawValue != null) {
        return mRawValue;
    }
    return encodeAsResXml();
}
 
Example #29
Source File: AndrolibResources.java    From ratel with Apache License 2.0 5 votes vote down vote up
public void decodeManifestWithResources(ResTable resTable, ExtFile apkFile, File outDir)
        throws AndrolibException {

    Duo<ResFileDecoder, AXmlResourceParser> duo = getResFileDecoder();
    ResFileDecoder fileDecoder = duo.m1;
    ResAttrDecoder attrDecoder = duo.m2.getAttrDecoder();

    attrDecoder.setCurrentPackage(resTable.listMainPackages().iterator().next());

    Directory inApk, in = null, out;
    try {
        inApk = apkFile.getDirectory();
        out = new FileDirectory(outDir);
        LOGGER.info("Decoding AndroidManifest.xml with resources...");

        fileDecoder.decodeManifest(inApk, "AndroidManifest.xml", out, "AndroidManifest.xml");

        // Remove versionName / versionCode (aapt API 16)
        if (!resTable.getAnalysisMode()) {

            // check for a mismatch between resources.arsc package and the package listed in AndroidManifest
            // also remove the android::versionCode / versionName from manifest for rebuild
            // this is a required change to prevent aapt warning about conflicting versions
            // it will be passed as a parameter to aapt like "--min-sdk-version" via apktool.yml
            adjustPackageManifest(resTable, outDir.getAbsolutePath() + File.separator + "AndroidManifest.xml");

            ResXmlPatcher.removeManifestVersions(new File(
                    outDir.getAbsolutePath() + File.separator + "AndroidManifest.xml"));

            mPackageId = String.valueOf(resTable.getPackageId());
        }
    } catch (DirectoryException ex) {
        throw new AndrolibException(ex);
    }
}
 
Example #30
Source File: SmaliDecoder.java    From ratel with Apache License 2.0 5 votes vote down vote up
private void 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 dex
        DexBackedDexFile dexFile = DexFileFactory.loadDexEntry(mApkFile, mDexFile, true, Opcodes.forApi(mApi));

        if (dexFile.isOdexFile()) {
            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);
    } catch (IOException ex) {
        throw new AndrolibException(ex);
    }
}