001/*
002 * Copyright (C) 2015-2021 KeepSafe Software
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package com.getkeepsafe.dexcount.treegen.workers;
017
018import com.getkeepsafe.dexcount.PackageTree;
019import com.getkeepsafe.dexcount.source.SourceFile;
020import com.getkeepsafe.dexcount.source.SourceFiles;
021import org.apache.commons.io.IOUtils;
022import org.gradle.api.file.RegularFileProperty;
023import org.slf4j.Logger;
024import org.slf4j.LoggerFactory;
025
026import java.io.File;
027import java.io.IOException;
028import java.util.List;
029
030public abstract class ApkishWorker extends ModernWorker<ApkishWorker.Params> {
031    private static final Logger LOGGER = LoggerFactory.getLogger(ApkishWorker.class);
032
033    public interface Params extends ModernWorker.Params {
034        RegularFileProperty getApkishFile();
035    }
036
037    @Override
038    protected PackageTree generatePackageTree() throws IOException {
039        PackageTree tree = new PackageTree(getDeobfuscator());
040
041        File inputFile = getInputFile();
042
043        List<SourceFile> sourceFiles = SourceFiles.extractDexData(inputFile);
044        try {
045            sourceFiles.forEach(sf -> {
046                sf.getMethodRefs().forEach(tree::addMethodRef);
047                sf.getFieldRefs().forEach(tree::addFieldRef);
048            });
049        } finally {
050            IOUtils.closeQuietly(sourceFiles.toArray(new SourceFile[0]));
051        }
052
053        return tree;
054    }
055
056    private File getInputFile() {
057        return getParameters().getApkishFile().getAsFile().get();
058    }
059
060    @Override
061    protected String getInputRepresentation() {
062        return getInputFile().getName();
063    }
064
065    @Override
066    protected Logger getLogger() {
067        return LOGGER;
068    }
069}