PackageManagerTests.java revision 315a5fb91dbafe6073435a13d937cee9d26877f6
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.content.pm;
18
19import com.android.frameworks.coretests.R;
20import com.android.internal.content.PackageHelper;
21
22import android.content.BroadcastReceiver;
23import android.content.Context;
24import android.content.Intent;
25import android.content.IntentFilter;
26import android.content.pm.ApplicationInfo;
27import android.content.pm.IPackageMoveObserver;
28import android.content.pm.PackageInfo;
29import android.content.pm.PackageManager;
30import android.content.pm.PackageParser;
31import android.content.pm.PackageManager.NameNotFoundException;
32import android.content.res.Resources;
33import android.content.res.Resources.NotFoundException;
34import android.net.Uri;
35import android.test.AndroidTestCase;
36import android.test.suitebuilder.annotation.Suppress;
37import android.util.DisplayMetrics;
38import android.util.Log;
39import android.os.Environment;
40import android.os.FileUtils;
41import android.os.IBinder;
42import android.os.RemoteException;
43import android.os.ServiceManager;
44import android.os.StatFs;
45import android.os.storage.IMountService;
46import android.os.storage.StorageListener;
47import android.os.storage.StorageManager;
48import android.os.storage.StorageResultCode;
49import android.provider.Settings;
50import android.provider.Settings.SettingNotFoundException;
51import android.test.AndroidTestCase;
52import android.util.DisplayMetrics;
53import android.util.Log;
54
55import java.io.File;
56import java.io.InputStream;
57
58public class PackageManagerTests extends AndroidTestCase {
59    private static final boolean localLOGV = true;
60    public static final String TAG="PackageManagerTests";
61    public final long MAX_WAIT_TIME = 25*1000;
62    public final long WAIT_TIME_INCR = 5*1000;
63    private static final String SECURE_CONTAINERS_PREFIX = "/mnt/asec";
64    private static final int APP_INSTALL_AUTO = PackageHelper.APP_INSTALL_AUTO;
65    private static final int APP_INSTALL_DEVICE = PackageHelper.APP_INSTALL_INTERNAL;
66    private static final int APP_INSTALL_SDCARD = PackageHelper.APP_INSTALL_EXTERNAL;
67    private boolean mOrigState;
68
69    void failStr(String errMsg) {
70        Log.w(TAG, "errMsg="+errMsg);
71        fail(errMsg);
72    }
73    void failStr(Exception e) {
74        failStr(e.getMessage());
75    }
76
77    @Override
78    protected void setUp() throws Exception {
79        super.setUp();
80        mOrigState = getMediaState();
81        if (!mountMedia()) {
82            Log.i(TAG, "sdcard not mounted? Some of these tests might fail");
83        }
84    }
85
86    @Override
87    protected void tearDown() throws Exception {
88        // Restore media state.
89        boolean newState = getMediaState();
90        if (newState != mOrigState) {
91            if (mOrigState) {
92                getMs().mountVolume(Environment.getExternalStorageDirectory().getPath());
93            } else {
94                getMs().unmountVolume(Environment.getExternalStorageDirectory().getPath(), true);
95            }
96        }
97        super.tearDown();
98    }
99
100    private class PackageInstallObserver extends IPackageInstallObserver.Stub {
101        public int returnCode;
102        private boolean doneFlag = false;
103
104        public void packageInstalled(String packageName, int returnCode) {
105            synchronized(this) {
106                this.returnCode = returnCode;
107                doneFlag = true;
108                notifyAll();
109            }
110        }
111
112        public boolean isDone() {
113            return doneFlag;
114        }
115    }
116
117    abstract class GenericReceiver extends BroadcastReceiver {
118        private boolean doneFlag = false;
119        boolean received = false;
120        Intent intent;
121        IntentFilter filter;
122        abstract boolean notifyNow(Intent intent);
123        @Override
124        public void onReceive(Context context, Intent intent) {
125            if (notifyNow(intent)) {
126                synchronized (this) {
127                    received = true;
128                    doneFlag = true;
129                    this.intent = intent;
130                    notifyAll();
131                }
132            }
133        }
134
135        public boolean isDone() {
136            return doneFlag;
137        }
138
139        public void setFilter(IntentFilter filter) {
140            this.filter = filter;
141        }
142    }
143
144    class InstallReceiver extends GenericReceiver {
145        String pkgName;
146
147        InstallReceiver(String pkgName) {
148            this.pkgName = pkgName;
149            IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
150            filter.addDataScheme("package");
151            super.setFilter(filter);
152        }
153
154        public boolean notifyNow(Intent intent) {
155            String action = intent.getAction();
156            if (!Intent.ACTION_PACKAGE_ADDED.equals(action)) {
157                return false;
158            }
159            Uri data = intent.getData();
160            String installedPkg = data.getEncodedSchemeSpecificPart();
161            if (pkgName.equals(installedPkg)) {
162                return true;
163            }
164            return false;
165        }
166    }
167
168    private PackageManager getPm() {
169        return mContext.getPackageManager();
170    }
171
172    private IPackageManager getIPm() {
173        IPackageManager ipm  = IPackageManager.Stub.asInterface(
174                ServiceManager.getService("package"));
175        return ipm;
176    }
177
178    public boolean invokeInstallPackage(Uri packageURI, int flags,
179            GenericReceiver receiver) throws Exception {
180        PackageInstallObserver observer = new PackageInstallObserver();
181        final boolean received = false;
182        mContext.registerReceiver(receiver, receiver.filter);
183        final boolean DEBUG = true;
184        try {
185            // Wait on observer
186            synchronized(observer) {
187                synchronized (receiver) {
188                    getPm().installPackage(packageURI, observer, flags, null);
189                    long waitTime = 0;
190                    while((!observer.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
191                        observer.wait(WAIT_TIME_INCR);
192                        waitTime += WAIT_TIME_INCR;
193                    }
194                    if(!observer.isDone()) {
195                        throw new Exception("Timed out waiting for packageInstalled callback");
196                    }
197                    if (observer.returnCode != PackageManager.INSTALL_SUCCEEDED) {
198                        Log.i(TAG, "Failed to install with error code = " + observer.returnCode);
199                        return false;
200                    }
201                    // Verify we received the broadcast
202                    waitTime = 0;
203                    while((!receiver.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
204                        receiver.wait(WAIT_TIME_INCR);
205                        waitTime += WAIT_TIME_INCR;
206                    }
207                    if(!receiver.isDone()) {
208                        throw new Exception("Timed out waiting for PACKAGE_ADDED notification");
209                    }
210                    return receiver.received;
211                }
212            }
213        } finally {
214            mContext.unregisterReceiver(receiver);
215        }
216    }
217
218    public void invokeInstallPackageFail(Uri packageURI, int flags, int result) throws Exception {
219        PackageInstallObserver observer = new PackageInstallObserver();
220        try {
221            // Wait on observer
222            synchronized(observer) {
223                getPm().installPackage(packageURI, observer, flags, null);
224                long waitTime = 0;
225                while((!observer.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
226                    observer.wait(WAIT_TIME_INCR);
227                    waitTime += WAIT_TIME_INCR;
228                }
229                if(!observer.isDone()) {
230                    throw new Exception("Timed out waiting for packageInstalled callback");
231                }
232                assertEquals(observer.returnCode, result);
233            }
234        } finally {
235        }
236    }
237
238    Uri getInstallablePackage(int fileResId, File outFile) {
239        Resources res = mContext.getResources();
240        InputStream is = null;
241        try {
242            is = res.openRawResource(fileResId);
243        } catch (NotFoundException e) {
244            failStr("Failed to load resource with id: " + fileResId);
245        }
246        FileUtils.setPermissions(outFile.getPath(),
247                FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IRWXO,
248                -1, -1);
249        assertTrue(FileUtils.copyToFile(is, outFile));
250        FileUtils.setPermissions(outFile.getPath(),
251                FileUtils.S_IRWXU | FileUtils.S_IRWXG | FileUtils.S_IRWXO,
252                -1, -1);
253        return Uri.fromFile(outFile);
254    }
255
256    private PackageParser.Package parsePackage(Uri packageURI) {
257        final String archiveFilePath = packageURI.getPath();
258        PackageParser packageParser = new PackageParser(archiveFilePath);
259        File sourceFile = new File(archiveFilePath);
260        DisplayMetrics metrics = new DisplayMetrics();
261        metrics.setToDefaults();
262        PackageParser.Package pkg = packageParser.parsePackage(sourceFile, archiveFilePath, metrics, 0);
263        packageParser = null;
264        return pkg;
265    }
266    private boolean checkSd(long pkgLen) {
267        String status = Environment.getExternalStorageState();
268        if (!status.equals(Environment.MEDIA_MOUNTED)) {
269            return false;
270        }
271        long sdSize = -1;
272        StatFs sdStats = new StatFs(
273                Environment.getExternalStorageDirectory().getPath());
274        sdSize = (long)sdStats.getAvailableBlocks() *
275                (long)sdStats.getBlockSize();
276        // TODO check for thesholds here
277        return pkgLen <= sdSize;
278
279    }
280    private boolean checkInt(long pkgLen) {
281        StatFs intStats = new StatFs(Environment.getDataDirectory().getPath());
282        long intSize = (long)intStats.getBlockCount() *
283                (long)intStats.getBlockSize();
284        long iSize = (long)intStats.getAvailableBlocks() *
285                (long)intStats.getBlockSize();
286        // TODO check for thresholds here?
287        return pkgLen <= iSize;
288    }
289    private static final int INSTALL_LOC_INT = 1;
290    private static final int INSTALL_LOC_SD = 2;
291    private static final int INSTALL_LOC_ERR = -1;
292    private int getInstallLoc(int flags, int expInstallLocation, long pkgLen) {
293        // Flags explicitly over ride everything else.
294        if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0 ) {
295            return INSTALL_LOC_INT;
296        } else if ((flags & PackageManager.INSTALL_EXTERNAL) != 0 ) {
297            return INSTALL_LOC_SD;
298        } else if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
299            return INSTALL_LOC_INT;
300        }
301        // Manifest option takes precedence next
302        if (expInstallLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
303            if (checkSd(pkgLen)) {
304               return INSTALL_LOC_SD;
305            }
306            if (checkInt(pkgLen)) {
307                return INSTALL_LOC_INT;
308            }
309            return INSTALL_LOC_ERR;
310        }
311        if (expInstallLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
312            if (checkInt(pkgLen)) {
313                return INSTALL_LOC_INT;
314            }
315            return INSTALL_LOC_ERR;
316        }
317        if (expInstallLocation == PackageInfo.INSTALL_LOCATION_AUTO) {
318            // Check for free memory internally
319            if (checkInt(pkgLen)) {
320                return INSTALL_LOC_INT;
321            }
322            // Check for free memory externally
323            if (checkSd(pkgLen)) {
324                return INSTALL_LOC_SD;
325            }
326            return INSTALL_LOC_ERR;
327        }
328        // Check for settings preference.
329        boolean checkSd = false;
330        int userPref = getDefaultInstallLoc();
331        if (userPref == APP_INSTALL_DEVICE) {
332            if (checkInt(pkgLen)) {
333                return INSTALL_LOC_INT;
334            }
335            return INSTALL_LOC_ERR;
336        } else if (userPref == APP_INSTALL_SDCARD) {
337            if (checkSd(pkgLen)) {
338                return INSTALL_LOC_SD;
339            }
340            return INSTALL_LOC_ERR;
341        }
342        // Default system policy for apps with no manifest option specified.
343        // Check for free memory internally
344        if (checkInt(pkgLen)) {
345            return INSTALL_LOC_INT;
346        }
347        return INSTALL_LOC_ERR;
348    }
349
350    private void assertInstall(PackageParser.Package pkg, int flags, int expInstallLocation) {
351        try {
352            String pkgName = pkg.packageName;
353            ApplicationInfo info = getPm().getApplicationInfo(pkgName, 0);
354            assertNotNull(info);
355            assertEquals(pkgName, info.packageName);
356            File dataDir = Environment.getDataDirectory();
357            String appInstallPath = new File(dataDir, "app").getPath();
358            String drmInstallPath = new File(dataDir, "app-private").getPath();
359            File srcDir = new File(info.sourceDir);
360            String srcPath = srcDir.getParent();
361            File publicSrcDir = new File(info.publicSourceDir);
362            String publicSrcPath = publicSrcDir.getParent();
363            long pkgLen = new File(info.sourceDir).length();
364
365            if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
366                assertTrue((info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
367                assertEquals(srcPath, drmInstallPath);
368                assertEquals(publicSrcPath, appInstallPath);
369            } else {
370                assertFalse((info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
371                int rLoc = getInstallLoc(flags, expInstallLocation, pkgLen);
372                if (rLoc == INSTALL_LOC_INT) {
373                    assertEquals(srcPath, appInstallPath);
374                    assertEquals(publicSrcPath, appInstallPath);
375                    assertFalse((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
376                } else if (rLoc == INSTALL_LOC_SD){
377                    assertTrue((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
378                    assertTrue(srcPath.startsWith(SECURE_CONTAINERS_PREFIX));
379                    assertTrue(publicSrcPath.startsWith(SECURE_CONTAINERS_PREFIX));
380                } else {
381                    // TODO handle error. Install should have failed.
382                }
383            }
384        } catch (NameNotFoundException e) {
385            failStr("failed with exception : " + e);
386        }
387    }
388
389    private void assertNotInstalled(String pkgName) {
390        try {
391            ApplicationInfo info = getPm().getApplicationInfo(pkgName, 0);
392            fail(pkgName + " shouldnt be installed");
393        } catch (NameNotFoundException e) {
394        }
395    }
396
397    class InstallParams {
398        Uri packageURI;
399        PackageParser.Package pkg;
400        InstallParams(String outFileName, int rawResId) {
401            this.pkg = getParsedPackage(outFileName, rawResId);
402            this.packageURI = Uri.fromFile(new File(pkg.mScanPath));
403        }
404        InstallParams(PackageParser.Package pkg) {
405            this.packageURI = Uri.fromFile(new File(pkg.mScanPath));
406            this.pkg = pkg;
407        }
408        long getApkSize() {
409            File file = new File(pkg.mScanPath);
410            return file.length();
411        }
412    }
413
414    private InstallParams sampleInstallFromRawResource(int flags, boolean cleanUp) {
415        return installFromRawResource("install.apk", R.raw.install, flags, cleanUp,
416                false, -1, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
417    }
418
419    static final String PERM_PACKAGE = "package";
420    static final String PERM_DEFINED = "defined";
421    static final String PERM_UNDEFINED = "undefined";
422    static final String PERM_USED = "used";
423    static final String PERM_NOTUSED = "notused";
424
425    private void assertPermissions(String[] cmds) {
426        final PackageManager pm = getPm();
427        String pkg = null;
428        PackageInfo pkgInfo = null;
429        String mode = PERM_DEFINED;
430        int i = 0;
431        while (i < cmds.length) {
432            String cmd = cmds[i++];
433            if (cmd == PERM_PACKAGE) {
434                pkg = cmds[i++];
435                try {
436                    pkgInfo = pm.getPackageInfo(pkg,
437                            PackageManager.GET_PERMISSIONS
438                            | PackageManager.GET_UNINSTALLED_PACKAGES);
439                } catch (NameNotFoundException e) {
440                    pkgInfo = null;
441                }
442            } else if (cmd == PERM_DEFINED || cmd == PERM_UNDEFINED
443                    || cmd == PERM_USED || cmd == PERM_NOTUSED) {
444                mode = cmds[i++];
445            } else {
446                if (mode == PERM_DEFINED) {
447                    try {
448                        PermissionInfo pi = pm.getPermissionInfo(cmd, 0);
449                        assertNotNull(pi);
450                        assertEquals(pi.packageName, pkg);
451                        assertEquals(pi.name, cmd);
452                        assertNotNull(pkgInfo);
453                        boolean found = false;
454                        for (int j=0; j<pkgInfo.permissions.length && !found; j++) {
455                            if (pkgInfo.permissions[j].name.equals(cmd)) {
456                                found = true;
457                            }
458                        }
459                        if (!found) {
460                            fail("Permission not found: " + cmd);
461                        }
462                    } catch (NameNotFoundException e) {
463                        throw new RuntimeException(e);
464                    }
465                } else if (mode == PERM_UNDEFINED) {
466                    try {
467                        pm.getPermissionInfo(cmd, 0);
468                        throw new RuntimeException("Permission exists: " + cmd);
469                    } catch (NameNotFoundException e) {
470                    }
471                    if (pkgInfo != null) {
472                        boolean found = false;
473                        for (int j=0; j<pkgInfo.permissions.length && !found; j++) {
474                            if (pkgInfo.permissions[j].name.equals(cmd)) {
475                                found = true;
476                            }
477                        }
478                        if (found) {
479                            fail("Permission still exists: " + cmd);
480                        }
481                    }
482                } else if (mode == PERM_USED || mode == PERM_NOTUSED) {
483                    boolean found = false;
484                    for (int j=0; j<pkgInfo.requestedPermissions.length && !found; j++) {
485                        if (pkgInfo.requestedPermissions[j].equals(cmd)) {
486                            found = true;
487                        }
488                    }
489                    if (!found) {
490                        fail("Permission not requested: " + cmd);
491                    }
492                    if (mode == PERM_USED) {
493                        if (pm.checkPermission(cmd, pkg)
494                                != PackageManager.PERMISSION_GRANTED) {
495                            fail("Permission not granted: " + cmd);
496                        }
497                    } else {
498                        if (pm.checkPermission(cmd, pkg)
499                                != PackageManager.PERMISSION_DENIED) {
500                            fail("Permission granted: " + cmd);
501                        }
502                    }
503                }
504            }
505        }
506    }
507
508    private PackageParser.Package getParsedPackage(String outFileName, int rawResId) {
509        PackageManager pm = mContext.getPackageManager();
510        File filesDir = mContext.getFilesDir();
511        File outFile = new File(filesDir, outFileName);
512        Uri packageURI = getInstallablePackage(rawResId, outFile);
513        PackageParser.Package pkg = parsePackage(packageURI);
514        return pkg;
515    }
516
517    /*
518     * Utility function that reads a apk bundled as a raw resource
519     * copies it into own data directory and invokes
520     * PackageManager api to install it.
521     */
522    private void installFromRawResource(InstallParams ip,
523            int flags, boolean cleanUp, boolean fail, int result,
524            int expInstallLocation) {
525        PackageManager pm = mContext.getPackageManager();
526        PackageParser.Package pkg = ip.pkg;
527        Uri packageURI = ip.packageURI;
528        if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) == 0) {
529            // Make sure the package doesn't exist
530            try {
531                ApplicationInfo appInfo = pm.getApplicationInfo(pkg.packageName,
532                        PackageManager.GET_UNINSTALLED_PACKAGES);
533                GenericReceiver receiver = new DeleteReceiver(pkg.packageName);
534                invokeDeletePackage(pkg.packageName, 0, receiver);
535            } catch (NameNotFoundException e1) {
536            } catch (Exception e) {
537                failStr(e);
538            }
539        }
540        try {
541            if (fail) {
542                invokeInstallPackageFail(packageURI, flags, result);
543                if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) == 0) {
544                    assertNotInstalled(pkg.packageName);
545                }
546            } else {
547                InstallReceiver receiver = new InstallReceiver(pkg.packageName);
548                assertTrue(invokeInstallPackage(packageURI, flags, receiver));
549                // Verify installed information
550                assertInstall(pkg, flags, expInstallLocation);
551            }
552        } catch (Exception e) {
553            failStr("Failed with exception : " + e);
554        } finally {
555            if (cleanUp) {
556                cleanUpInstall(ip);
557            }
558        }
559    }
560
561    /*
562     * Utility function that reads a apk bundled as a raw resource
563     * copies it into own data directory and invokes
564     * PackageManager api to install it.
565     */
566    private InstallParams installFromRawResource(String outFileName,
567            int rawResId, int flags, boolean cleanUp, boolean fail, int result,
568            int expInstallLocation) {
569        PackageManager pm = mContext.getPackageManager();
570        InstallParams ip = new InstallParams(outFileName, rawResId);
571        installFromRawResource(ip, flags, cleanUp, fail, result, expInstallLocation);
572        return ip;
573    }
574
575    public void testInstallNormalInternal() {
576        sampleInstallFromRawResource(0, true);
577    }
578
579    public void testInstallFwdLockedInternal() {
580        sampleInstallFromRawResource(PackageManager.INSTALL_FORWARD_LOCK, true);
581    }
582
583    public void testInstallSdcard() {
584        sampleInstallFromRawResource(PackageManager.INSTALL_EXTERNAL, true);
585    }
586
587    /* ------------------------- Test replacing packages --------------*/
588    class ReplaceReceiver extends GenericReceiver {
589        String pkgName;
590        final static int INVALID = -1;
591        final static int REMOVED = 1;
592        final static int ADDED = 2;
593        final static int REPLACED = 3;
594        int removed = INVALID;
595        // for updated system apps only
596        boolean update = false;
597
598        ReplaceReceiver(String pkgName) {
599            this.pkgName = pkgName;
600            filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
601            filter.addAction(Intent.ACTION_PACKAGE_ADDED);
602            if (update) {
603                filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
604            }
605            filter.addDataScheme("package");
606            super.setFilter(filter);
607        }
608
609        public boolean notifyNow(Intent intent) {
610            String action = intent.getAction();
611            Uri data = intent.getData();
612            String installedPkg = data.getEncodedSchemeSpecificPart();
613            if (pkgName == null || !pkgName.equals(installedPkg)) {
614                return false;
615            }
616            if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
617                removed = REMOVED;
618            } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
619                if (removed != REMOVED) {
620                    return false;
621                }
622                boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
623                if (!replacing) {
624                    return false;
625                }
626                removed = ADDED;
627                if (!update) {
628                    return true;
629                }
630            } else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
631                if (removed != ADDED) {
632                    return false;
633                }
634                removed = REPLACED;
635                return true;
636            }
637            return false;
638        }
639    }
640
641    /*
642     * Utility function that reads a apk bundled as a raw resource
643     * copies it into own data directory and invokes
644     * PackageManager api to install first and then replace it
645     * again.
646     */
647    private void sampleReplaceFromRawResource(int flags) {
648        InstallParams ip = sampleInstallFromRawResource(flags, false);
649        boolean replace = ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0);
650        Log.i(TAG, "replace=" + replace);
651        GenericReceiver receiver;
652        if (replace) {
653            receiver = new ReplaceReceiver(ip.pkg.packageName);
654            Log.i(TAG, "Creating replaceReceiver");
655        } else {
656            receiver = new InstallReceiver(ip.pkg.packageName);
657        }
658        try {
659            try {
660                assertEquals(invokeInstallPackage(ip.packageURI, flags, receiver), replace);
661                if (replace) {
662                    assertInstall(ip.pkg, flags, ip.pkg.installLocation);
663                }
664            } catch (Exception e) {
665                failStr("Failed with exception : " + e);
666            }
667        } finally {
668            cleanUpInstall(ip);
669        }
670    }
671
672    public void testReplaceFailNormalInternal() {
673        sampleReplaceFromRawResource(0);
674    }
675
676    public void testReplaceFailFwdLockedInternal() {
677        sampleReplaceFromRawResource(PackageManager.INSTALL_FORWARD_LOCK);
678    }
679
680    public void testReplaceFailSdcard() {
681        sampleReplaceFromRawResource(PackageManager.INSTALL_EXTERNAL);
682    }
683
684    public void testReplaceNormalInternal() {
685        sampleReplaceFromRawResource(PackageManager.INSTALL_REPLACE_EXISTING);
686    }
687
688    public void testReplaceFwdLockedInternal() {
689        sampleReplaceFromRawResource(PackageManager.INSTALL_REPLACE_EXISTING |
690                PackageManager.INSTALL_FORWARD_LOCK);
691    }
692
693    public void testReplaceSdcard() {
694        sampleReplaceFromRawResource(PackageManager.INSTALL_REPLACE_EXISTING |
695                PackageManager.INSTALL_EXTERNAL);
696    }
697
698    /* -------------- Delete tests ---*/
699    class DeleteObserver extends IPackageDeleteObserver.Stub {
700
701        public boolean succeeded;
702        private boolean doneFlag = false;
703
704        public boolean isDone() {
705            return doneFlag;
706        }
707
708        public void packageDeleted(boolean succeeded) throws RemoteException {
709            synchronized(this) {
710                this.succeeded = succeeded;
711                doneFlag = true;
712                notifyAll();
713            }
714        }
715    }
716
717    class DeleteReceiver extends GenericReceiver {
718        String pkgName;
719
720        DeleteReceiver(String pkgName) {
721            this.pkgName = pkgName;
722            IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
723            filter.addDataScheme("package");
724            super.setFilter(filter);
725        }
726
727        public boolean notifyNow(Intent intent) {
728            String action = intent.getAction();
729            if (!Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
730                return false;
731            }
732            Uri data = intent.getData();
733            String installedPkg = data.getEncodedSchemeSpecificPart();
734            if (pkgName.equals(installedPkg)) {
735                return true;
736            }
737            return false;
738        }
739    }
740
741    public boolean invokeDeletePackage(final String pkgName, int flags,
742            GenericReceiver receiver) throws Exception {
743        DeleteObserver observer = new DeleteObserver();
744        final boolean received = false;
745        mContext.registerReceiver(receiver, receiver.filter);
746        try {
747            // Wait on observer
748            synchronized(observer) {
749                synchronized (receiver) {
750                    getPm().deletePackage(pkgName, observer, flags);
751                    long waitTime = 0;
752                    while((!observer.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
753                        observer.wait(WAIT_TIME_INCR);
754                        waitTime += WAIT_TIME_INCR;
755                    }
756                    if(!observer.isDone()) {
757                        throw new Exception("Timed out waiting for packageInstalled callback");
758                    }
759                    // Verify we received the broadcast
760                    waitTime = 0;
761                    while((!receiver.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
762                        receiver.wait(WAIT_TIME_INCR);
763                        waitTime += WAIT_TIME_INCR;
764                    }
765                    if(!receiver.isDone()) {
766                        throw new Exception("Timed out waiting for PACKAGE_REMOVED notification");
767                    }
768                    return receiver.received;
769                }
770            }
771        } finally {
772            mContext.unregisterReceiver(receiver);
773        }
774    }
775
776    public void deleteFromRawResource(int iFlags, int dFlags) {
777        InstallParams ip = sampleInstallFromRawResource(iFlags, false);
778        boolean retainData = ((dFlags & PackageManager.DONT_DELETE_DATA) != 0);
779        GenericReceiver receiver = new DeleteReceiver(ip.pkg.packageName);
780        DeleteObserver observer = new DeleteObserver();
781        try {
782            assertTrue(invokeDeletePackage(ip.pkg.packageName, dFlags, receiver));
783            ApplicationInfo info = null;
784            Log.i(TAG, "okay4");
785            try {
786            info = getPm().getApplicationInfo(ip.pkg.packageName,
787                    PackageManager.GET_UNINSTALLED_PACKAGES);
788            } catch (NameNotFoundException e) {
789                info = null;
790            }
791            if (retainData) {
792                assertNotNull(info);
793                assertEquals(info.packageName, ip.pkg.packageName);
794                File file = new File(info.dataDir);
795                assertTrue(file.exists());
796            } else {
797                assertNull(info);
798            }
799        } catch (Exception e) {
800            failStr(e);
801        } finally {
802            cleanUpInstall(ip);
803        }
804    }
805
806    public void testDeleteNormalInternal() {
807        deleteFromRawResource(0, 0);
808    }
809
810    public void testDeleteFwdLockedInternal() {
811        deleteFromRawResource(PackageManager.INSTALL_FORWARD_LOCK, 0);
812    }
813
814    public void testDeleteSdcard() {
815        deleteFromRawResource(PackageManager.INSTALL_EXTERNAL, 0);
816    }
817
818    public void testDeleteNormalInternalRetainData() {
819        deleteFromRawResource(0, PackageManager.DONT_DELETE_DATA);
820    }
821
822    public void testDeleteFwdLockedInternalRetainData() {
823        deleteFromRawResource(PackageManager.INSTALL_FORWARD_LOCK, PackageManager.DONT_DELETE_DATA);
824    }
825
826    public void testDeleteSdcardRetainData() {
827        deleteFromRawResource(PackageManager.INSTALL_EXTERNAL, PackageManager.DONT_DELETE_DATA);
828    }
829
830    /* sdcard mount/unmount tests ******/
831
832    class SdMountReceiver extends GenericReceiver {
833        String pkgNames[];
834        boolean status = true;
835
836        SdMountReceiver(String[] pkgNames) {
837            this.pkgNames = pkgNames;
838            IntentFilter filter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
839            super.setFilter(filter);
840        }
841
842        public boolean notifyNow(Intent intent) {
843            Log.i(TAG, "okay 1");
844            String action = intent.getAction();
845            if (!Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
846                return false;
847            }
848            String rpkgList[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
849            for (String pkg : pkgNames) {
850                boolean found = false;
851                for (String rpkg : rpkgList) {
852                    if (rpkg.equals(pkg)) {
853                        found = true;
854                        break;
855                    }
856                }
857                if (!found) {
858                    status = false;
859                    return true;
860                }
861            }
862            return true;
863        }
864    }
865
866    class SdUnMountReceiver extends GenericReceiver {
867        String pkgNames[];
868        boolean status = true;
869
870        SdUnMountReceiver(String[] pkgNames) {
871            this.pkgNames = pkgNames;
872            IntentFilter filter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
873            super.setFilter(filter);
874        }
875
876        public boolean notifyNow(Intent intent) {
877            String action = intent.getAction();
878            if (!Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
879                return false;
880            }
881            String rpkgList[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
882            for (String pkg : pkgNames) {
883                boolean found = false;
884                for (String rpkg : rpkgList) {
885                    if (rpkg.equals(pkg)) {
886                        found = true;
887                        break;
888                    }
889                }
890                if (!found) {
891                    status = false;
892                    return true;
893                }
894            }
895            return true;
896        }
897    }
898
899    IMountService getMs() {
900        IBinder service = ServiceManager.getService("mount");
901        if (service != null) {
902            return IMountService.Stub.asInterface(service);
903        } else {
904            Log.e(TAG, "Can't get mount service");
905        }
906        return null;
907    }
908
909    boolean getMediaState() {
910        try {
911        String mPath = Environment.getExternalStorageDirectory().getPath();
912        String state = getMs().getVolumeState(mPath);
913        return Environment.MEDIA_MOUNTED.equals(state);
914        } catch (RemoteException e) {
915            return false;
916        }
917    }
918
919    boolean mountMedia() {
920        if (getMediaState()) {
921            return true;
922        }
923        try {
924        String mPath = Environment.getExternalStorageDirectory().toString();
925        int ret = getMs().mountVolume(mPath);
926        return ret == StorageResultCode.OperationSucceeded;
927        } catch (RemoteException e) {
928            return false;
929        }
930    }
931
932    private boolean unmountMedia() {
933        String path = Environment.getExternalStorageDirectory().getPath();
934        try {
935            String state = getMs().getVolumeState(path);
936            if (Environment.MEDIA_UNMOUNTED.equals(state)) {
937                return true;
938            }
939        } catch (RemoteException e) {
940            failStr(e);
941        }
942
943        StorageListener observer = new StorageListener();
944        StorageManager sm = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
945        sm.registerListener(observer);
946        try {
947            // Wait on observer
948            synchronized(observer) {
949                getMs().unmountVolume(path, true);
950                long waitTime = 0;
951                while((!observer.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
952                    observer.wait(WAIT_TIME_INCR);
953                    waitTime += WAIT_TIME_INCR;
954                }
955                if(!observer.isDone()) {
956                    throw new Exception("Timed out waiting for unmount media notification");
957                }
958                return true;
959            }
960        } catch (Exception e) {
961            Log.e(TAG, "Exception : " + e);
962            return false;
963        } finally {
964            sm.unregisterListener(observer);
965        }
966    }
967
968    private boolean mountFromRawResource() {
969        // Install pkg on sdcard
970        InstallParams ip = sampleInstallFromRawResource(PackageManager.INSTALL_EXTERNAL, false);
971        if (localLOGV) Log.i(TAG, "Installed pkg on sdcard");
972        boolean origState = getMediaState();
973        boolean registeredReceiver = false;
974        SdMountReceiver receiver = new SdMountReceiver(new String[]{ip.pkg.packageName});
975        try {
976            if (localLOGV) Log.i(TAG, "Unmounting media");
977            // Unmount media
978            assertTrue(unmountMedia());
979            if (localLOGV) Log.i(TAG, "Unmounted media");
980            // Register receiver here
981            PackageManager pm = getPm();
982            mContext.registerReceiver(receiver, receiver.filter);
983            registeredReceiver = true;
984
985            // Wait on receiver
986            synchronized (receiver) {
987                if (localLOGV) Log.i(TAG, "Mounting media");
988                // Mount media again
989                assertTrue(mountMedia());
990                if (localLOGV) Log.i(TAG, "Mounted media");
991                if (localLOGV) Log.i(TAG, "Waiting for notification");
992                long waitTime = 0;
993                // Verify we received the broadcast
994                waitTime = 0;
995                while((!receiver.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
996                    receiver.wait(WAIT_TIME_INCR);
997                    waitTime += WAIT_TIME_INCR;
998                }
999                if(!receiver.isDone()) {
1000                    failStr("Timed out waiting for EXTERNAL_APPLICATIONS notification");
1001                }
1002                return receiver.received;
1003            }
1004        } catch (InterruptedException e) {
1005            failStr(e);
1006            return false;
1007        } finally {
1008            if (registeredReceiver) mContext.unregisterReceiver(receiver);
1009            // Restore original media state
1010            if (origState) {
1011                mountMedia();
1012            } else {
1013                unmountMedia();
1014            }
1015            if (localLOGV) Log.i(TAG, "Cleaning up install");
1016            cleanUpInstall(ip);
1017        }
1018    }
1019
1020    /*
1021     * Install package on sdcard. Unmount and then mount the media.
1022     * (Use PackageManagerService private api for now)
1023     * Make sure the installed package is available.
1024     * STOPSHIP will uncomment when MountService api's to mount/unmount
1025     * are made asynchronous.
1026     */
1027    public void xxxtestMountSdNormalInternal() {
1028        assertTrue(mountFromRawResource());
1029    }
1030
1031    void cleanUpInstall(InstallParams ip) {
1032        if (ip == null) {
1033            return;
1034        }
1035        Runtime.getRuntime().gc();
1036        Log.i(TAG, "Deleting package : " + ip.pkg.packageName);
1037        getPm().deletePackage(ip.pkg.packageName, null, 0);
1038        File outFile = new File(ip.pkg.mScanPath);
1039        if (outFile != null && outFile.exists()) {
1040            outFile.delete();
1041        }
1042    }
1043    void cleanUpInstall(String pkgName) {
1044        if (pkgName == null) {
1045            return;
1046        }
1047        Log.i(TAG, "Deleting package : " + pkgName);
1048        try {
1049            ApplicationInfo info = getPm().getApplicationInfo(pkgName,
1050                    PackageManager.GET_UNINSTALLED_PACKAGES);
1051            if (info != null) {
1052                getPm().deletePackage(pkgName, null, 0);
1053            }
1054        } catch (NameNotFoundException e) {}
1055    }
1056
1057    public void testManifestInstallLocationInternal() {
1058        installFromRawResource("install.apk", R.raw.install_loc_internal,
1059                0, true, false, -1, PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
1060    }
1061
1062    public void testManifestInstallLocationSdcard() {
1063        installFromRawResource("install.apk", R.raw.install_loc_sdcard,
1064                0, true, false, -1, PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1065    }
1066
1067    public void testManifestInstallLocationAuto() {
1068        installFromRawResource("install.apk", R.raw.install_loc_auto,
1069                0, true, false, -1, PackageInfo.INSTALL_LOCATION_AUTO);
1070    }
1071
1072    public void testManifestInstallLocationUnspecified() {
1073        installFromRawResource("install.apk", R.raw.install_loc_unspecified,
1074                0, true, false, -1, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
1075    }
1076
1077    public void testManifestInstallLocationFwdLockedFlagSdcard() {
1078        installFromRawResource("install.apk", R.raw.install_loc_unspecified,
1079                PackageManager.INSTALL_FORWARD_LOCK |
1080                PackageManager.INSTALL_EXTERNAL, true, true,
1081                PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION,
1082                PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
1083    }
1084
1085    public void testManifestInstallLocationFwdLockedSdcard() {
1086        installFromRawResource("install.apk", R.raw.install_loc_sdcard,
1087                PackageManager.INSTALL_FORWARD_LOCK, true, false,
1088                -1,
1089                PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1090    }
1091
1092    /*
1093     * Install a package on internal flash via PackageManager install flag. Replace
1094     * the package via flag to install on sdcard. Make sure the new flag overrides
1095     * the old install location.
1096     */
1097    public void testReplaceFlagInternalSdcard() {
1098        int iFlags = 0;
1099        int rFlags = PackageManager.INSTALL_EXTERNAL;
1100        InstallParams ip = sampleInstallFromRawResource(iFlags, false);
1101        GenericReceiver receiver = new ReplaceReceiver(ip.pkg.packageName);
1102        int replaceFlags = rFlags | PackageManager.INSTALL_REPLACE_EXISTING;
1103        try {
1104            assertEquals(invokeInstallPackage(ip.packageURI, replaceFlags, receiver), true);
1105            assertInstall(ip.pkg, rFlags, ip.pkg.installLocation);
1106        } catch (Exception e) {
1107            failStr("Failed with exception : " + e);
1108        } finally {
1109            cleanUpInstall(ip);
1110        }
1111    }
1112
1113    /*
1114     * Install a package on sdcard via PackageManager install flag. Replace
1115     * the package with no flags or manifest option and make sure the old
1116     * install location is retained.
1117     */
1118    public void testReplaceFlagSdcardInternal() {
1119        int iFlags = PackageManager.INSTALL_EXTERNAL;
1120        int rFlags = 0;
1121        InstallParams ip = sampleInstallFromRawResource(iFlags, false);
1122        GenericReceiver receiver = new ReplaceReceiver(ip.pkg.packageName);
1123        int replaceFlags = rFlags | PackageManager.INSTALL_REPLACE_EXISTING;
1124        try {
1125            assertEquals(invokeInstallPackage(ip.packageURI, replaceFlags, receiver), true);
1126            assertInstall(ip.pkg, iFlags, ip.pkg.installLocation);
1127        } catch (Exception e) {
1128            failStr("Failed with exception : " + e);
1129        } finally {
1130            cleanUpInstall(ip);
1131        }
1132    }
1133
1134    public void testManifestInstallLocationReplaceInternalSdcard() {
1135        int iFlags = 0;
1136        int iApk = R.raw.install_loc_internal;
1137        int rFlags = 0;
1138        int rApk = R.raw.install_loc_sdcard;
1139        InstallParams ip = installFromRawResource("install.apk", iApk,
1140                iFlags, false,
1141                false, -1, PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
1142        GenericReceiver receiver = new ReplaceReceiver(ip.pkg.packageName);
1143        int replaceFlags = rFlags | PackageManager.INSTALL_REPLACE_EXISTING;
1144        try {
1145            InstallParams rp = installFromRawResource("install.apk", rApk,
1146                    replaceFlags, false,
1147                    false, -1, PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1148            assertInstall(rp.pkg, replaceFlags, rp.pkg.installLocation);
1149        } catch (Exception e) {
1150            failStr("Failed with exception : " + e);
1151        } finally {
1152            cleanUpInstall(ip);
1153        }
1154    }
1155
1156    public void testManifestInstallLocationReplaceSdcardInternal() {
1157        int iFlags = 0;
1158        int iApk = R.raw.install_loc_sdcard;
1159        int rFlags = 0;
1160        int rApk = R.raw.install_loc_unspecified;
1161        InstallParams ip = installFromRawResource("install.apk", iApk,
1162                iFlags, false,
1163                false, -1, PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1164        int replaceFlags = rFlags | PackageManager.INSTALL_REPLACE_EXISTING;
1165        try {
1166            InstallParams rp = installFromRawResource("install.apk", rApk,
1167                    replaceFlags, false,
1168                    false, -1, PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1169            assertInstall(rp.pkg, replaceFlags, ip.pkg.installLocation);
1170        } catch (Exception e) {
1171            failStr("Failed with exception : " + e);
1172        } finally {
1173            cleanUpInstall(ip);
1174        }
1175    }
1176
1177    class MoveReceiver extends GenericReceiver {
1178        String pkgName;
1179        final static int INVALID = -1;
1180        final static int REMOVED = 1;
1181        final static int ADDED = 2;
1182        int removed = INVALID;
1183
1184        MoveReceiver(String pkgName) {
1185            this.pkgName = pkgName;
1186            filter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
1187            filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1188            super.setFilter(filter);
1189        }
1190
1191        public boolean notifyNow(Intent intent) {
1192            String action = intent.getAction();
1193            Log.i(TAG, "MoveReceiver::" + action);
1194            if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1195                String[] list = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1196                if (list != null) {
1197                    for (String pkg : list) {
1198                        if (pkg.equals(pkgName)) {
1199                            removed = REMOVED;
1200                            break;
1201                        }
1202                    }
1203                }
1204                removed = REMOVED;
1205            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
1206                if (removed != REMOVED) {
1207                    return false;
1208                }
1209                String[] list = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
1210                if (list != null) {
1211                    for (String pkg : list) {
1212                        if (pkg.equals(pkgName)) {
1213                            removed = ADDED;
1214                            return true;
1215                        }
1216                    }
1217                }
1218            }
1219            return false;
1220        }
1221    }
1222
1223    private class PackageMoveObserver extends IPackageMoveObserver.Stub {
1224        public int returnCode;
1225        private boolean doneFlag = false;
1226        public String packageName;
1227        public PackageMoveObserver(String pkgName) {
1228            packageName = pkgName;
1229        }
1230        public void packageMoved(String packageName, int returnCode) {
1231            Log.i("DEBUG_MOVE::", "pkg = " + packageName + ", " + "ret = " + returnCode);
1232            if (!packageName.equals(this.packageName)) {
1233                return;
1234            }
1235            synchronized(this) {
1236                this.returnCode = returnCode;
1237                doneFlag = true;
1238                notifyAll();
1239            }
1240        }
1241
1242        public boolean isDone() {
1243            return doneFlag;
1244        }
1245    }
1246
1247    public boolean invokeMovePackage(String pkgName, int flags,
1248            GenericReceiver receiver) throws Exception {
1249        PackageMoveObserver observer = new PackageMoveObserver(pkgName);
1250        final boolean received = false;
1251        mContext.registerReceiver(receiver, receiver.filter);
1252        try {
1253            // Wait on observer
1254            synchronized(observer) {
1255                synchronized (receiver) {
1256                    getPm().movePackage(pkgName, observer, flags);
1257                    long waitTime = 0;
1258                    while((!observer.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
1259                        observer.wait(WAIT_TIME_INCR);
1260                        waitTime += WAIT_TIME_INCR;
1261                    }
1262                    if(!observer.isDone()) {
1263                        throw new Exception("Timed out waiting for pkgmove callback");
1264                    }
1265                    if (observer.returnCode != PackageManager.MOVE_SUCCEEDED) {
1266                        return false;
1267                    }
1268                    // Verify we received the broadcast
1269                    waitTime = 0;
1270                    while((!receiver.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
1271                        receiver.wait(WAIT_TIME_INCR);
1272                        waitTime += WAIT_TIME_INCR;
1273                    }
1274                    if(!receiver.isDone()) {
1275                        throw new Exception("Timed out waiting for MOVE notifications");
1276                    }
1277                    return receiver.received;
1278                }
1279            }
1280        } finally {
1281            mContext.unregisterReceiver(receiver);
1282        }
1283    }
1284    private boolean invokeMovePackageFail(String pkgName, int flags, int errCode) throws Exception {
1285        PackageMoveObserver observer = new PackageMoveObserver(pkgName);
1286        try {
1287            // Wait on observer
1288            synchronized(observer) {
1289                getPm().movePackage(pkgName, observer, flags);
1290                long waitTime = 0;
1291                while((!observer.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
1292                    observer.wait(WAIT_TIME_INCR);
1293                    waitTime += WAIT_TIME_INCR;
1294                }
1295                if(!observer.isDone()) {
1296                    throw new Exception("Timed out waiting for pkgmove callback");
1297                }
1298                assertEquals(errCode, observer.returnCode);
1299            }
1300        } finally {
1301        }
1302        return true;
1303    }
1304
1305    private int getDefaultInstallLoc() {
1306        int origDefaultLoc = PackageInfo.INSTALL_LOCATION_AUTO;
1307        try {
1308            origDefaultLoc = Settings.System.getInt(mContext.getContentResolver(), Settings.Secure.DEFAULT_INSTALL_LOCATION);
1309        } catch (SettingNotFoundException e1) {
1310        }
1311        return origDefaultLoc;
1312    }
1313
1314    private void setInstallLoc(int loc) {
1315        Settings.System.putInt(mContext.getContentResolver(),
1316                Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
1317    }
1318    /*
1319     * Tests for moving apps between internal and external storage
1320     */
1321    /*
1322     * Utility function that reads a apk bundled as a raw resource
1323     * copies it into own data directory and invokes
1324     * PackageManager api to install first and then replace it
1325     * again.
1326     */
1327
1328    private void moveFromRawResource(String outFileName,
1329            int rawResId, int installFlags, int moveFlags, boolean cleanUp,
1330            boolean fail, int result) {
1331        int origDefaultLoc = getDefaultInstallLoc();
1332        InstallParams ip = null;
1333        try {
1334            setInstallLoc(PackageHelper.APP_INSTALL_AUTO);
1335            // Install first
1336            ip = installFromRawResource("install.apk", rawResId, installFlags, false,
1337                    false, -1, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
1338            ApplicationInfo oldAppInfo = getPm().getApplicationInfo(ip.pkg.packageName, 0);
1339            if (fail) {
1340                assertTrue(invokeMovePackageFail(ip.pkg.packageName, moveFlags, result));
1341                ApplicationInfo info = getPm().getApplicationInfo(ip.pkg.packageName, 0);
1342                assertNotNull(info);
1343                assertEquals(oldAppInfo.flags, info.flags);
1344            } else {
1345                // Create receiver based on expRetCode
1346                MoveReceiver receiver = new MoveReceiver(ip.pkg.packageName);
1347                boolean retCode = invokeMovePackage(ip.pkg.packageName, moveFlags,
1348                        receiver);
1349                assertTrue(retCode);
1350                ApplicationInfo info = getPm().getApplicationInfo(ip.pkg.packageName, 0);
1351                assertNotNull(info);
1352                if ((moveFlags & PackageManager.MOVE_INTERNAL) != 0) {
1353                    assertTrue((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) == 0);
1354                } else if ((moveFlags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0){
1355                    assertTrue((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
1356                }
1357            }
1358        } catch (NameNotFoundException e) {
1359            failStr("Pkg hasnt been installed correctly");
1360        } catch (Exception e) {
1361            failStr("Failed with exception : " + e);
1362        } finally {
1363            if (ip != null) {
1364                cleanUpInstall(ip);
1365            }
1366            // Restore default install location
1367            setInstallLoc(origDefaultLoc);
1368        }
1369    }
1370    private void sampleMoveFromRawResource(int installFlags, int moveFlags, boolean fail,
1371            int result) {
1372        moveFromRawResource("install.apk",
1373                R.raw.install, installFlags, moveFlags, true,
1374                fail, result);
1375    }
1376
1377    public void testMoveAppInternalToExternal() {
1378        int installFlags = PackageManager.INSTALL_INTERNAL;
1379        int moveFlags = PackageManager.MOVE_EXTERNAL_MEDIA;
1380        boolean fail = false;
1381        int result = PackageManager.MOVE_SUCCEEDED;
1382        sampleMoveFromRawResource(installFlags, moveFlags, fail, result);
1383    }
1384
1385    public void testMoveAppInternalToInternal() {
1386        int installFlags = PackageManager.INSTALL_INTERNAL;
1387        int moveFlags = PackageManager.MOVE_INTERNAL;
1388        boolean fail = true;
1389        int result = PackageManager.MOVE_FAILED_INVALID_LOCATION;
1390        sampleMoveFromRawResource(installFlags, moveFlags, fail, result);
1391    }
1392
1393    public void testMoveAppExternalToExternal() {
1394        int installFlags = PackageManager.INSTALL_EXTERNAL;
1395        int moveFlags = PackageManager.MOVE_EXTERNAL_MEDIA;
1396        boolean fail = true;
1397        int result = PackageManager.MOVE_FAILED_INVALID_LOCATION;
1398        sampleMoveFromRawResource(installFlags, moveFlags, fail, result);
1399    }
1400    public void testMoveAppExternalToInternal() {
1401        int installFlags = PackageManager.INSTALL_EXTERNAL;
1402        int moveFlags = PackageManager.MOVE_INTERNAL;
1403        boolean fail = false;
1404        int result = PackageManager.MOVE_SUCCEEDED;
1405        sampleMoveFromRawResource(installFlags, moveFlags, fail, result);
1406    }
1407    public void testMoveAppForwardLocked() {
1408        int installFlags = PackageManager.INSTALL_FORWARD_LOCK;
1409        int moveFlags = PackageManager.MOVE_EXTERNAL_MEDIA;
1410        boolean fail = true;
1411        int result = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
1412        sampleMoveFromRawResource(installFlags, moveFlags, fail, result);
1413    }
1414    public void testMoveAppFailInternalToExternalDelete() {
1415        int installFlags = 0;
1416        int moveFlags = PackageManager.MOVE_EXTERNAL_MEDIA;
1417        boolean fail = true;
1418        final int result = PackageManager.MOVE_FAILED_DOESNT_EXIST;
1419
1420        int rawResId = R.raw.install;
1421        int origDefaultLoc = getDefaultInstallLoc();
1422        InstallParams ip = null;
1423        try {
1424            PackageManager pm = getPm();
1425            setInstallLoc(PackageHelper.APP_INSTALL_AUTO);
1426            // Install first
1427            ip = installFromRawResource("install.apk", R.raw.install, installFlags, false,
1428                    false, -1, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
1429            // Delete the package now retaining data.
1430            pm.deletePackage(ip.pkg.packageName, null, PackageManager.DONT_DELETE_DATA);
1431            assertTrue(invokeMovePackageFail(ip.pkg.packageName, moveFlags, result));
1432        } catch (Exception e) {
1433            failStr(e);
1434        } finally {
1435            if (ip != null) {
1436                cleanUpInstall(ip);
1437            }
1438            // Restore default install location
1439            setInstallLoc(origDefaultLoc);
1440        }
1441    }
1442    /*
1443     * Test that an install error code is returned when media is unmounted
1444     * and package installed on sdcard via package manager flag.
1445     */
1446    public void testInstallSdcardUnmount() {
1447        boolean origState = getMediaState();
1448        try {
1449            // Unmount sdcard
1450            assertTrue(unmountMedia());
1451            // Try to install and make sure an error code is returned.
1452            installFromRawResource("install.apk", R.raw.install,
1453                    PackageManager.INSTALL_EXTERNAL, false,
1454                    true, PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE,
1455                    PackageInfo.INSTALL_LOCATION_AUTO);
1456        } finally {
1457            // Restore original media state
1458            if (origState) {
1459                mountMedia();
1460            } else {
1461                unmountMedia();
1462            }
1463        }
1464    }
1465
1466    /*
1467    * Unmount sdcard. Try installing an app with manifest option to install
1468    * on sdcard. Make sure it gets installed on internal flash.
1469    */
1470   public void testInstallManifestSdcardUnmount() {
1471       boolean origState = getMediaState();
1472       try {
1473           // Unmount sdcard
1474           assertTrue(unmountMedia());
1475           InstallParams ip = new InstallParams("install.apk", R.raw.install_loc_sdcard);
1476           installFromRawResource(ip, 0, true, false, -1,
1477                   PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
1478       } finally {
1479           // Restore original media state
1480           if (origState) {
1481               mountMedia();
1482           } else {
1483               unmountMedia();
1484           }
1485       }
1486   }
1487
1488   /*---------- Recommended install location tests ----*/
1489   /* Precedence: FlagManifestExistingUser
1490    * PrecedenceSuffixes:
1491    * Flag : FlagI, FlagE, FlagF
1492    * I - internal, E - external, F - forward locked, Flag suffix absent if not using any option.
1493    * Manifest: ManifestI, ManifestE, ManifestA, Manifest suffix absent if not using any option.
1494    * Existing: Existing suffix absent if not existing.
1495    * User: UserI, UserE, UserA, User suffix absent if not existing.
1496    *
1497    */
1498   /*
1499    * Install an app on internal flash
1500    */
1501   public void testFlagI() {
1502       sampleInstallFromRawResource(PackageManager.INSTALL_INTERNAL, true);
1503   }
1504   /*
1505    * Install an app on sdcard.
1506    */
1507   public void testFlagE() {
1508       sampleInstallFromRawResource(PackageManager.INSTALL_EXTERNAL, true);
1509   }
1510
1511   /*
1512    * Install an app on sdcard.
1513    */
1514   public void testFlagF() {
1515       sampleInstallFromRawResource(PackageManager.INSTALL_FORWARD_LOCK, true);
1516   }
1517   /*
1518    * Install an app with both internal and external flags set. should fail
1519    */
1520   public void testFlagIE() {
1521       installFromRawResource("install.apk", R.raw.install,
1522               PackageManager.INSTALL_EXTERNAL | PackageManager.INSTALL_INTERNAL,
1523               false,
1524               true, PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION,
1525               PackageInfo.INSTALL_LOCATION_AUTO);
1526   }
1527
1528   /*
1529    * Install an app with both internal and external flags set. should fail
1530    */
1531   public void testFlagIF() {
1532       sampleInstallFromRawResource(PackageManager.INSTALL_FORWARD_LOCK |
1533               PackageManager.INSTALL_INTERNAL, true);
1534   }
1535   /*
1536    * Install an app with both internal and external flags set. should fail
1537    */
1538   public void testFlagEF() {
1539       installFromRawResource("install.apk", R.raw.install,
1540               PackageManager.INSTALL_FORWARD_LOCK | PackageManager.INSTALL_EXTERNAL,
1541               false,
1542               true, PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION,
1543               PackageInfo.INSTALL_LOCATION_AUTO);
1544   }
1545   /*
1546    * Install an app with both internal and external flags set. should fail
1547    */
1548   public void testFlagIEF() {
1549       installFromRawResource("install.apk", R.raw.install,
1550               PackageManager.INSTALL_FORWARD_LOCK | PackageManager.INSTALL_INTERNAL |
1551               PackageManager.INSTALL_EXTERNAL,
1552               false,
1553               true, PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION,
1554               PackageInfo.INSTALL_LOCATION_AUTO);
1555   }
1556   /*
1557    * Install an app with both internal and manifest option set.
1558    * should install on internal.
1559    */
1560   public void testFlagIManifestI() {
1561       installFromRawResource("install.apk", R.raw.install_loc_internal,
1562               PackageManager.INSTALL_INTERNAL,
1563               true,
1564               false, -1,
1565               PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
1566   }
1567   /*
1568    * Install an app with both internal and manifest preference for
1569    * preferExternal. Should install on internal.
1570    */
1571   public void testFlagIManifestE() {
1572       installFromRawResource("install.apk", R.raw.install_loc_sdcard,
1573               PackageManager.INSTALL_INTERNAL,
1574               true,
1575               false, -1,
1576               PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
1577   }
1578   /*
1579    * Install an app with both internal and manifest preference for
1580    * auto. should install internal.
1581    */
1582   public void testFlagIManifestA() {
1583       installFromRawResource("install.apk", R.raw.install_loc_auto,
1584               PackageManager.INSTALL_INTERNAL,
1585               true,
1586               false, -1,
1587               PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
1588   }
1589   /*
1590    * Install an app with both external and manifest option set.
1591    * should install externally.
1592    */
1593   public void testFlagEManifestI() {
1594       installFromRawResource("install.apk", R.raw.install_loc_internal,
1595               PackageManager.INSTALL_EXTERNAL,
1596               true,
1597               false, -1,
1598               PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1599   }
1600   /*
1601    * Install an app with both external and manifest preference for
1602    * preferExternal. Should install externally.
1603    */
1604   public void testFlagEManifestE() {
1605       installFromRawResource("install.apk", R.raw.install_loc_sdcard,
1606               PackageManager.INSTALL_EXTERNAL,
1607               true,
1608               false, -1,
1609               PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1610   }
1611   /*
1612    * Install an app with both external and manifest preference for
1613    * auto. should install on external media.
1614    */
1615   public void testFlagEManifestA() {
1616       installFromRawResource("install.apk", R.raw.install_loc_auto,
1617               PackageManager.INSTALL_EXTERNAL,
1618               true,
1619               false, -1,
1620               PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1621   }
1622   /*
1623    * Install an app with fwd locked flag set and install location set to
1624    * internal. should install internally.
1625    */
1626   public void testFlagFManifestI() {
1627       installFromRawResource("install.apk", R.raw.install_loc_internal,
1628               PackageManager.INSTALL_EXTERNAL,
1629               true,
1630               false, -1,
1631               PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1632   }
1633   /*
1634    * Install an app with fwd locked flag set and install location set to
1635    * preferExternal. should install internally.
1636    */
1637   public void testFlagFManifestE() {
1638       installFromRawResource("install.apk", R.raw.install_loc_sdcard,
1639               PackageManager.INSTALL_EXTERNAL,
1640               true,
1641               false, -1,
1642               PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1643   }
1644   /*
1645    * Install an app with fwd locked flag set and install location set to
1646    * auto. should install internally.
1647    */
1648   public void testFlagFManifestA() {
1649       installFromRawResource("install.apk", R.raw.install_loc_auto,
1650               PackageManager.INSTALL_EXTERNAL,
1651               true,
1652               false, -1,
1653               PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1654   }
1655   /* The following test functions verify install location for existing apps.
1656    * ie existing app can be installed internally or externally. If install
1657    * flag is explicitly set it should override current location. If manifest location
1658    * is set, that should over ride current location too. if not the existing install
1659    * location should be honoured.
1660    * testFlagI/E/F/ExistingI/E -
1661    */
1662   public void testFlagIExistingI() {
1663       int iFlags = PackageManager.INSTALL_INTERNAL;
1664       int rFlags = PackageManager.INSTALL_INTERNAL | PackageManager.INSTALL_REPLACE_EXISTING;
1665       // First install.
1666       installFromRawResource("install.apk", R.raw.install,
1667               iFlags,
1668               false,
1669               false, -1,
1670               -1);
1671       // Replace now
1672       installFromRawResource("install.apk", R.raw.install,
1673               rFlags,
1674               true,
1675               false, -1,
1676               -1);
1677   }
1678   public void testFlagIExistingE() {
1679       int iFlags = PackageManager.INSTALL_EXTERNAL;
1680       int rFlags = PackageManager.INSTALL_INTERNAL | PackageManager.INSTALL_REPLACE_EXISTING;
1681       // First install.
1682       installFromRawResource("install.apk", R.raw.install,
1683               iFlags,
1684               false,
1685               false, -1,
1686               -1);
1687       // Replace now
1688       installFromRawResource("install.apk", R.raw.install,
1689               rFlags,
1690               true,
1691               false, -1,
1692               -1);
1693   }
1694   public void testFlagEExistingI() {
1695       int iFlags = PackageManager.INSTALL_INTERNAL;
1696       int rFlags = PackageManager.INSTALL_EXTERNAL | PackageManager.INSTALL_REPLACE_EXISTING;
1697       // First install.
1698       installFromRawResource("install.apk", R.raw.install,
1699               iFlags,
1700               false,
1701               false, -1,
1702               -1);
1703       // Replace now
1704       installFromRawResource("install.apk", R.raw.install,
1705               rFlags,
1706               true,
1707               false, -1,
1708               -1);
1709   }
1710   public void testFlagEExistingE() {
1711       int iFlags = PackageManager.INSTALL_EXTERNAL;
1712       int rFlags = PackageManager.INSTALL_EXTERNAL | PackageManager.INSTALL_REPLACE_EXISTING;
1713       // First install.
1714       installFromRawResource("install.apk", R.raw.install,
1715               iFlags,
1716               false,
1717               false, -1,
1718               -1);
1719       // Replace now
1720       installFromRawResource("install.apk", R.raw.install,
1721               rFlags,
1722               true,
1723               false, -1,
1724               -1);
1725   }
1726   public void testFlagFExistingI() {
1727       int iFlags = PackageManager.INSTALL_INTERNAL;
1728       int rFlags = PackageManager.INSTALL_FORWARD_LOCK | PackageManager.INSTALL_REPLACE_EXISTING;
1729       // First install.
1730       installFromRawResource("install.apk", R.raw.install,
1731               iFlags,
1732               false,
1733               false, -1,
1734               -1);
1735       // Replace now
1736       installFromRawResource("install.apk", R.raw.install,
1737               rFlags,
1738               true,
1739               false, -1,
1740               -1);
1741   }
1742   public void testFlagFExistingE() {
1743       int iFlags = PackageManager.INSTALL_EXTERNAL;
1744       int rFlags = PackageManager.INSTALL_FORWARD_LOCK | PackageManager.INSTALL_REPLACE_EXISTING;
1745       // First install.
1746       installFromRawResource("install.apk", R.raw.install,
1747               iFlags,
1748               false,
1749               false, -1,
1750               -1);
1751       // Replace now
1752       installFromRawResource("install.apk", R.raw.install,
1753               rFlags,
1754               true,
1755               false, -1,
1756               -1);
1757   }
1758   /*
1759    * The following set of tests verify the installation of apps with
1760    * install location attribute set to internalOnly, preferExternal and auto.
1761    * The manifest option should dictate the install location.
1762    * public void testManifestI/E/A
1763    * TODO out of memory fall back behaviour.
1764    */
1765   public void testManifestI() {
1766       installFromRawResource("install.apk", R.raw.install_loc_internal,
1767               0,
1768               true,
1769               false, -1,
1770               PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
1771   }
1772   public void testManifestE() {
1773       installFromRawResource("install.apk", R.raw.install_loc_sdcard,
1774               0,
1775               true,
1776               false, -1,
1777               PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1778   }
1779   public void testManifestA() {
1780       installFromRawResource("install.apk", R.raw.install_loc_auto,
1781               0,
1782               true,
1783               false, -1,
1784               PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
1785   }
1786   /*
1787    * The following set of tests verify the installation of apps
1788    * with install location attribute set to internalOnly, preferExternal and auto
1789    * for already existing apps. The manifest option should take precedence.
1790    * TODO add out of memory fall back behaviour.
1791    * testManifestI/E/AExistingI/E
1792    */
1793   public void testManifestIExistingI() {
1794       int iFlags = PackageManager.INSTALL_INTERNAL;
1795       int rFlags = PackageManager.INSTALL_REPLACE_EXISTING;
1796       // First install.
1797       installFromRawResource("install.apk", R.raw.install,
1798               iFlags,
1799               false,
1800               false, -1,
1801               -1);
1802       // Replace now
1803       installFromRawResource("install.apk", R.raw.install_loc_internal,
1804               rFlags,
1805               true,
1806               false, -1,
1807               PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
1808   }
1809   public void testManifestIExistingE() {
1810       int iFlags = PackageManager.INSTALL_EXTERNAL;
1811       int rFlags = PackageManager.INSTALL_REPLACE_EXISTING;
1812       // First install.
1813       installFromRawResource("install.apk", R.raw.install,
1814               iFlags,
1815               false,
1816               false, -1,
1817               -1);
1818       // Replace now
1819       installFromRawResource("install.apk", R.raw.install_loc_internal,
1820               rFlags,
1821               true,
1822               false, -1,
1823               PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
1824   }
1825   public void testManifestEExistingI() {
1826       int iFlags = PackageManager.INSTALL_INTERNAL;
1827       int rFlags = PackageManager.INSTALL_REPLACE_EXISTING;
1828       // First install.
1829       installFromRawResource("install.apk", R.raw.install,
1830               iFlags,
1831               false,
1832               false, -1,
1833               -1);
1834       // Replace now
1835       installFromRawResource("install.apk", R.raw.install_loc_sdcard,
1836               rFlags,
1837               true,
1838               false, -1,
1839               PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1840   }
1841   public void testManifestEExistingE() {
1842       int iFlags = PackageManager.INSTALL_EXTERNAL;
1843       int rFlags = PackageManager.INSTALL_REPLACE_EXISTING;
1844       // First install.
1845       installFromRawResource("install.apk", R.raw.install,
1846               iFlags,
1847               false,
1848               false, -1,
1849               -1);
1850       // Replace now
1851       installFromRawResource("install.apk", R.raw.install_loc_sdcard,
1852               rFlags,
1853               true,
1854               false, -1,
1855               PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1856   }
1857   public void testManifestAExistingI() {
1858       int iFlags = PackageManager.INSTALL_INTERNAL;
1859       int rFlags = PackageManager.INSTALL_REPLACE_EXISTING;
1860       // First install.
1861       installFromRawResource("install.apk", R.raw.install,
1862               iFlags,
1863               false,
1864               false, -1,
1865               -1);
1866       // Replace now
1867       installFromRawResource("install.apk", R.raw.install_loc_auto,
1868               rFlags,
1869               true,
1870               false, -1,
1871               PackageInfo.INSTALL_LOCATION_AUTO);
1872   }
1873   public void testManifestAExistingE() {
1874       int iFlags = PackageManager.INSTALL_EXTERNAL;
1875       int rFlags = PackageManager.INSTALL_REPLACE_EXISTING;
1876       // First install.
1877       installFromRawResource("install.apk", R.raw.install,
1878               iFlags,
1879               false,
1880               false, -1,
1881               -1);
1882       // Replace now
1883       installFromRawResource("install.apk", R.raw.install_loc_auto,
1884               rFlags,
1885               true,
1886               false, -1,
1887               PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1888   }
1889   /*
1890    * The following set of tests check install location for existing
1891    * application based on user setting.
1892    */
1893   private int getExpectedInstallLocation(int userSetting) {
1894       int iloc = PackageInfo.INSTALL_LOCATION_UNSPECIFIED;
1895       boolean enable = getUserSettingSetInstallLocation();
1896       if (enable) {
1897           if (userSetting == PackageHelper.APP_INSTALL_AUTO) {
1898               iloc = PackageInfo.INSTALL_LOCATION_AUTO;
1899           } else if (userSetting == PackageHelper.APP_INSTALL_EXTERNAL) {
1900               iloc = PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL;
1901           } else if (userSetting == PackageHelper.APP_INSTALL_INTERNAL) {
1902               iloc = PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY;
1903           }
1904       }
1905       return iloc;
1906   }
1907   private void setExistingXUserX(int userSetting, int iFlags, int iloc) {
1908       int rFlags = PackageManager.INSTALL_REPLACE_EXISTING;
1909       // First install.
1910       installFromRawResource("install.apk", R.raw.install,
1911               iFlags,
1912               false,
1913               false, -1,
1914               PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
1915       int origSetting = getDefaultInstallLoc();
1916       try {
1917           // Set user setting
1918           setInstallLoc(userSetting);
1919           // Replace now
1920           installFromRawResource("install.apk", R.raw.install,
1921                   rFlags,
1922                   true,
1923                   false, -1,
1924                   iloc);
1925       } finally {
1926           setInstallLoc(origSetting);
1927       }
1928   }
1929   public void testExistingIUserI() {
1930       int userSetting = PackageHelper.APP_INSTALL_INTERNAL;
1931       int iFlags = PackageManager.INSTALL_INTERNAL;
1932       setExistingXUserX(userSetting, iFlags, PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
1933   }
1934   public void testExistingIUserE() {
1935       int userSetting = PackageHelper.APP_INSTALL_EXTERNAL;
1936       int iFlags = PackageManager.INSTALL_INTERNAL;
1937       setExistingXUserX(userSetting, iFlags, PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
1938   }
1939   public void testExistingIUserA() {
1940       int userSetting = PackageHelper.APP_INSTALL_AUTO;
1941       int iFlags = PackageManager.INSTALL_INTERNAL;
1942       setExistingXUserX(userSetting, iFlags, PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
1943   }
1944   public void testExistingEUserI() {
1945       int userSetting = PackageHelper.APP_INSTALL_INTERNAL;
1946       int iFlags = PackageManager.INSTALL_EXTERNAL;
1947       setExistingXUserX(userSetting, iFlags, PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1948   }
1949   public void testExistingEUserE() {
1950       int userSetting = PackageHelper.APP_INSTALL_EXTERNAL;
1951       int iFlags = PackageManager.INSTALL_EXTERNAL;
1952       setExistingXUserX(userSetting, iFlags, PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1953   }
1954   public void testExistingEUserA() {
1955       int userSetting = PackageHelper.APP_INSTALL_AUTO;
1956       int iFlags = PackageManager.INSTALL_EXTERNAL;
1957       setExistingXUserX(userSetting, iFlags, PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL);
1958   }
1959   /*
1960    * The following set of tests verify that the user setting defines
1961    * the install location.
1962    *
1963    */
1964   private boolean getUserSettingSetInstallLocation() {
1965       try {
1966           return Settings.System.getInt(mContext.getContentResolver(), Settings.Secure.SET_INSTALL_LOCATION) != 0;
1967
1968       } catch (SettingNotFoundException e1) {
1969       }
1970       return false;
1971   }
1972
1973   private void setUserSettingSetInstallLocation(boolean value) {
1974       Settings.System.putInt(mContext.getContentResolver(),
1975               Settings.Secure.SET_INSTALL_LOCATION, value ? 1 : 0);
1976   }
1977   private void setUserX(boolean enable, int userSetting, int iloc) {
1978       boolean origUserSetting = getUserSettingSetInstallLocation();
1979       int origSetting = getDefaultInstallLoc();
1980       try {
1981           setUserSettingSetInstallLocation(enable);
1982           // Set user setting
1983           setInstallLoc(userSetting);
1984           // Replace now
1985           installFromRawResource("install.apk", R.raw.install,
1986                   0,
1987                   true,
1988                   false, -1,
1989                   iloc);
1990       } finally {
1991           // Restore original setting
1992           setUserSettingSetInstallLocation(origUserSetting);
1993           setInstallLoc(origSetting);
1994       }
1995   }
1996   public void testUserI() {
1997       int userSetting = PackageHelper.APP_INSTALL_INTERNAL;
1998       int iloc = getExpectedInstallLocation(userSetting);
1999       setUserX(true, userSetting, iloc);
2000   }
2001   public void testUserE() {
2002       int userSetting = PackageHelper.APP_INSTALL_EXTERNAL;
2003       int iloc = getExpectedInstallLocation(userSetting);
2004       setUserX(true, userSetting, iloc);
2005   }
2006   public void testUserA() {
2007       int userSetting = PackageHelper.APP_INSTALL_AUTO;
2008       int iloc = getExpectedInstallLocation(userSetting);
2009       setUserX(true, userSetting, iloc);
2010   }
2011   /*
2012    * The following set of tests turn on/off the basic
2013    * user setting for turning on install location.
2014    */
2015   public void testUserPrefOffUserI() {
2016       int userSetting = PackageHelper.APP_INSTALL_INTERNAL;
2017       int iloc = PackageInfo.INSTALL_LOCATION_UNSPECIFIED;
2018       setUserX(false, userSetting, iloc);
2019   }
2020   public void testUserPrefOffUserE() {
2021       int userSetting = PackageHelper.APP_INSTALL_EXTERNAL;
2022       int iloc = PackageInfo.INSTALL_LOCATION_UNSPECIFIED;
2023       setUserX(false, userSetting, iloc);
2024   }
2025   public void testUserPrefOffA() {
2026       int userSetting = PackageHelper.APP_INSTALL_AUTO;
2027       int iloc = PackageInfo.INSTALL_LOCATION_UNSPECIFIED;
2028       setUserX(false, userSetting, iloc);
2029   }
2030
2031    static final String BASE_PERMISSIONS_DEFINED[] = new String[] {
2032        PERM_PACKAGE, "com.android.unit_tests.install_decl_perm",
2033        PERM_DEFINED,
2034        "com.android.frameworks.coretests.NORMAL",
2035        "com.android.frameworks.coretests.DANGEROUS",
2036        "com.android.frameworks.coretests.SIGNATURE",
2037    };
2038
2039    static final String BASE_PERMISSIONS_UNDEFINED[] = new String[] {
2040        PERM_PACKAGE, "com.android.frameworks.coretests.install_decl_perm",
2041        PERM_UNDEFINED,
2042        "com.android.frameworks.coretests.NORMAL",
2043        "com.android.frameworks.coretests.DANGEROUS",
2044        "com.android.frameworks.coretests.SIGNATURE",
2045    };
2046
2047    static final String BASE_PERMISSIONS_USED[] = new String[] {
2048        PERM_PACKAGE, "com.android.frameworks.coretests.install_use_perm_good",
2049        PERM_USED,
2050        "com.android.frameworks.coretests.NORMAL",
2051        "com.android.frameworks.coretests.DANGEROUS",
2052        "com.android.frameworks.coretests.SIGNATURE",
2053    };
2054
2055    static final String BASE_PERMISSIONS_NOTUSED[] = new String[] {
2056        PERM_PACKAGE, "com.android.frameworks.coretests.install_use_perm_good",
2057        PERM_NOTUSED,
2058        "com.android.frameworks.coretests.NORMAL",
2059        "com.android.frameworks.coretests.DANGEROUS",
2060        "com.android.frameworks.coretests.SIGNATURE",
2061    };
2062
2063    static final String BASE_PERMISSIONS_SIGUSED[] = new String[] {
2064        PERM_PACKAGE, "com.android.frameworks.coretests.install_use_perm_good",
2065        PERM_USED,
2066        "com.android.frameworks.coretests.SIGNATURE",
2067        PERM_NOTUSED,
2068        "com.android.frameworks.coretests.NORMAL",
2069        "com.android.frameworks.coretests.DANGEROUS",
2070    };
2071
2072    /*
2073     * Ensure that permissions are properly declared.
2074     */
2075    public void testInstallDeclaresPermissions() {
2076        InstallParams ip = null;
2077        InstallParams ip2 = null;
2078        try {
2079            // **: Upon installing a package, are its declared permissions published?
2080
2081            int iFlags = PackageManager.INSTALL_INTERNAL;
2082            int iApk = R.raw.install_decl_perm;
2083            ip = installFromRawResource("install.apk", iApk,
2084                    iFlags, false,
2085                    false, -1, PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
2086            assertInstall(ip.pkg, iFlags, ip.pkg.installLocation);
2087            assertPermissions(BASE_PERMISSIONS_DEFINED);
2088
2089            // **: Upon installing package, are its permissions granted?
2090
2091            int i2Flags = PackageManager.INSTALL_INTERNAL;
2092            int i2Apk = R.raw.install_use_perm_good;
2093            ip2 = installFromRawResource("install2.apk", i2Apk,
2094                    i2Flags, false,
2095                    false, -1, PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
2096            assertInstall(ip2.pkg, i2Flags, ip2.pkg.installLocation);
2097            assertPermissions(BASE_PERMISSIONS_USED);
2098
2099            // **: Upon removing but not deleting, are permissions retained?
2100
2101            GenericReceiver receiver = new DeleteReceiver(ip.pkg.packageName);
2102
2103            try {
2104                invokeDeletePackage(ip.pkg.packageName, PackageManager.DONT_DELETE_DATA, receiver);
2105            } catch (Exception e) {
2106                failStr(e);
2107            }
2108            assertPermissions(BASE_PERMISSIONS_DEFINED);
2109            assertPermissions(BASE_PERMISSIONS_USED);
2110
2111            // **: Upon re-installing, are permissions retained?
2112
2113            ip = installFromRawResource("install.apk", iApk,
2114                    iFlags | PackageManager.INSTALL_REPLACE_EXISTING, false,
2115                    false, -1, PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
2116            assertInstall(ip.pkg, iFlags, ip.pkg.installLocation);
2117            assertPermissions(BASE_PERMISSIONS_DEFINED);
2118            assertPermissions(BASE_PERMISSIONS_USED);
2119
2120            // **: Upon deleting package, are all permissions removed?
2121
2122            try {
2123                invokeDeletePackage(ip.pkg.packageName, 0, receiver);
2124                ip = null;
2125            } catch (Exception e) {
2126                failStr(e);
2127            }
2128            assertPermissions(BASE_PERMISSIONS_UNDEFINED);
2129            assertPermissions(BASE_PERMISSIONS_NOTUSED);
2130
2131            // **: Delete package using permissions; nothing to check here.
2132
2133            GenericReceiver receiver2 = new DeleteReceiver(ip2.pkg.packageName);
2134            try {
2135                invokeDeletePackage(ip2.pkg.packageName, 0, receiver);
2136                ip2 = null;
2137            } catch (Exception e) {
2138                failStr(e);
2139            }
2140
2141            // **: Re-install package using permissions; no permissions can be granted.
2142
2143            ip2 = installFromRawResource("install2.apk", i2Apk,
2144                    i2Flags, false,
2145                    false, -1, PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
2146            assertInstall(ip2.pkg, i2Flags, ip2.pkg.installLocation);
2147            assertPermissions(BASE_PERMISSIONS_NOTUSED);
2148
2149            // **: Upon installing declaring package, are sig permissions granted
2150            // to other apps (but not other perms)?
2151
2152            ip = installFromRawResource("install.apk", iApk,
2153                    iFlags, false,
2154                    false, -1, PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
2155            assertInstall(ip.pkg, iFlags, ip.pkg.installLocation);
2156            assertPermissions(BASE_PERMISSIONS_DEFINED);
2157            assertPermissions(BASE_PERMISSIONS_SIGUSED);
2158
2159            // **: Re-install package using permissions; are all permissions granted?
2160
2161            ip2 = installFromRawResource("install2.apk", i2Apk,
2162                    i2Flags | PackageManager.INSTALL_REPLACE_EXISTING, false,
2163                    false, -1, PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
2164            assertInstall(ip2.pkg, i2Flags, ip2.pkg.installLocation);
2165            assertPermissions(BASE_PERMISSIONS_NOTUSED);
2166
2167            // **: Upon deleting package, are all permissions removed?
2168
2169            try {
2170                invokeDeletePackage(ip.pkg.packageName, 0, receiver);
2171                ip = null;
2172            } catch (Exception e) {
2173                failStr(e);
2174            }
2175            assertPermissions(BASE_PERMISSIONS_UNDEFINED);
2176            assertPermissions(BASE_PERMISSIONS_NOTUSED);
2177
2178            // **: Delete package using permissions; nothing to check here.
2179
2180            try {
2181                invokeDeletePackage(ip2.pkg.packageName, 0, receiver);
2182                ip2 = null;
2183            } catch (Exception e) {
2184                failStr(e);
2185            }
2186
2187        } finally {
2188            if (ip2 != null) {
2189                cleanUpInstall(ip2);
2190            }
2191            if (ip != null) {
2192                cleanUpInstall(ip);
2193            }
2194        }
2195    }
2196
2197    /*
2198     * Ensure that permissions are properly declared.
2199     */
2200    public void testInstallOnSdPermissionsUnmount() {
2201        InstallParams ip = null;
2202        boolean origMediaState = getMediaState();
2203        try {
2204            // **: Upon installing a package, are its declared permissions published?
2205            int iFlags = PackageManager.INSTALL_INTERNAL;
2206            int iApk = R.raw.install_decl_perm;
2207            ip = installFromRawResource("install.apk", iApk,
2208                    iFlags, false,
2209                    false, -1, PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
2210            assertInstall(ip.pkg, iFlags, ip.pkg.installLocation);
2211            assertPermissions(BASE_PERMISSIONS_DEFINED);
2212            // Unmount media here
2213            assertTrue(unmountMedia());
2214            // Mount media again
2215            mountMedia();
2216            //Check permissions now
2217            assertPermissions(BASE_PERMISSIONS_DEFINED);
2218        } finally {
2219            if (ip != null) {
2220                cleanUpInstall(ip);
2221            }
2222        }
2223    }
2224
2225    /* This test creates a stale container via MountService and then installs
2226     * a package and verifies that the stale container is cleaned up and install
2227     * is successful.
2228     * Please note that this test is very closely tied to the framework's
2229     * naming convention for secure containers.
2230     */
2231    public void testInstallSdcardStaleContainer() {
2232        boolean origMediaState = getMediaState();
2233        try {
2234            String outFileName = "install.apk";
2235            int rawResId = R.raw.install;
2236            PackageManager pm = mContext.getPackageManager();
2237            File filesDir = mContext.getFilesDir();
2238            File outFile = new File(filesDir, outFileName);
2239            Uri packageURI = getInstallablePackage(rawResId, outFile);
2240            PackageParser.Package pkg = parsePackage(packageURI);
2241            assertNotNull(pkg);
2242            // Install an app on sdcard.
2243            installFromRawResource(outFileName, rawResId,
2244                    PackageManager.INSTALL_EXTERNAL, false,
2245                    false, -1, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2246            // Unmount sdcard
2247            unmountMedia();
2248            // Delete the app on sdcard to leave a stale container on sdcard.
2249            GenericReceiver receiver = new DeleteReceiver(pkg.packageName);
2250            assertTrue(invokeDeletePackage(pkg.packageName, 0, receiver));
2251            mountMedia();
2252            // Reinstall the app and make sure it gets installed.
2253            installFromRawResource(outFileName, rawResId,
2254                    PackageManager.INSTALL_EXTERNAL, true,
2255                    false, -1, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2256        } catch (Exception e) {
2257            failStr(e.getMessage());
2258        } finally {
2259            if (origMediaState) {
2260                mountMedia();
2261            } else {
2262                unmountMedia();
2263            }
2264
2265        }
2266    }
2267    /*
2268     * The following series of tests are related to upgrading apps with
2269     * different certificates.
2270     */
2271    private int APP1_UNSIGNED = R.raw.install_app1_unsigned;
2272    private int APP1_CERT1 = R.raw.install_app1_cert1;
2273    private int APP1_CERT2 = R.raw.install_app1_cert2;
2274    private int APP1_CERT1_CERT2 = R.raw.install_app1_cert1_cert2;
2275    private int APP1_CERT3_CERT4 = R.raw.install_app1_cert3_cert4;
2276    private int APP1_CERT3 = R.raw.install_app1_cert3;
2277    private int APP2_UNSIGNED = R.raw.install_app2_unsigned;
2278    private int APP2_CERT1 = R.raw.install_app2_cert1;
2279    private int APP2_CERT2 = R.raw.install_app2_cert2;
2280    private int APP2_CERT1_CERT2 = R.raw.install_app2_cert1_cert2;
2281    private int APP2_CERT3 = R.raw.install_app2_cert3;
2282
2283    private InstallParams replaceCerts(int apk1, int apk2, boolean cleanUp, boolean fail, int retCode) {
2284        int rFlags = PackageManager.INSTALL_REPLACE_EXISTING;
2285        String apk1Name = "install1.apk";
2286        String apk2Name = "install2.apk";
2287        PackageParser.Package pkg1 = getParsedPackage(apk1Name, apk1);
2288        try {
2289            InstallParams ip = installFromRawResource(apk1Name, apk1, 0, false,
2290                    false, -1, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2291            installFromRawResource(apk2Name, apk2, rFlags, false,
2292                    fail, retCode, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2293            return ip;
2294        } catch (Exception e) {
2295            failStr(e.getMessage());
2296        } finally {
2297            if (cleanUp) {
2298                cleanUpInstall(pkg1.packageName);
2299            }
2300        }
2301        return null;
2302    }
2303    /*
2304     * Test that an app signed with two certificates can be upgraded by the
2305     * same app signed with two certificates.
2306     */
2307    public void testReplaceMatchAllCerts() {
2308        replaceCerts(APP1_CERT1_CERT2, APP1_CERT1_CERT2, true, false, -1);
2309    }
2310
2311    /*
2312     * Test that an app signed with two certificates cannot be upgraded
2313     * by an app signed with a different certificate.
2314     */
2315    public void testReplaceMatchNoCerts1() {
2316        replaceCerts(APP1_CERT1_CERT2, APP1_CERT3, true, true,
2317                PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES);
2318    }
2319    /*
2320     * Test that an app signed with two certificates cannot be upgraded
2321     * by an app signed with a different certificate.
2322     */
2323    public void testReplaceMatchNoCerts2() {
2324        replaceCerts(APP1_CERT1_CERT2, APP1_CERT3_CERT4, true, true,
2325                PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES);
2326    }
2327    /*
2328     * Test that an app signed with two certificates cannot be upgraded by
2329     * an app signed with a subset of initial certificates.
2330     */
2331    public void testReplaceMatchSomeCerts1() {
2332        replaceCerts(APP1_CERT1_CERT2, APP1_CERT1, true, true,
2333                PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES);
2334    }
2335    /*
2336     * Test that an app signed with two certificates cannot be upgraded by
2337     * an app signed with the last certificate.
2338     */
2339    public void testReplaceMatchSomeCerts2() {
2340        replaceCerts(APP1_CERT1_CERT2, APP1_CERT2, true, true,
2341                PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES);
2342    }
2343    /*
2344     * Test that an app signed with a certificate can be upgraded by app
2345     * signed with a superset of certificates.
2346     */
2347    public void testReplaceMatchMoreCerts() {
2348        replaceCerts(APP1_CERT1, APP1_CERT1_CERT2, true, true,
2349                PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES);
2350    }
2351    /*
2352     * Test that an app signed with a certificate can be upgraded by app
2353     * signed with a superset of certificates. Then verify that the an app
2354     * signed with the original set of certs cannot upgrade the new one.
2355     */
2356    public void testReplaceMatchMoreCertsReplaceSomeCerts() {
2357        InstallParams ip = replaceCerts(APP1_CERT1, APP1_CERT1_CERT2, false, true,
2358                PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES);
2359        try {
2360            int rFlags = PackageManager.INSTALL_REPLACE_EXISTING;
2361            installFromRawResource("install.apk", APP1_CERT1, rFlags, false,
2362                    false, -1,
2363                    PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2364        } catch (Exception e) {
2365            failStr(e.getMessage());
2366        } finally {
2367            if (ip != null) {
2368                cleanUpInstall(ip);
2369            }
2370        }
2371    }
2372    /*
2373     * The following tests are related to testing the checkSignatures
2374     * api.
2375     */
2376    private void checkSignatures(int apk1, int apk2, int expMatchResult) {
2377        checkSharedSignatures(apk1, apk2, true, false, -1, expMatchResult);
2378    }
2379    public void testCheckSignaturesAllMatch() {
2380        int apk1 = APP1_CERT1_CERT2;
2381        int apk2 = APP2_CERT1_CERT2;
2382        checkSignatures(apk1, apk2, PackageManager.SIGNATURE_MATCH);
2383    }
2384    public void testCheckSignaturesNoMatch() {
2385        int apk1 = APP1_CERT1;
2386        int apk2 = APP2_CERT2;
2387        checkSignatures(apk1, apk2, PackageManager.SIGNATURE_NO_MATCH);
2388    }
2389    public void testCheckSignaturesSomeMatch1() {
2390        int apk1 = APP1_CERT1_CERT2;
2391        int apk2 = APP2_CERT1;
2392        checkSignatures(apk1, apk2, PackageManager.SIGNATURE_NO_MATCH);
2393    }
2394    public void testCheckSignaturesSomeMatch2() {
2395        int apk1 = APP1_CERT1_CERT2;
2396        int apk2 = APP2_CERT2;
2397        checkSignatures(apk1, apk2, PackageManager.SIGNATURE_NO_MATCH);
2398    }
2399    public void testCheckSignaturesMoreMatch() {
2400        int apk1 = APP1_CERT1;
2401        int apk2 = APP2_CERT1_CERT2;
2402        checkSignatures(apk1, apk2, PackageManager.SIGNATURE_NO_MATCH);
2403    }
2404    public void testCheckSignaturesUnknown() {
2405        int apk1 = APP1_CERT1_CERT2;
2406        int apk2 = APP2_CERT1_CERT2;
2407        String apk1Name = "install1.apk";
2408        String apk2Name = "install2.apk";
2409        InstallParams ip1 = null;
2410
2411        try {
2412            ip1 = installFromRawResource(apk1Name, apk1, 0, false,
2413                    false, -1, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2414            PackageManager pm = mContext.getPackageManager();
2415            // Delete app2
2416            File filesDir = mContext.getFilesDir();
2417            File outFile = new File(filesDir, apk2Name);
2418            int rawResId = apk2;
2419            Uri packageURI = getInstallablePackage(rawResId, outFile);
2420            PackageParser.Package pkg = parsePackage(packageURI);
2421            getPm().deletePackage(pkg.packageName, null, 0);
2422            // Check signatures now
2423            int match = mContext.getPackageManager().checkSignatures(
2424                    ip1.pkg.packageName, pkg.packageName);
2425            assertEquals(PackageManager.SIGNATURE_UNKNOWN_PACKAGE, match);
2426        } finally {
2427            if (ip1 != null) {
2428                cleanUpInstall(ip1);
2429            }
2430        }
2431    }
2432    public void testInstallNoCertificates() {
2433        int apk1 = APP1_UNSIGNED;
2434        String apk1Name = "install1.apk";
2435        InstallParams ip1 = null;
2436
2437        try {
2438            installFromRawResource(apk1Name, apk1, 0, false,
2439                    true, PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES,
2440                    PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2441        } finally {
2442        }
2443    }
2444    /* The following tests are related to apps using shared uids signed
2445     * with different certs.
2446     */
2447    private int SHARED1_UNSIGNED = R.raw.install_shared1_unsigned;
2448    private int SHARED1_CERT1 = R.raw.install_shared1_cert1;
2449    private int SHARED1_CERT2 = R.raw.install_shared1_cert2;
2450    private int SHARED1_CERT1_CERT2 = R.raw.install_shared1_cert1_cert2;
2451    private int SHARED2_UNSIGNED = R.raw.install_shared2_unsigned;
2452    private int SHARED2_CERT1 = R.raw.install_shared2_cert1;
2453    private int SHARED2_CERT2 = R.raw.install_shared2_cert2;
2454    private int SHARED2_CERT1_CERT2 = R.raw.install_shared2_cert1_cert2;
2455    private void checkSharedSignatures(int apk1, int apk2, boolean cleanUp, boolean fail, int retCode, int expMatchResult) {
2456        String apk1Name = "install1.apk";
2457        String apk2Name = "install2.apk";
2458        PackageParser.Package pkg1 = getParsedPackage(apk1Name, apk1);
2459        PackageParser.Package pkg2 = getParsedPackage(apk2Name, apk2);
2460
2461        try {
2462            // Clean up before testing first.
2463            cleanUpInstall(pkg1.packageName);
2464            cleanUpInstall(pkg2.packageName);
2465            installFromRawResource(apk1Name, apk1, 0, false,
2466                    false, -1, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2467            if (fail) {
2468                installFromRawResource(apk2Name, apk2, 0, false,
2469                        true, retCode, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2470            } else {
2471                installFromRawResource(apk2Name, apk2, 0, false,
2472                        false, -1, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2473                int match = mContext.getPackageManager().checkSignatures(
2474                        pkg1.packageName, pkg2.packageName);
2475                assertEquals(expMatchResult, match);
2476            }
2477        } finally {
2478            if (cleanUp) {
2479                cleanUpInstall(pkg1.packageName);
2480                cleanUpInstall(pkg2.packageName);
2481            }
2482        }
2483    }
2484    public void testCheckSignaturesSharedAllMatch() {
2485        int apk1 = SHARED1_CERT1_CERT2;
2486        int apk2 = SHARED2_CERT1_CERT2;
2487        boolean fail = false;
2488        int retCode = -1;
2489        int expMatchResult = PackageManager.SIGNATURE_MATCH;
2490        checkSharedSignatures(apk1, apk2, true, fail, retCode, expMatchResult);
2491    }
2492    public void testCheckSignaturesSharedNoMatch() {
2493        int apk1 = SHARED1_CERT1;
2494        int apk2 = SHARED2_CERT2;
2495        boolean fail = true;
2496        int retCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2497        int expMatchResult = -1;
2498        checkSharedSignatures(apk1, apk2, true, fail, retCode, expMatchResult);
2499    }
2500    /*
2501     * Test that an app signed with cert1 and cert2 cannot be replaced when signed with cert1 alone.
2502     */
2503    public void testCheckSignaturesSharedSomeMatch1() {
2504        int apk1 = SHARED1_CERT1_CERT2;
2505        int apk2 = SHARED2_CERT1;
2506        boolean fail = true;
2507        int retCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2508        int expMatchResult = -1;
2509        checkSharedSignatures(apk1, apk2, true, fail, retCode, expMatchResult);
2510    }
2511    /*
2512     * Test that an app signed with cert1 and cert2 cannot be replaced when signed with cert2 alone.
2513     */
2514    public void testCheckSignaturesSharedSomeMatch2() {
2515        int apk1 = SHARED1_CERT1_CERT2;
2516        int apk2 = SHARED2_CERT2;
2517        boolean fail = true;
2518        int retCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2519        int expMatchResult = -1;
2520        checkSharedSignatures(apk1, apk2, true, fail, retCode, expMatchResult);
2521    }
2522    public void testCheckSignaturesSharedUnknown() {
2523        int apk1 = SHARED1_CERT1_CERT2;
2524        int apk2 = SHARED2_CERT1_CERT2;
2525        String apk1Name = "install1.apk";
2526        String apk2Name = "install2.apk";
2527        InstallParams ip1 = null;
2528
2529        try {
2530            ip1 = installFromRawResource(apk1Name, apk1, 0, false,
2531                    false, -1, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2532            PackageManager pm = mContext.getPackageManager();
2533            // Delete app2
2534            PackageParser.Package pkg = getParsedPackage(apk2Name, apk2);
2535            getPm().deletePackage(pkg.packageName, null, 0);
2536            // Check signatures now
2537            int match = mContext.getPackageManager().checkSignatures(
2538                    ip1.pkg.packageName, pkg.packageName);
2539            assertEquals(PackageManager.SIGNATURE_UNKNOWN_PACKAGE, match);
2540        } finally {
2541            if (ip1 != null) {
2542                cleanUpInstall(ip1);
2543            }
2544        }
2545    }
2546
2547    public void testReplaceFirstSharedMatchAllCerts() {
2548        int apk1 = SHARED1_CERT1;
2549        int apk2 = SHARED2_CERT1;
2550        int rapk1 = SHARED1_CERT1;
2551        checkSignatures(apk1, apk2, PackageManager.SIGNATURE_MATCH);
2552        replaceCerts(apk1, rapk1, true, false, -1);
2553    }
2554    public void testReplaceSecondSharedMatchAllCerts() {
2555        int apk1 = SHARED1_CERT1;
2556        int apk2 = SHARED2_CERT1;
2557        int rapk2 = SHARED2_CERT1;
2558        checkSignatures(apk1, apk2, PackageManager.SIGNATURE_MATCH);
2559        replaceCerts(apk2, rapk2, true, false, -1);
2560    }
2561    public void testReplaceFirstSharedMatchSomeCerts() {
2562        int apk1 = SHARED1_CERT1_CERT2;
2563        int apk2 = SHARED2_CERT1_CERT2;
2564        int rapk1 = SHARED1_CERT1;
2565        boolean fail = true;
2566        int retCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2567        checkSharedSignatures(apk1, apk2, false, false, -1, PackageManager.SIGNATURE_MATCH);
2568        installFromRawResource("install.apk", rapk1, PackageManager.INSTALL_REPLACE_EXISTING, true,
2569                fail, retCode, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2570    }
2571    public void testReplaceSecondSharedMatchSomeCerts() {
2572        int apk1 = SHARED1_CERT1_CERT2;
2573        int apk2 = SHARED2_CERT1_CERT2;
2574        int rapk2 = SHARED2_CERT1;
2575        boolean fail = true;
2576        int retCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2577        checkSharedSignatures(apk1, apk2, false, false, -1, PackageManager.SIGNATURE_MATCH);
2578        installFromRawResource("install.apk", rapk2, PackageManager.INSTALL_REPLACE_EXISTING, true,
2579                fail, retCode, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2580    }
2581    public void testReplaceFirstSharedMatchNoCerts() {
2582        int apk1 = SHARED1_CERT1;
2583        int apk2 = SHARED2_CERT1;
2584        int rapk1 = SHARED1_CERT2;
2585        boolean fail = true;
2586        int retCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2587        checkSharedSignatures(apk1, apk2, false, false, -1, PackageManager.SIGNATURE_MATCH);
2588        installFromRawResource("install.apk", rapk1, PackageManager.INSTALL_REPLACE_EXISTING, true,
2589                fail, retCode, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2590    }
2591    public void testReplaceSecondSharedMatchNoCerts() {
2592        int apk1 = SHARED1_CERT1;
2593        int apk2 = SHARED2_CERT1;
2594        int rapk2 = SHARED2_CERT2;
2595        boolean fail = true;
2596        int retCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2597        checkSharedSignatures(apk1, apk2, false, false, -1, PackageManager.SIGNATURE_MATCH);
2598        installFromRawResource("install.apk", rapk2, PackageManager.INSTALL_REPLACE_EXISTING, true,
2599                fail, retCode, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2600    }
2601    public void testReplaceFirstSharedMatchMoreCerts() {
2602        int apk1 = SHARED1_CERT1;
2603        int apk2 = SHARED2_CERT1;
2604        int rapk1 = SHARED1_CERT1_CERT2;
2605        boolean fail = true;
2606        int retCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2607        checkSharedSignatures(apk1, apk2, false, false, -1, PackageManager.SIGNATURE_MATCH);
2608        installFromRawResource("install.apk", rapk1, PackageManager.INSTALL_REPLACE_EXISTING, true,
2609                fail, retCode, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2610    }
2611    public void testReplaceSecondSharedMatchMoreCerts() {
2612        int apk1 = SHARED1_CERT1;
2613        int apk2 = SHARED2_CERT1;
2614        int rapk2 = SHARED2_CERT1_CERT2;
2615        boolean fail = true;
2616        int retCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2617        checkSharedSignatures(apk1, apk2, false, false, -1, PackageManager.SIGNATURE_MATCH);
2618        installFromRawResource("install.apk", rapk2, PackageManager.INSTALL_REPLACE_EXISTING, true,
2619                fail, retCode, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
2620    }
2621    /*---------- Recommended install location tests ----*/
2622    /*
2623     * TODO's
2624     * check version numbers for upgrades
2625     * check permissions of installed packages
2626     * how to do tests on updated system apps?
2627     * verify updates to system apps cannot be installed on the sdcard.
2628     */
2629}
2630