summaryrefslogtreecommitdiff
path: root/sdklib/src/main/java/com/android/sdklib/repository/local/LocalPlatformPkgInfo.java
blob: 534677efb835554157bcfe30aa2fe28df63ce38b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/*
 * Copyright (C) 2013 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.
 */

package com.android.sdklib.repository.local;

import com.android.SdkConstants;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.annotations.VisibleForTesting;
import com.android.sdklib.AndroidVersion;
import com.android.sdklib.IAndroidTarget;
import com.android.sdklib.IAndroidTarget.OptionalLibrary;
import com.android.sdklib.ISystemImage;
import com.android.sdklib.ISystemImage.LocationType;
import com.android.sdklib.SdkManager.LayoutlibVersion;
import com.android.sdklib.SystemImage;
import com.android.sdklib.internal.androidTarget.OptionalLibraryImpl;
import com.android.sdklib.internal.androidTarget.PlatformTarget;
import com.android.sdklib.internal.project.ProjectProperties;
import com.android.sdklib.io.FileOp;
import com.android.sdklib.io.IFileOp;
import com.android.sdklib.repository.FullRevision;
import com.android.sdklib.repository.MajorRevision;
import com.android.sdklib.repository.PkgProps;
import com.android.sdklib.repository.descriptors.IPkgDesc;
import com.android.sdklib.repository.descriptors.IdDisplay;
import com.android.sdklib.repository.descriptors.PkgDesc;
import com.android.sdklib.repository.descriptors.PkgType;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.TreeMultimap;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;

@SuppressWarnings("ConstantConditions")
public class LocalPlatformPkgInfo extends LocalPkgInfo {

    public static final String PROP_VERSION_SDK      = "ro.build.version.sdk";      //$NON-NLS-1$
    public static final String PROP_VERSION_CODENAME = "ro.build.version.codename"; //$NON-NLS-1$
    public static final String PROP_VERSION_RELEASE  = "ro.build.version.release";  //$NON-NLS-1$

    @NonNull
    private final IPkgDesc mDesc;

    /** Android target, lazyly loaded from #getAndroidTarget */
    private IAndroidTarget mTarget;
    private boolean mLoaded;

    public LocalPlatformPkgInfo(@NonNull LocalSdk localSdk,
                                @NonNull File localDir,
                                @NonNull Properties sourceProps,
                                @NonNull AndroidVersion version,
                                @NonNull MajorRevision revision,
                                @NonNull FullRevision minToolsRev) {
        super(localSdk, localDir, sourceProps);
        mDesc = PkgDesc.Builder.newPlatform(version, revision, minToolsRev).create();
    }

    @NonNull
    @Override
    public IPkgDesc getDesc() {
        return mDesc;
    }

    /** The "path" of a Platform is its Target Hash. */
    @NonNull
    public String getTargetHash() {
        return getDesc().getPath();
    }

    @Nullable
    public IAndroidTarget getAndroidTarget() {
        if (!mLoaded) {
            mTarget = createAndroidTarget();
            mLoaded = true;
        }
        return mTarget;
    }

    public boolean isLoaded() {
        return mLoaded;
    }

    //-----

    /**
     * Creates the PlatformTarget. Invoked by {@link #getAndroidTarget()}.
     */
    @SuppressWarnings("ConstantConditions")
    @Nullable
    protected IAndroidTarget createAndroidTarget() {
        LocalSdk sdk = getLocalSdk();
        IFileOp fileOp = sdk.getFileOp();
        File platformFolder = getLocalDir();
        File buildProp = new File(platformFolder, SdkConstants.FN_BUILD_PROP);
        File sourcePropFile = new File(platformFolder, SdkConstants.FN_SOURCE_PROP);

        if (!fileOp.isFile(buildProp) || !fileOp.isFile(sourcePropFile)) {
            appendLoadError("Ignoring platform '%1$s': %2$s is missing.",   //$NON-NLS-1$
                    platformFolder.getName(),
                    SdkConstants.FN_BUILD_PROP);
            return null;
        }

        Map<String, String> platformProp = new HashMap<String, String>();

        // add all the property files
        Map<String, String> map = null;

        try {
            map = ProjectProperties.parsePropertyStream(
                    fileOp.newFileInputStream(buildProp),
                    buildProp.getPath(),
                    null /*log*/);
            if (map != null) {
                platformProp.putAll(map);
            }
        } catch (FileNotFoundException ignore) {}

        try {
            map = ProjectProperties.parsePropertyStream(
                    fileOp.newFileInputStream(sourcePropFile),
                    sourcePropFile.getPath(),
                    null /*log*/);
            if (map != null) {
                platformProp.putAll(map);
            }
        } catch (FileNotFoundException ignore) {}

        File sdkPropFile = new File(platformFolder, SdkConstants.FN_SDK_PROP);
        if (fileOp.isFile(sdkPropFile)) { // obsolete platforms don't have this.
            try {
                map = ProjectProperties.parsePropertyStream(
                        fileOp.newFileInputStream(sdkPropFile),
                        sdkPropFile.getPath(),
                        null /*log*/);
                if (map != null) {
                    platformProp.putAll(map);
                }
            } catch (FileNotFoundException ignore) {}
        }

        // look for some specific values in the map.

        // api level
        int apiNumber;
        String stringValue = platformProp.get(PROP_VERSION_SDK);
        if (stringValue == null) {
            appendLoadError("Ignoring platform '%1$s': %2$s is missing from '%3$s'",
                    platformFolder.getName(), PROP_VERSION_SDK,
                    SdkConstants.FN_BUILD_PROP);
            return null;
        } else {
            try {
                 apiNumber = Integer.parseInt(stringValue);
            } catch (NumberFormatException e) {
                // looks like apiNumber does not parse to a number.
                // Ignore this platform.
                appendLoadError(
                        "Ignoring platform '%1$s': %2$s is not a valid number in %3$s.",
                        platformFolder.getName(), PROP_VERSION_SDK,
                        SdkConstants.FN_BUILD_PROP);
                return null;
            }
        }

        // Codename must be either null or a platform codename.
        // REL means it's a release version and therefore the codename should be null.
        AndroidVersion apiVersion =
            new AndroidVersion(apiNumber, platformProp.get(PROP_VERSION_CODENAME));

        // version string
        String apiName = platformProp.get(PkgProps.PLATFORM_VERSION);
        if (apiName == null) {
            apiName = platformProp.get(PROP_VERSION_RELEASE);
        }
        if (apiName == null) {
            appendLoadError(
                    "Ignoring platform '%1$s': %2$s is missing from '%3$s'",
                    platformFolder.getName(), PROP_VERSION_RELEASE,
                    SdkConstants.FN_BUILD_PROP);
            return null;
        }

        // platform rev number & layoutlib version are extracted from the source.properties
        // saved by the SDK Manager when installing the package.

        int revision = 1;
        LayoutlibVersion layoutlibVersion = null;
        try {
            revision = Integer.parseInt(platformProp.get(PkgProps.PKG_REVISION));
        } catch (NumberFormatException e) {
            // do nothing, we'll keep the default value of 1.
        }

        try {
            String propApi = platformProp.get(PkgProps.LAYOUTLIB_API);
            String propRev = platformProp.get(PkgProps.LAYOUTLIB_REV);
            int llApi = propApi == null ? LayoutlibVersion.NOT_SPECIFIED :
                                          Integer.parseInt(propApi);
            int llRev = propRev == null ? LayoutlibVersion.NOT_SPECIFIED :
                                          Integer.parseInt(propRev);
            if (llApi > LayoutlibVersion.NOT_SPECIFIED &&
                    llRev >= LayoutlibVersion.NOT_SPECIFIED) {
                layoutlibVersion = new LayoutlibVersion(llApi, llRev);
            }
        } catch (NumberFormatException e) {
            // do nothing, we'll ignore the layoutlib version if it's invalid
        }

        // api number and name look valid, perform a few more checks
        String err = checkPlatformContent(fileOp, platformFolder);
        if (err != null) {
            appendLoadError("%s", err); //$NLN-NLS-1$
            return null;
        }

        ISystemImage[] systemImages = getPlatformSystemImages(fileOp, platformFolder, apiVersion);

        // create the target.
        PlatformTarget pt = new PlatformTarget(
                sdk.getLocation().getPath(),
                platformFolder.getAbsolutePath(),
                apiVersion,
                apiName,
                revision,
                layoutlibVersion,
                systemImages,
                platformProp,
                getOptionalLibraries(platformFolder),
                sdk.getLatestBuildTool());

        // add the skins from the platform. Make a copy to not modify the original collection.
        List<File> skins = new ArrayList<File>(PackageParserUtils.parseSkinFolder(pt.getFile(IAndroidTarget.SKINS), fileOp));

        // add the system-image specific skins, if any.
        for (ISystemImage systemImage : systemImages) {
            skins.addAll(Arrays.asList(systemImage.getSkins()));
        }

        pt.setSkins(skins.toArray(new File[skins.size()]));

        // add path to the non-legacy samples package if it exists
        LocalPkgInfo samples = sdk.getPkgInfo(PkgType.PKG_SAMPLE, getDesc().getAndroidVersion());
        if (samples != null) {
            pt.setSamplesPath(samples.getLocalDir().getAbsolutePath());
        }

        // add path to the non-legacy sources package if it exists
        LocalPkgInfo sources = sdk.getPkgInfo(PkgType.PKG_SOURCE, getDesc().getAndroidVersion());
        if (sources != null) {
            pt.setSourcesPath(sources.getLocalDir().getAbsolutePath());
        }

        return pt;
    }

    /**
     * Get all the system images supported by a platform target.
     * For a platform, we first look in the new sdk/system-images folders then we
     * look for sub-folders in the platform/images directory and/or the one legacy
     * folder.
     * If any given API appears twice or more, the first occurrence wins.
     *
     * @param fileOp File operation wrapper.
     * @param platformDir Root of the platform target being loaded.
     * @param apiVersion API level + codename of platform being loaded.
     * @return an array of ISystemImage containing all the system images for the target.
     *              The list can be empty but not null.
     */
    @NonNull
    private ISystemImage[] getPlatformSystemImages(IFileOp fileOp,
                                                   File platformDir,
                                                   AndroidVersion apiVersion) {
        Set<ISystemImage> found = new TreeSet<ISystemImage>();
        SetMultimap<IdDisplay, String> tagToAbiFound = TreeMultimap.create();


        // Look in the SDK/system-image/platform-n/tag/abi folders.
        // Look in the SDK/system-image/platform-n/abi folders.
        // If we find multiple occurrences of the same platform/abi, the first one read wins.

        LocalPkgInfo[] sysImgInfos = getLocalSdk().getPkgsInfos(PkgType.PKG_SYS_IMAGE);
        for (LocalPkgInfo pkg : sysImgInfos) {
            IPkgDesc d = pkg.getDesc();
            if (pkg instanceof LocalSysImgPkgInfo &&
                    !d.hasVendor() &&
                    apiVersion.equals(d.getAndroidVersion())) {
                IdDisplay tag = d.getTag();
                String abi = d.getPath();
                if (tag != null && abi != null && !tagToAbiFound.containsEntry(tag, abi)) {
                    found.add(((LocalSysImgPkgInfo)pkg).getSystemImage());
                    tagToAbiFound.put(tag, abi);
                }
            }
        }

        // Look in either the platform/images/abi or the legacy folder
        File imgDir = new File(platformDir, SdkConstants.OS_IMAGES_FOLDER);
        File[] files =  fileOp.listFiles(imgDir);
        boolean useLegacy = true;
        boolean hasImgFiles = false;
        final IdDisplay defaultTag = SystemImage.DEFAULT_TAG;

        // Look for sub-directories
        for (File file : files) {
            if (fileOp.isDirectory(file)) {
                useLegacy = false;
                String abi = file.getName();
                if (!tagToAbiFound.containsEntry(defaultTag, abi)) {
                    found.add(new SystemImage(
                            file,
                            LocationType.IN_IMAGES_SUBFOLDER,
                            defaultTag,
                            abi,
                            FileOp.EMPTY_FILE_ARRAY));
                    tagToAbiFound.put(defaultTag, abi);
                }
            } else if (!hasImgFiles && fileOp.isFile(file)) {
                if (file.getName().endsWith(".img")) {      //$NON-NLS-1$
                    hasImgFiles = true;
                }
            }
        }

        if (useLegacy &&
                hasImgFiles &&
                fileOp.isDirectory(imgDir) &&
                !tagToAbiFound.containsEntry(defaultTag, SdkConstants.ABI_ARMEABI)) {
            // We found no sub-folder system images but it looks like the top directory
            // has some img files in it. It must be a legacy ARM EABI system image folder.
            found.add(new SystemImage(
                    imgDir,
                    LocationType.IN_LEGACY_FOLDER,
                    defaultTag,
                    SdkConstants.ABI_ARMEABI,
                    FileOp.EMPTY_FILE_ARRAY));
        }

        return found.toArray(new ISystemImage[found.size()]);
    }

    private List<OptionalLibrary> getOptionalLibraries(@NonNull File platformDir) {
        File optionalDir = new File(platformDir, "optional");
        if (!optionalDir.isDirectory()) {
            return Collections.emptyList();
        }

        File optionalJson = new File(optionalDir, "optional.json");
        if (!optionalJson.isFile()) {
            return Collections.emptyList();
        }

        return getLibsFromJson(optionalJson);
    }

    public static class Library {
        String name;
        String jar;
        boolean manifest;
    }


    @VisibleForTesting
    static List<OptionalLibrary> getLibsFromJson(@NonNull File jsonFile) {

        Gson gson = new Gson();

        try {
            Type collectionType = new TypeToken<Collection<Library>>() {
            }.getType();
            Collection<Library> libs = gson
                    .fromJson(Files.newReader(jsonFile, Charsets.UTF_8), collectionType);

            // convert into the right format.
            List<OptionalLibrary> optionalLibraries = Lists.newArrayListWithCapacity(libs.size());

            File rootFolder = jsonFile.getParentFile();
            for (Library lib : libs) {
                optionalLibraries.add(new OptionalLibraryImpl(
                        lib.name,
                        new File(rootFolder, lib.jar),
                        lib.name,
                        lib.manifest));
            }

            return optionalLibraries;
        } catch (FileNotFoundException e) {
            // shouldn't happen since we've checked the file is here, but can happen in
            // some cases (too many files open).
            return Collections.emptyList();
        }
    }

    /** List of items in the platform to check when parsing it. These paths are relative to the
     * platform root folder. */
    private static final String[] sPlatformContentList = new String[] {
        SdkConstants.FN_FRAMEWORK_LIBRARY,
        SdkConstants.FN_FRAMEWORK_AIDL,
    };

    /**
     * Checks the given platform has all the required files, and returns true if they are all
     * present.
     * <p/>This checks the presence of the following files: android.jar, framework.aidl, aapt(.exe),
     * aidl(.exe), dx(.bat), and dx.jar
     *
     * @param fileOp File operation wrapper.
     * @param platform The folder containing the platform.
     * @return An error description if platform is rejected; null if no error is detected.
     */
    @NonNull
    private static String checkPlatformContent(IFileOp fileOp, @NonNull File platform) {
        for (String relativePath : sPlatformContentList) {
            File f = new File(platform, relativePath);
            if (!fileOp.exists(f)) {
                return String.format(
                        "Ignoring platform '%1$s': %2$s is missing.",                  //$NON-NLS-1$
                        platform.getName(), relativePath);
            }
        }
        return null;
    }
}