Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 77788eb4 authored by Alexandria Cornwall's avatar Alexandria Cornwall
Browse files

AAPT2: Add dominator tree analysis and resource removal

Added dominator tree analysis of resource configurations for each
resource entry to allow deduping of resource entries if:

1. The configuration for the resource entry's value is dominated by
a configuration with an equivalent entry value.

2. All compatible configurations for the entry (those not in conflict
and unrelated by domination with the configuration for the entry's
value) have an equivalent entry value.

Bug: 30051199
Test: make libaapt2_tests && libaapt2_tests
Change-Id: I66468d3014a2d6097a94b039ac1028f9f461c7d3
parent d67b4f53
Loading
Loading
Loading
Loading
+4 −0
Original line number Diff line number Diff line
@@ -40,6 +40,7 @@ sources := \
	link/ProductFilter.cpp \
	link/PrivateAttributeMover.cpp \
	link/ReferenceLinker.cpp \
	link/ResourceDeduper.cpp \
	link/TableMerger.cpp \
	link/VersionCollapser.cpp \
	link/XmlNamespaceRemover.cpp \
@@ -56,6 +57,7 @@ sources := \
	util/Util.cpp \
	ConfigDescription.cpp \
	Debug.cpp \
	DominatorTree.cpp \
	Flags.cpp \
	java/AnnotationProcessor.cpp \
	java/ClassDefinition.cpp \
@@ -93,6 +95,7 @@ testSources := \
	link/PrivateAttributeMover_test.cpp \
	link/ProductFilter_test.cpp \
	link/ReferenceLinker_test.cpp \
	link/ResourceDeduper_test.cpp \
	link/TableMerger_test.cpp \
	link/VersionCollapser_test.cpp \
	link/XmlNamespaceRemover_test.cpp \
@@ -106,6 +109,7 @@ testSources := \
	util/StringPiece_test.cpp \
	util/Util_test.cpp \
	ConfigDescription_test.cpp \
	DominatorTree_test.cpp \
	java/AnnotationProcessor_test.cpp \
	java/JavaClassGenerator_test.cpp \
	java/ManifestClassGenerator_test.cpp \
+92 −0
Original line number Diff line number Diff line
@@ -789,4 +789,96 @@ ConfigDescription ConfigDescription::copyWithoutSdkVersion() const {
    return copy;
}

bool ConfigDescription::dominates(const ConfigDescription& o) const {
    if (*this == defaultConfig() || *this == o) {
        return true;
    }
    return matchWithDensity(o)
            && !o.matchWithDensity(*this)
            && !isMoreSpecificThan(o)
            && !o.hasHigherPrecedenceThan(*this);
}

bool ConfigDescription::hasHigherPrecedenceThan(const ConfigDescription& o) const {
    // The order of the following tests defines the importance of one
    // configuration parameter over another. Those tests first are more
    // important, trumping any values in those following them.
    // The ordering should be the same as ResTable_config#isBetterThan.
    if (mcc || o.mcc) return (!o.mcc);
    if (mnc || o.mnc) return (!o.mnc);
    if (language[0] || o.language[0]) return (!o.language[0]);
    if (country[0] || o.country[0]) return (!o.country[0]);
    // Script and variant require either a language or country, both of which
    // have higher precedence.
    if ((screenLayout | o.screenLayout) & MASK_LAYOUTDIR) {
        return !(o.screenLayout & MASK_LAYOUTDIR);
    }
    if (smallestScreenWidthDp || o.smallestScreenWidthDp) return (!o.smallestScreenWidthDp);
    if (screenWidthDp || o.screenWidthDp) return (!o.screenWidthDp);
    if (screenHeightDp || o.screenHeightDp) return (!o.screenHeightDp);
    if ((screenLayout | o.screenLayout) & MASK_SCREENSIZE) {
        return !(o.screenLayout & MASK_SCREENSIZE);
    }
    if ((screenLayout | o.screenLayout) & MASK_SCREENLONG) {
        return !(o.screenLayout & MASK_SCREENLONG);
    }
    if ((screenLayout2 | o.screenLayout2) & MASK_SCREENROUND) {
        return !(o.screenLayout2 & MASK_SCREENROUND);
    }
    if (orientation || o.orientation) return (!o.orientation);
    if ((uiMode | o.uiMode) & MASK_UI_MODE_TYPE) {
        return !(o.uiMode & MASK_UI_MODE_TYPE);
    }
    if ((uiMode | o.uiMode) & MASK_UI_MODE_NIGHT) {
        return !(o.uiMode & MASK_UI_MODE_NIGHT);
    }
    if (density || o.density) return (!o.density);
    if (touchscreen || o.touchscreen) return (!o.touchscreen);
    if ((inputFlags | o.inputFlags) & MASK_KEYSHIDDEN) {
        return !(o.inputFlags & MASK_KEYSHIDDEN);
    }
    if ((inputFlags | o.inputFlags) & MASK_NAVHIDDEN) {
        return !(o.inputFlags & MASK_NAVHIDDEN);
    }
    if (keyboard || o.keyboard) return (!o.keyboard);
    if (navigation || o.navigation) return (!o.navigation);
    if (screenWidth || o.screenWidth) return (!o.screenWidth);
    if (screenHeight || o.screenHeight) return (!o.screenHeight);
    if (sdkVersion || o.sdkVersion) return (!o.sdkVersion);
    if (minorVersion || o.minorVersion) return (!o.minorVersion);
    // Both configurations have nothing defined except some possible future
    // value. Returning the comparison of the two configurations is a
    // "best effort" at this point to protect against incorrect dominations.
    return *this != o;
}

bool ConfigDescription::conflictsWith(const ConfigDescription& o) const {
    // This method should be updated as new configuration parameters are
    // introduced (e.g. screenConfig2).
    auto pred = [](const uint32_t a, const uint32_t b) -> bool {
        return a == 0 || b == 0 || a == b;
    };
    // The values here can be found in ResTable_config#match. Density and range
    // values can't lead to conflicts, and are ignored.
    return !pred(mcc, o.mcc)
            || !pred(mnc, o.mnc)
            || !pred(locale, o.locale)
            || !pred(screenLayout & MASK_LAYOUTDIR, o.screenLayout & MASK_LAYOUTDIR)
            || !pred(screenLayout & MASK_SCREENLONG, o.screenLayout & MASK_SCREENLONG)
            || !pred(screenLayout & MASK_UI_MODE_TYPE, o.screenLayout & MASK_UI_MODE_TYPE)
            || !pred(uiMode & MASK_UI_MODE_TYPE, o.uiMode & MASK_UI_MODE_TYPE)
            || !pred(uiMode & MASK_UI_MODE_NIGHT, o.uiMode & MASK_UI_MODE_NIGHT)
            || !pred(screenLayout2 & MASK_SCREENROUND, o.screenLayout2 & MASK_SCREENROUND)
            || !pred(orientation, o.orientation)
            || !pred(touchscreen, o.touchscreen)
            || !pred(inputFlags & MASK_KEYSHIDDEN, o.inputFlags & MASK_KEYSHIDDEN)
            || !pred(inputFlags & MASK_NAVHIDDEN, o.inputFlags & MASK_NAVHIDDEN)
            || !pred(keyboard, o.keyboard)
            || !pred(navigation, o.navigation);
}

bool ConfigDescription::isCompatibleWith(const ConfigDescription& o) const {
    return !conflictsWith(o) && !dominates(o) && !o.dominates(*this);
}

} // namespace aapt
+42 −2
Original line number Diff line number Diff line
@@ -59,14 +59,50 @@ struct ConfigDescription : public android::ResTable_config {
    ConfigDescription& operator=(const ConfigDescription& o);
    ConfigDescription& operator=(ConfigDescription&& o);

    ConfigDescription copyWithoutSdkVersion() const;

    /**
     * A configuration X dominates another configuration Y, if X has at least the
     * precedence of Y and X is strictly more general than Y: for any type defined
     * by X, the same type is defined by Y with a value equal to or, in the case
     * of ranges, more specific than that of X.
     *
     * For example, the configuration 'en-w800dp' dominates 'en-rGB-w1024dp'. It
     * does not dominate 'fr', 'en-w720dp', or 'mcc001-en-w800dp'.
     */
    bool dominates(const ConfigDescription& o) const;

    /**
     * Returns true if this configuration defines a more important configuration
     * parameter than o. For example, "en" has higher precedence than "v23",
     * whereas "en" has the same precedence as "en-v23".
     */
    bool hasHigherPrecedenceThan(const ConfigDescription& o) const;

    /**
     * A configuration conflicts with another configuration if both
     * configurations define an incompatible configuration parameter. An
     * incompatible configuration parameter is a non-range, non-density parameter
     * that is defined in both configurations as a different, non-default value.
     */
    bool conflictsWith(const ConfigDescription& o) const;

    /**
     * A configuration is compatible with another configuration if both
     * configurations can match a common concrete device configuration and are
     * unrelated by domination. For example, land-v11 conflicts with port-v21
     * but is compatible with v21 (both land-v11 and v21 would match en-land-v23).
     */
    bool isCompatibleWith(const ConfigDescription& o) const;

    bool matchWithDensity(const ConfigDescription& o) const;

    bool operator<(const ConfigDescription& o) const;
    bool operator<=(const ConfigDescription& o) const;
    bool operator==(const ConfigDescription& o) const;
    bool operator!=(const ConfigDescription& o) const;
    bool operator>=(const ConfigDescription& o) const;
    bool operator>(const ConfigDescription& o) const;

    ConfigDescription copyWithoutSdkVersion() const;
};

inline ConfigDescription::ConfigDescription() {
@@ -103,6 +139,10 @@ inline ConfigDescription& ConfigDescription::operator=(ConfigDescription&& o) {
    return *this;
}

inline bool ConfigDescription::matchWithDensity(const ConfigDescription& o) const {
    return match(o) && (density == 0 || density == o.density);
}

inline bool ConfigDescription::operator<(const ConfigDescription& o) const {
    return compare(o) < 0;
}
+89 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ConfigDescription.h"
#include "DominatorTree.h"

#include <algorithm>

namespace aapt {

DominatorTree::DominatorTree(
        const std::vector<std::unique_ptr<ResourceConfigValue>>& configs) {
    for (const auto& config : configs) {
        mProductRoots[config->product].tryAddChild(
                util::make_unique<Node>(config.get(), nullptr));
    }
}

void DominatorTree::accept(Visitor* visitor) {
    for (auto& entry : mProductRoots) {
        visitor->visitTree(entry.first, &entry.second);
    }
}

bool DominatorTree::Node::tryAddChild(std::unique_ptr<Node> newChild) {
    assert(newChild->mValue && "cannot add a root or empty node as a child");
    if (mValue && !dominates(newChild.get())) {
        // This is not the root and the child dominates us.
        return false;
    }
    return addChild(std::move(newChild));
}

bool DominatorTree::Node::addChild(std::unique_ptr<Node> newChild) {
    bool hasDominatedChildren = false;
    // Demote children dominated by the new config.
    for (auto& child : mChildren) {
        if (newChild->dominates(child.get())) {
            child->mParent = newChild.get();
            newChild->mChildren.push_back(std::move(child));
            child = {};
            hasDominatedChildren = true;
        }
    }
    // Remove dominated children.
    if (hasDominatedChildren) {
        mChildren.erase(std::remove_if(mChildren.begin(), mChildren.end(),
                [](const std::unique_ptr<Node>& child) -> bool {
            return child == nullptr;
        }), mChildren.end());
    }
    // Add the new config to a child if a child dominates the new config.
    for (auto& child : mChildren) {
        if (child->dominates(newChild.get())) {
            child->addChild(std::move(newChild));
            return true;
        }
    }
    // The new config is not dominated by a child, so add it here.
    newChild->mParent = this;
    mChildren.push_back(std::move(newChild));
    return true;
}

bool DominatorTree::Node::dominates(const Node* other) const {
    // Check root node dominations.
    if (other->isRootNode()) {
        return isRootNode();
    } else if (isRootNode()) {
        return true;
    }
    // Neither node is a root node; compare the configurations.
    return mValue->config.dominates(other->mValue->config);
}

} // namespace aapt
+127 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef AAPT_DOMINATOR_TREE_H
#define AAPT_DOMINATOR_TREE_H

#include "ResourceTable.h"

#include <map>
#include <memory>
#include <string>
#include <vector>

namespace aapt {

/**
 * A dominator tree of configurations as defined by resolution rules for Android
 * resources.
 *
 * A node in the tree represents a resource configuration.
 *
 * The tree has the following property:
 *
 * Each child of a given configuration defines a strict superset of qualifiers
 * and has a value that is at least as specific as that of its ancestors. A
 * value is "at least as specific" if it is either identical or it represents a
 * stronger requirement.
 * For example, v21 is more specific than v11, and w1200dp is more specific than
 * w800dp.
 *
 * The dominator tree relies on the underlying configurations passed to it. If
 * the configurations passed to the dominator tree go out of scope, the tree
 * will exhibit undefined behavior.
 */
class DominatorTree {
public:
    explicit DominatorTree(const std::vector<std::unique_ptr<ResourceConfigValue>>& configs);

    class Node {
    public:
        explicit Node(ResourceConfigValue* value = nullptr, Node* parent = nullptr) :
                mValue(value), mParent(parent) {
        }

        inline ResourceConfigValue* value() const {
            return mValue;
        }

        inline Node* parent() const {
            return mParent;
        }

        inline bool isRootNode() const {
            return !mValue;
        }

        inline const std::vector<std::unique_ptr<Node>>& children() const {
            return mChildren;
        }

        bool tryAddChild(std::unique_ptr<Node> newChild);

    private:
        bool addChild(std::unique_ptr<Node> newChild);
        bool dominates(const Node* other) const;

        ResourceConfigValue* mValue;
        Node* mParent;
        std::vector<std::unique_ptr<Node>> mChildren;

        DISALLOW_COPY_AND_ASSIGN(Node);
    };

    struct Visitor {
        virtual ~Visitor() = default;
        virtual void visitTree(const std::string& product, Node* root) = 0;
    };

    class BottomUpVisitor : public Visitor {
    public:
        virtual ~BottomUpVisitor() = default;

        void visitTree(const std::string& product, Node* root) override {
            for (auto& child : root->children()) {
                visitNode(child.get());
            }
        }

        virtual void visitConfig(Node* node) = 0;

    private:
        void visitNode(Node* node) {
            for (auto& child : node->children()) {
                visitNode(child.get());
            }
            visitConfig(node);
        }
    };

    void accept(Visitor* visitor);

    inline const std::map<std::string, Node>& getProductRoots() const {
        return mProductRoots;
    }

private:
    DISALLOW_COPY_AND_ASSIGN(DominatorTree);

    std::map<std::string, Node> mProductRoots;
};

} // namespace aapt

#endif // AAPT_DOMINATOR_TREE_H
Loading