blob: 001d98e4f1a34b19809695fc942207d20e727afe [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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 com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070021import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080022import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080023import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070024import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080025import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27import org.xmlpull.v1.XmlPullParser;
28import org.xmlpull.v1.XmlPullParserException;
29import org.xmlpull.v1.XmlSerializer;
30
31import android.app.ActivityManagerNative;
32import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080033import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080034import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070036import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070037import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.Intent;
39import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080041import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070042import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.ActivityInfo;
44import android.content.pm.ApplicationInfo;
45import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070046import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.IPackageDataObserver;
48import android.content.pm.IPackageDeleteObserver;
49import android.content.pm.IPackageInstallObserver;
50import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080051import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.IPackageStatsObserver;
53import android.content.pm.InstrumentationInfo;
54import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080055import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.PackageManager;
57import android.content.pm.PackageStats;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
60import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.pm.PackageParser;
62import android.content.pm.PermissionInfo;
63import android.content.pm.PermissionGroupInfo;
64import android.content.pm.ProviderInfo;
65import android.content.pm.ResolveInfo;
66import android.content.pm.ServiceInfo;
67import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
69import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080072import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070075import android.os.Looper;
76import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Parcel;
78import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
83import android.os.ParcelFileDescriptor;
84import android.os.Process;
85import android.os.ServiceManager;
86import android.os.SystemClock;
87import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070088import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.util.*;
91import android.view.Display;
92import android.view.WindowManager;
93
94import java.io.File;
95import java.io.FileDescriptor;
96import java.io.FileInputStream;
97import java.io.FileNotFoundException;
98import java.io.FileOutputStream;
99import java.io.FileReader;
100import java.io.FilenameFilter;
101import java.io.IOException;
102import java.io.InputStream;
103import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800104import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800105import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.ArrayList;
107import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700108import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.Collections;
110import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800111import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import java.util.Enumeration;
113import java.util.HashMap;
114import java.util.HashSet;
115import java.util.Iterator;
Kenny Root85387d72010-08-26 10:13:11 -0700116import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import java.util.List;
118import java.util.Map;
119import java.util.Set;
120import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800121import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import java.util.zip.ZipFile;
123import java.util.zip.ZipOutputStream;
124
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700125/**
126 * Keep track of all those .apks everywhere.
127 *
128 * This is very central to the platform's security; please run the unit
129 * tests whenever making modifications here:
130 *
131mmm frameworks/base/tests/AndroidTests
132adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
133adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
134 *
135 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136class PackageManagerService extends IPackageManager.Stub {
137 private static final String TAG = "PackageManager";
138 private static final boolean DEBUG_SETTINGS = false;
139 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800140 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800141 private static final boolean DEBUG_INSTALL = false;
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -0700142 private static final boolean DEBUG_NATIVE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
145 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400146 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 private static final int FIRST_APPLICATION_UID =
148 Process.FIRST_APPLICATION_UID;
149 private static final int MAX_APPLICATION_UIDS = 1000;
150
151 private static final boolean SHOW_INFO = false;
152
153 private static final boolean GET_CERTIFICATES = true;
154
Oscar Montemayora8529f62009-11-18 10:14:20 -0800155 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private static final int REMOVE_EVENTS =
158 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
159 private static final int ADD_EVENTS =
160 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
161
162 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800163 // Suffix used during package installation when copying/moving
164 // package apks to install directory.
165 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800167 /**
168 * Indicates the state of installation. Used by PackageManager to
169 * figure out incomplete installations. Say a package is being installed
170 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
171 * the package installation is successful or unsuccesful lin which case
172 * the PackageManager will no longer maintain state information associated
173 * with the package. If some exception(like device freeze or battery being
174 * pulled out) occurs during installation of a package, the PackageManager
175 * needs this information to clean up the previously failed installation.
176 */
177 private static final int PKG_INSTALL_INCOMPLETE = 0;
178 private static final int PKG_INSTALL_COMPLETE = 1;
179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final int SCAN_MONITOR = 1<<0;
181 static final int SCAN_NO_DEX = 1<<1;
182 static final int SCAN_FORCE_DEX = 1<<2;
183 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800184 static final int SCAN_NEW_INSTALL = 1<<4;
185 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700187 static final int REMOVE_CHATTY = 1<<16;
188
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800189 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
190 "com.android.defcontainer",
191 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700192
Kenny Root85387d72010-08-26 10:13:11 -0700193 private static final String LIB_DIR_NAME = "lib";
194
Kenny Rootc78a8072010-07-27 15:18:38 -0700195 static final String mTempContainerPrefix = "smdl2tmp";
196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
198 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700199 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Dianne Hackborn851a5412009-05-08 12:06:44 -0700201 final int mSdkVersion = Build.VERSION.SDK_INT;
202 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
203 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 final Context mContext;
206 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700207 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 final DisplayMetrics mMetrics;
209 final int mDefParseFlags;
210 final String[] mSeparateProcesses;
211
212 // This is where all application persistent data goes.
213 final File mAppDataDir;
214
Oscar Montemayora8529f62009-11-18 10:14:20 -0800215 // If Encrypted File System feature is enabled, all application persistent data
216 // should go here instead.
217 final File mSecureAppDataDir;
218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 // This is the object monitoring the framework dir.
220 final FileObserver mFrameworkInstallObserver;
221
222 // This is the object monitoring the system app dir.
223 final FileObserver mSystemInstallObserver;
224
225 // This is the object monitoring mAppInstallDir.
226 final FileObserver mAppInstallObserver;
227
228 // This is the object monitoring mDrmAppPrivateInstallDir.
229 final FileObserver mDrmAppInstallObserver;
230
231 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
232 // LOCK HELD. Can be called with mInstallLock held.
233 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 final File mFrameworkDir;
236 final File mSystemAppDir;
237 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700238 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
241 // apps.
242 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 // Lock for state used when installing and doing other long running
247 // operations. Methods that must be called with this lock held have
248 // the prefix "LI".
249 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // These are the directories in the 3rd party applications installed dir
252 // that we have currently loaded packages from. Keys are the application's
253 // installed zip file (absolute codePath), and values are Package.
254 final HashMap<String, PackageParser.Package> mAppDirs =
255 new HashMap<String, PackageParser.Package>();
256
257 // Information for the parser to write more useful error messages.
258 File mScanningPath;
259 int mLastScanError;
260
261 final int[] mOutPermissions = new int[3];
262
263 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 // Keys are String (package name), values are Package. This also serves
266 // as the lock for the global state. Methods that must be called with
267 // this lock held have the prefix "LP".
268 final HashMap<String, PackageParser.Package> mPackages =
269 new HashMap<String, PackageParser.Package>();
270
271 final Settings mSettings;
272 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273
274 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
275 int[] mGlobalGids;
276
277 // These are the built-in uid -> permission mappings that were read from the
278 // etc/permissions.xml file.
279 final SparseArray<HashSet<String>> mSystemPermissions =
280 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 // These are the built-in shared libraries that were read from the
283 // etc/permissions.xml file.
284 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800285
Dianne Hackborn49237342009-08-27 20:08:01 -0700286 // Temporary for building the final shared libraries for an .apk.
287 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800288
Dianne Hackborn49237342009-08-27 20:08:01 -0700289 // These are the features this devices supports that were read from the
290 // etc/permissions.xml file.
291 final HashMap<String, FeatureInfo> mAvailableFeatures =
292 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 // All available activities, for your resolving pleasure.
295 final ActivityIntentResolver mActivities =
296 new ActivityIntentResolver();
297
298 // All available receivers, for your resolving pleasure.
299 final ActivityIntentResolver mReceivers =
300 new ActivityIntentResolver();
301
302 // All available services, for your resolving pleasure.
303 final ServiceIntentResolver mServices = new ServiceIntentResolver();
304
305 // Keys are String (provider class name), values are Provider.
306 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
307 new HashMap<ComponentName, PackageParser.Provider>();
308
309 // Mapping from provider base names (first directory in content URI codePath)
310 // to the provider information.
311 final HashMap<String, PackageParser.Provider> mProviders =
312 new HashMap<String, PackageParser.Provider>();
313
314 // Mapping from instrumentation class names to info about them.
315 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
316 new HashMap<ComponentName, PackageParser.Instrumentation>();
317
318 // Mapping from permission names to info about them.
319 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
320 new HashMap<String, PackageParser.PermissionGroup>();
321
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800322 // Packages whose data we have transfered into another package, thus
323 // should no longer exist.
324 final HashSet<String> mTransferedPackages = new HashSet<String>();
325
Dianne Hackborn854060af2009-07-09 18:14:31 -0700326 // Broadcast actions that are only available to the system.
327 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 boolean mSystemReady;
330 boolean mSafeMode;
331 boolean mHasSystemUidErrors;
332
333 ApplicationInfo mAndroidApplication;
334 final ActivityInfo mResolveActivity = new ActivityInfo();
335 final ResolveInfo mResolveInfo = new ResolveInfo();
336 ComponentName mResolveComponentName;
337 PackageParser.Package mPlatformPackage;
338
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700339 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800340 final HashMap<String, ArrayList<String>> mPendingBroadcasts
341 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800342 // Service Connection to remote media container service to copy
343 // package uri's from external media onto secure containers
344 // or internal storage.
345 private IMediaContainerService mContainerService = null;
346
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700347 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800348 static final int MCS_BOUND = 3;
349 static final int END_COPY = 4;
350 static final int INIT_COPY = 5;
351 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800352 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800353 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800354 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800355 static final int MCS_RECONNECT = 10;
356 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700357 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700358 static final int WRITE_SETTINGS = 13;
359
360 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800361
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700362 // Delay time in millisecs
363 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800364 final private DefaultContainerConnection mDefContainerConn =
365 new DefaultContainerConnection();
366 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800367 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800368 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800369 IMediaContainerService imcs =
370 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800371 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800372 }
373
374 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800375 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800376 }
377 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378
Christopher Tate1bb69062010-02-19 17:02:12 -0800379 // Recordkeeping of restore-after-install operations that are currently in flight
380 // between the Package Manager and the Backup Manager
381 class PostInstallData {
382 public InstallArgs args;
383 public PackageInstalledInfo res;
384
385 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
386 args = _a;
387 res = _r;
388 }
389 };
390 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
391 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
392
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700393 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800394 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800395 final ArrayList<HandlerParams> mPendingInstalls =
396 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800397
398 private boolean connectToService() {
399 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
400 " DefaultContainerService");
401 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700402 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800403 if (mContext.bindService(service, mDefContainerConn,
404 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700405 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800406 mBound = true;
407 return true;
408 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800410 return false;
411 }
412
413 private void disconnectService() {
414 mContainerService = null;
415 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700416 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800417 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700418 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800419 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800420
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700421 PackageHandler(Looper looper) {
422 super(looper);
423 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700424
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700425 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700426 try {
427 doHandleMessage(msg);
428 } finally {
429 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
430 }
431 }
432
433 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700434 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800435 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800436 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800437 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800438 int idx = mPendingInstalls.size();
439 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
440 // If a bind was already initiated we dont really
441 // need to do anything. The pending install
442 // will be processed later on.
443 if (!mBound) {
444 // If this is the only one pending we might
445 // have to bind to the service again.
446 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800447 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800448 params.serviceError();
449 return;
450 } else {
451 // Once we bind to the service, the first
452 // pending request will be processed.
453 mPendingInstalls.add(idx, params);
454 }
455 } else {
456 mPendingInstalls.add(idx, params);
457 // Already bound to the service. Just make
458 // sure we trigger off processing the first request.
459 if (idx == 0) {
460 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800461 }
462 }
463 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800464 }
465 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800466 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800467 if (msg.obj != null) {
468 mContainerService = (IMediaContainerService) msg.obj;
469 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 if (mContainerService == null) {
471 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800472 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800473 for (HandlerParams params : mPendingInstalls) {
474 mPendingInstalls.remove(0);
475 // Indicate service bind error
476 params.serviceError();
477 }
478 mPendingInstalls.clear();
479 } else if (mPendingInstalls.size() > 0) {
480 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800481 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800482 params.startCopy();
483 }
484 } else {
485 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800486 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800487 }
488 break;
489 }
490 case MCS_RECONNECT : {
491 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
492 if (mPendingInstalls.size() > 0) {
493 if (mBound) {
494 disconnectService();
495 }
496 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800497 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800498 for (HandlerParams params : mPendingInstalls) {
499 mPendingInstalls.remove(0);
500 // Indicate service bind error
501 params.serviceError();
502 }
503 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800504 }
505 }
506 break;
507 }
508 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800509 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
510 // Delete pending install
511 if (mPendingInstalls.size() > 0) {
512 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800513 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800514 if (mPendingInstalls.size() == 0) {
515 if (mBound) {
516 disconnectService();
517 }
518 } else {
519 // There are more pending requests in queue.
520 // Just post MCS_BOUND message to trigger processing
521 // of next pending install.
522 mHandler.sendEmptyMessage(MCS_BOUND);
523 }
524 break;
525 }
526 case MCS_GIVE_UP: {
527 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
528 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800529 break;
530 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800532 String packages[];
533 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700534 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700535 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700536 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700537 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800538 if (mPendingBroadcasts == null) {
539 return;
540 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700541 size = mPendingBroadcasts.size();
542 if (size <= 0) {
543 // Nothing to be done. Just return
544 return;
545 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800546 packages = new String[size];
547 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700548 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800549 Iterator<HashMap.Entry<String, ArrayList<String>>>
550 it = mPendingBroadcasts.entrySet().iterator();
551 int i = 0;
552 while (it.hasNext() && i < size) {
553 HashMap.Entry<String, ArrayList<String>> ent = it.next();
554 packages[i] = ent.getKey();
555 components[i] = ent.getValue();
556 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700557 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800558 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700559 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800560 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700561 mPendingBroadcasts.clear();
562 }
563 // Send broadcasts
564 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800565 sendPackageChangedBroadcast(packages[i], true,
566 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700567 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700569 break;
570 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800571 case START_CLEANING_PACKAGE: {
572 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700573 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800574 synchronized (mPackages) {
575 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
576 mSettings.mPackagesToBeCleaned.add(packageName);
577 }
578 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800580 startCleaningPackages();
581 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800582 case POST_INSTALL: {
583 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
584 PostInstallData data = mRunningInstalls.get(msg.arg1);
585 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700586 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800587
588 if (data != null) {
589 InstallArgs args = data.args;
590 PackageInstalledInfo res = data.res;
591
592 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700593 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800594 Bundle extras = new Bundle(1);
595 extras.putInt(Intent.EXTRA_UID, res.uid);
596 final boolean update = res.removedInfo.removedPackage != null;
597 if (update) {
598 extras.putBoolean(Intent.EXTRA_REPLACING, true);
599 }
600 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
601 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700602 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800603 if (update) {
604 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
605 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700606 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800607 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700608 if (res.removedInfo.args != null) {
609 // Remove the replaced package's older resources safely now
610 deleteOld = true;
611 }
612 }
613 // Force a gc to clear up things
614 Runtime.getRuntime().gc();
615 // We delete after a gc for applications on sdcard.
616 if (deleteOld) {
617 synchronized (mInstallLock) {
618 res.removedInfo.args.doPostDeleteLI(true);
619 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800620 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800621 if (args.observer != null) {
622 try {
623 args.observer.packageInstalled(res.name, res.returnCode);
624 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800625 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800626 }
627 }
628 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800629 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800630 }
631 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700632 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700633 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
634 boolean reportStatus = msg.arg1 == 1;
635 boolean doGc = msg.arg2 == 1;
636 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
637 if (doGc) {
638 // Force a gc to clear up stale containers.
639 Runtime.getRuntime().gc();
640 }
641 if (msg.obj != null) {
642 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
643 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
644 // Unload containers
645 unloadAllContainers(args);
646 }
647 if (reportStatus) {
648 try {
649 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
650 PackageHelper.getMountService().finishMediaUpdate();
651 } catch (RemoteException e) {
652 Log.e(TAG, "MountService not running?");
653 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700654 }
655 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700656 case WRITE_SETTINGS: {
657 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
658 synchronized (mPackages) {
659 removeMessages(WRITE_SETTINGS);
660 mSettings.writeLP();
661 }
662 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
663 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700664 }
665 }
666 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800667
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700668 void scheduleWriteSettingsLocked() {
669 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
670 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
671 }
672 }
673
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800674 static boolean installOnSd(int flags) {
675 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700676 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800677 return false;
678 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700679 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
680 return true;
681 }
682 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800683 }
684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 public static final IPackageManager main(Context context, boolean factoryTest) {
686 PackageManagerService m = new PackageManagerService(context, factoryTest);
687 ServiceManager.addService("package", m);
688 return m;
689 }
690
691 static String[] splitString(String str, char sep) {
692 int count = 1;
693 int i = 0;
694 while ((i=str.indexOf(sep, i)) >= 0) {
695 count++;
696 i++;
697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 String[] res = new String[count];
700 i=0;
701 count = 0;
702 int lastI=0;
703 while ((i=str.indexOf(sep, i)) >= 0) {
704 res[count] = str.substring(lastI, i);
705 count++;
706 i++;
707 lastI = i;
708 }
709 res[count] = str.substring(lastI, str.length());
710 return res;
711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800714 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800718 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 mContext = context;
722 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700723 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 mMetrics = new DisplayMetrics();
725 mSettings = new Settings();
726 mSettings.addSharedUserLP("android.uid.system",
727 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
728 mSettings.addSharedUserLP("android.uid.phone",
729 MULTIPLE_APPLICATION_UIDS
730 ? RADIO_UID : FIRST_APPLICATION_UID,
731 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400732 mSettings.addSharedUserLP("android.uid.log",
733 MULTIPLE_APPLICATION_UIDS
734 ? LOG_UID : FIRST_APPLICATION_UID,
735 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736
737 String separateProcesses = SystemProperties.get("debug.separate_processes");
738 if (separateProcesses != null && separateProcesses.length() > 0) {
739 if ("*".equals(separateProcesses)) {
740 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
741 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800742 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 } else {
744 mDefParseFlags = 0;
745 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800746 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 + separateProcesses);
748 }
749 } else {
750 mDefParseFlags = 0;
751 mSeparateProcesses = null;
752 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 Installer installer = new Installer();
755 // Little hacky thing to check if installd is here, to determine
756 // whether we are running on the simulator and thus need to take
757 // care of building the /data file structure ourself.
758 // (apparently the sim now has a working installer)
759 if (installer.ping() && Process.supportsProcesses()) {
760 mInstaller = installer;
761 } else {
762 mInstaller = null;
763 }
764
765 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
766 Display d = wm.getDefaultDisplay();
767 d.getMetrics(mMetrics);
768
769 synchronized (mInstallLock) {
770 synchronized (mPackages) {
771 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700772 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 File dataDir = Environment.getDataDirectory();
775 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800776 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
778
779 if (mInstaller == null) {
780 // Make sure these dirs exist, when we are running in
781 // the simulator.
782 // Make a wide-open directory for random misc stuff.
783 File miscDir = new File(dataDir, "misc");
784 miscDir.mkdirs();
785 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800786 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 mDrmAppPrivateInstallDir.mkdirs();
788 }
789
790 readPermissions();
791
792 mRestoredSettings = mSettings.readLP();
793 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800794
795 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800797
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800798 // Set flag to monitor and not change apk file paths when
799 // scanning install directories.
800 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700801 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800802 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800803 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700804 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700809 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700812 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 /**
815 * Out of paranoia, ensure that everything in the boot class
816 * path has been dexed.
817 */
818 String bootClassPath = System.getProperty("java.boot.class.path");
819 if (bootClassPath != null) {
820 String[] paths = splitString(bootClassPath, ':');
821 for (int i=0; i<paths.length; i++) {
822 try {
823 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
824 libFiles.add(paths[i]);
825 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700826 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 }
828 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800829 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800831 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 }
833 }
834 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800835 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 /**
839 * Also ensure all external libraries have had dexopt run on them.
840 */
841 if (mSharedLibraries.size() > 0) {
842 Iterator<String> libs = mSharedLibraries.values().iterator();
843 while (libs.hasNext()) {
844 String lib = libs.next();
845 try {
846 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
847 libFiles.add(lib);
848 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700849 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 }
851 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800852 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800854 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
856 }
857 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 // Gross hack for now: we know this file doesn't contain any
860 // code, so don't dexopt it to avoid the resulting log spew.
861 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 /**
864 * And there are a number of commands implemented in Java, which
865 * we currently need to do the dexopt on so that they can be
866 * run from a non-root shell.
867 */
868 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700869 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 for (int i=0; i<frameworkFiles.length; i++) {
871 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
872 String path = libPath.getPath();
873 // Skip the file if we alrady did it.
874 if (libFiles.contains(path)) {
875 continue;
876 }
877 // Skip the file if it is not a type we want to dexopt.
878 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
879 continue;
880 }
881 try {
882 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
883 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700884 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
886 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800887 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800889 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
891 }
892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800893
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700894 if (didDexOpt) {
895 // If we had to do a dexopt of one of the previous
896 // things, then something on the system has changed.
897 // Consider this significant, and wipe away all other
898 // existing dexopt files to ensure we don't leave any
899 // dangling around.
900 String[] files = mDalvikCacheDir.list();
901 if (files != null) {
902 for (int i=0; i<files.length; i++) {
903 String fn = files[i];
904 if (fn.startsWith("data@app@")
905 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800906 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700907 (new File(mDalvikCacheDir, fn)).delete();
908 }
909 }
910 }
911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800913
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800914 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 mFrameworkInstallObserver = new AppDirObserver(
916 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
917 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700918 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
919 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800920 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800921
922 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
924 mSystemInstallObserver = new AppDirObserver(
925 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
926 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700927 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
928 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800929
930 if (mInstaller != null) {
931 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
932 mInstaller.moveFiles();
933 }
934
935 // Prune any system packages that no longer exist.
936 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
937 while (psit.hasNext()) {
938 PackageSetting ps = psit.next();
939 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800940 && !mPackages.containsKey(ps.name)
941 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800942 psit.remove();
943 String msg = "System package " + ps.name
944 + " no longer exists; wiping its data";
945 reportSettingsProblem(Log.WARN, msg);
946 if (mInstaller != null) {
947 // XXX how to set useEncryptedFSDir for packages that
948 // are not encrypted?
949 mInstaller.remove(ps.name, true);
950 }
951 }
952 }
953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 mAppInstallDir = new File(dataDir, "app");
955 if (mInstaller == null) {
956 // Make sure these dirs exist, when we are running in
957 // the simulator.
958 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
959 }
960 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800961 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 //clean up list
963 for(int i = 0; i < deletePkgsList.size(); i++) {
964 //clean up here
965 cleanupInstallFailedPackage(deletePkgsList.get(i));
966 }
967 //delete tmp files
968 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800969
970 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 SystemClock.uptimeMillis());
972 mAppInstallObserver = new AppDirObserver(
973 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
974 mAppInstallObserver.startWatching();
975 scanDirLI(mAppInstallDir, 0, scanMode);
976
977 mDrmAppInstallObserver = new AppDirObserver(
978 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
979 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800980 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800982 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800984 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 + ((SystemClock.uptimeMillis()-startTime)/1000f)
986 + " seconds");
987
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700988 // If the platform SDK has changed since the last time we booted,
989 // we need to re-grant app permission to catch any new ones that
990 // appear. This is really a hack, and means that apps can in some
991 // cases get permissions that the user didn't initially explicitly
992 // allow... it would be nice to have some better way to handle
993 // this situation.
994 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
995 != mSdkVersion;
996 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
997 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
998 + "; regranting permissions for internal storage");
999 mSettings.mInternalSdkPlatform = mSdkVersion;
1000
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001001 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002
1003 mSettings.writeLP();
1004
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001005 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 // Now after opening every single application zip, make sure they
1009 // are all flushed. Not really needed, but keeps things nice and
1010 // tidy.
1011 Runtime.getRuntime().gc();
1012 } // synchronized (mPackages)
1013 } // synchronized (mInstallLock)
1014 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 @Override
1017 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1018 throws RemoteException {
1019 try {
1020 return super.onTransact(code, data, reply, flags);
1021 } catch (RuntimeException e) {
1022 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001023 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025 throw e;
1026 }
1027 }
1028
Dianne Hackborne6620b22010-01-22 14:46:21 -08001029 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001030 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001032 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1033 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001035 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001036 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
1038 } else {
1039 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001040 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 File dataDir = new File(pkg.applicationInfo.dataDir);
1042 dataDir.delete();
1043 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001044 if (ps.codePath != null) {
1045 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001046 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001047 }
1048 }
1049 if (ps.resourcePath != null) {
1050 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001051 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001052 }
1053 }
1054 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
1056
1057 void readPermissions() {
1058 // Read permissions from .../etc/permission directory.
1059 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1060 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001061 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 return;
1063 }
1064 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001065 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 return;
1067 }
1068
1069 // Iterate over the files in the directory and scan .xml files
1070 for (File f : libraryDir.listFiles()) {
1071 // We'll read platform.xml last
1072 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1073 continue;
1074 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001077 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 continue;
1079 }
1080 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001081 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 continue;
1083 }
1084
1085 readPermissionsFromXml(f);
1086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1089 final File permFile = new File(Environment.getRootDirectory(),
1090 "etc/permissions/platform.xml");
1091 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001092
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001093 StringBuilder sb = new StringBuilder(128);
1094 sb.append("Libs:");
1095 Iterator<String> it = mSharedLibraries.keySet().iterator();
1096 while (it.hasNext()) {
1097 sb.append(' ');
1098 String name = it.next();
1099 sb.append(name);
1100 sb.append(':');
1101 sb.append(mSharedLibraries.get(name));
1102 }
1103 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001104
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001105 sb.setLength(0);
1106 sb.append("Features:");
1107 it = mAvailableFeatures.keySet().iterator();
1108 while (it.hasNext()) {
1109 sb.append(' ');
1110 sb.append(it.next());
1111 }
1112 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001114
1115 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 FileReader permReader = null;
1117 try {
1118 permReader = new FileReader(permFile);
1119 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001120 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 return;
1122 }
1123
1124 try {
1125 XmlPullParser parser = Xml.newPullParser();
1126 parser.setInput(permReader);
1127
1128 XmlUtils.beginDocument(parser, "permissions");
1129
1130 while (true) {
1131 XmlUtils.nextElement(parser);
1132 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1133 break;
1134 }
1135
1136 String name = parser.getName();
1137 if ("group".equals(name)) {
1138 String gidStr = parser.getAttributeValue(null, "gid");
1139 if (gidStr != null) {
1140 int gid = Integer.parseInt(gidStr);
1141 mGlobalGids = appendInt(mGlobalGids, gid);
1142 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001143 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 + parser.getPositionDescription());
1145 }
1146
1147 XmlUtils.skipCurrentTag(parser);
1148 continue;
1149 } else if ("permission".equals(name)) {
1150 String perm = parser.getAttributeValue(null, "name");
1151 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001152 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 + parser.getPositionDescription());
1154 XmlUtils.skipCurrentTag(parser);
1155 continue;
1156 }
1157 perm = perm.intern();
1158 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 } else if ("assign-permission".equals(name)) {
1161 String perm = parser.getAttributeValue(null, "name");
1162 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001163 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 + parser.getPositionDescription());
1165 XmlUtils.skipCurrentTag(parser);
1166 continue;
1167 }
1168 String uidStr = parser.getAttributeValue(null, "uid");
1169 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001170 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 + parser.getPositionDescription());
1172 XmlUtils.skipCurrentTag(parser);
1173 continue;
1174 }
1175 int uid = Process.getUidForName(uidStr);
1176 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001177 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 + uidStr + "\" at "
1179 + parser.getPositionDescription());
1180 XmlUtils.skipCurrentTag(parser);
1181 continue;
1182 }
1183 perm = perm.intern();
1184 HashSet<String> perms = mSystemPermissions.get(uid);
1185 if (perms == null) {
1186 perms = new HashSet<String>();
1187 mSystemPermissions.put(uid, perms);
1188 }
1189 perms.add(perm);
1190 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 } else if ("library".equals(name)) {
1193 String lname = parser.getAttributeValue(null, "name");
1194 String lfile = parser.getAttributeValue(null, "file");
1195 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001196 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 + parser.getPositionDescription());
1198 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001199 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 + parser.getPositionDescription());
1201 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001202 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001203 mSharedLibraries.put(lname, lfile);
1204 }
1205 XmlUtils.skipCurrentTag(parser);
1206 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001207
Dianne Hackborn49237342009-08-27 20:08:01 -07001208 } else if ("feature".equals(name)) {
1209 String fname = parser.getAttributeValue(null, "name");
1210 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001211 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001212 + parser.getPositionDescription());
1213 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001214 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001215 FeatureInfo fi = new FeatureInfo();
1216 fi.name = fname;
1217 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
1219 XmlUtils.skipCurrentTag(parser);
1220 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 } else {
1223 XmlUtils.skipCurrentTag(parser);
1224 continue;
1225 }
1226
1227 }
1228 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001229 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001231 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233 }
1234
1235 void readPermission(XmlPullParser parser, String name)
1236 throws IOException, XmlPullParserException {
1237
1238 name = name.intern();
1239
1240 BasePermission bp = mSettings.mPermissions.get(name);
1241 if (bp == null) {
1242 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1243 mSettings.mPermissions.put(name, bp);
1244 }
1245 int outerDepth = parser.getDepth();
1246 int type;
1247 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1248 && (type != XmlPullParser.END_TAG
1249 || parser.getDepth() > outerDepth)) {
1250 if (type == XmlPullParser.END_TAG
1251 || type == XmlPullParser.TEXT) {
1252 continue;
1253 }
1254
1255 String tagName = parser.getName();
1256 if ("group".equals(tagName)) {
1257 String gidStr = parser.getAttributeValue(null, "gid");
1258 if (gidStr != null) {
1259 int gid = Process.getGidForName(gidStr);
1260 bp.gids = appendInt(bp.gids, gid);
1261 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001262 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 + parser.getPositionDescription());
1264 }
1265 }
1266 XmlUtils.skipCurrentTag(parser);
1267 }
1268 }
1269
1270 static int[] appendInt(int[] cur, int val) {
1271 if (cur == null) {
1272 return new int[] { val };
1273 }
1274 final int N = cur.length;
1275 for (int i=0; i<N; i++) {
1276 if (cur[i] == val) {
1277 return cur;
1278 }
1279 }
1280 int[] ret = new int[N+1];
1281 System.arraycopy(cur, 0, ret, 0, N);
1282 ret[N] = val;
1283 return ret;
1284 }
1285
1286 static int[] appendInts(int[] cur, int[] add) {
1287 if (add == null) return cur;
1288 if (cur == null) return add;
1289 final int N = add.length;
1290 for (int i=0; i<N; i++) {
1291 cur = appendInt(cur, add[i]);
1292 }
1293 return cur;
1294 }
1295
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001296 static int[] removeInt(int[] cur, int val) {
1297 if (cur == null) {
1298 return null;
1299 }
1300 final int N = cur.length;
1301 for (int i=0; i<N; i++) {
1302 if (cur[i] == val) {
1303 int[] ret = new int[N-1];
1304 if (i > 0) {
1305 System.arraycopy(cur, 0, ret, 0, i);
1306 }
1307 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001308 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001309 }
1310 return ret;
1311 }
1312 }
1313 return cur;
1314 }
1315
1316 static int[] removeInts(int[] cur, int[] rem) {
1317 if (rem == null) return cur;
1318 if (cur == null) return cur;
1319 final int N = rem.length;
1320 for (int i=0; i<N; i++) {
1321 cur = removeInt(cur, rem[i]);
1322 }
1323 return cur;
1324 }
1325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001327 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1328 // The package has been uninstalled but has retained data and resources.
1329 return PackageParser.generatePackageInfo(p, null, flags);
1330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 final PackageSetting ps = (PackageSetting)p.mExtras;
1332 if (ps == null) {
1333 return null;
1334 }
1335 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1336 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1337 }
1338
1339 public PackageInfo getPackageInfo(String packageName, int flags) {
1340 synchronized (mPackages) {
1341 PackageParser.Package p = mPackages.get(packageName);
1342 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001343 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 + ": " + p);
1345 if (p != null) {
1346 return generatePackageInfo(p, flags);
1347 }
1348 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1349 return generatePackageInfoFromSettingsLP(packageName, flags);
1350 }
1351 }
1352 return null;
1353 }
1354
Dianne Hackborn47096932010-02-11 15:57:09 -08001355 public String[] currentToCanonicalPackageNames(String[] names) {
1356 String[] out = new String[names.length];
1357 synchronized (mPackages) {
1358 for (int i=names.length-1; i>=0; i--) {
1359 PackageSetting ps = mSettings.mPackages.get(names[i]);
1360 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1361 }
1362 }
1363 return out;
1364 }
1365
1366 public String[] canonicalToCurrentPackageNames(String[] names) {
1367 String[] out = new String[names.length];
1368 synchronized (mPackages) {
1369 for (int i=names.length-1; i>=0; i--) {
1370 String cur = mSettings.mRenamedPackages.get(names[i]);
1371 out[i] = cur != null ? cur : names[i];
1372 }
1373 }
1374 return out;
1375 }
1376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 public int getPackageUid(String packageName) {
1378 synchronized (mPackages) {
1379 PackageParser.Package p = mPackages.get(packageName);
1380 if(p != null) {
1381 return p.applicationInfo.uid;
1382 }
1383 PackageSetting ps = mSettings.mPackages.get(packageName);
1384 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1385 return -1;
1386 }
1387 p = ps.pkg;
1388 return p != null ? p.applicationInfo.uid : -1;
1389 }
1390 }
1391
1392 public int[] getPackageGids(String packageName) {
1393 synchronized (mPackages) {
1394 PackageParser.Package p = mPackages.get(packageName);
1395 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001396 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 + ": " + p);
1398 if (p != null) {
1399 final PackageSetting ps = (PackageSetting)p.mExtras;
1400 final SharedUserSetting suid = ps.sharedUser;
1401 return suid != null ? suid.gids : ps.gids;
1402 }
1403 }
1404 // stupid thing to indicate an error.
1405 return new int[0];
1406 }
1407
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001408 static final PermissionInfo generatePermissionInfo(
1409 BasePermission bp, int flags) {
1410 if (bp.perm != null) {
1411 return PackageParser.generatePermissionInfo(bp.perm, flags);
1412 }
1413 PermissionInfo pi = new PermissionInfo();
1414 pi.name = bp.name;
1415 pi.packageName = bp.sourcePackage;
1416 pi.nonLocalizedLabel = bp.name;
1417 pi.protectionLevel = bp.protectionLevel;
1418 return pi;
1419 }
1420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 public PermissionInfo getPermissionInfo(String name, int flags) {
1422 synchronized (mPackages) {
1423 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001424 if (p != null) {
1425 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
1427 return null;
1428 }
1429 }
1430
1431 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1432 synchronized (mPackages) {
1433 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1434 for (BasePermission p : mSettings.mPermissions.values()) {
1435 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001436 if (p.perm == null || p.perm.info.group == null) {
1437 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001440 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1442 }
1443 }
1444 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 if (out.size() > 0) {
1447 return out;
1448 }
1449 return mPermissionGroups.containsKey(group) ? out : null;
1450 }
1451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1454 synchronized (mPackages) {
1455 return PackageParser.generatePermissionGroupInfo(
1456 mPermissionGroups.get(name), flags);
1457 }
1458 }
1459
1460 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1461 synchronized (mPackages) {
1462 final int N = mPermissionGroups.size();
1463 ArrayList<PermissionGroupInfo> out
1464 = new ArrayList<PermissionGroupInfo>(N);
1465 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1466 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1467 }
1468 return out;
1469 }
1470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1473 PackageSetting ps = mSettings.mPackages.get(packageName);
1474 if(ps != null) {
1475 if(ps.pkg == null) {
1476 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1477 if(pInfo != null) {
1478 return pInfo.applicationInfo;
1479 }
1480 return null;
1481 }
1482 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1483 }
1484 return null;
1485 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1488 PackageSetting ps = mSettings.mPackages.get(packageName);
1489 if(ps != null) {
1490 if(ps.pkg == null) {
1491 ps.pkg = new PackageParser.Package(packageName);
1492 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001493 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1494 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1495 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1496 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001497 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001498 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500 return generatePackageInfo(ps.pkg, flags);
1501 }
1502 return null;
1503 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1506 synchronized (mPackages) {
1507 PackageParser.Package p = mPackages.get(packageName);
1508 if (Config.LOGV) Log.v(
1509 TAG, "getApplicationInfo " + packageName
1510 + ": " + p);
1511 if (p != null) {
1512 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001513 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 }
1515 if ("android".equals(packageName)||"system".equals(packageName)) {
1516 return mAndroidApplication;
1517 }
1518 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1519 return generateApplicationInfoFromSettingsLP(packageName, flags);
1520 }
1521 }
1522 return null;
1523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001524
1525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1527 mContext.enforceCallingOrSelfPermission(
1528 android.Manifest.permission.CLEAR_APP_CACHE, null);
1529 // Queue up an async operation since clearing cache may take a little while.
1530 mHandler.post(new Runnable() {
1531 public void run() {
1532 mHandler.removeCallbacks(this);
1533 int retCode = -1;
1534 if (mInstaller != null) {
1535 retCode = mInstaller.freeCache(freeStorageSize);
1536 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001537 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539 } //end if mInstaller
1540 if (observer != null) {
1541 try {
1542 observer.onRemoveCompleted(null, (retCode >= 0));
1543 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001544 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
1546 }
1547 }
1548 });
1549 }
1550
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001551 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001552 mContext.enforceCallingOrSelfPermission(
1553 android.Manifest.permission.CLEAR_APP_CACHE, null);
1554 // Queue up an async operation since clearing cache may take a little while.
1555 mHandler.post(new Runnable() {
1556 public void run() {
1557 mHandler.removeCallbacks(this);
1558 int retCode = -1;
1559 if (mInstaller != null) {
1560 retCode = mInstaller.freeCache(freeStorageSize);
1561 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001562 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001563 }
1564 }
1565 if(pi != null) {
1566 try {
1567 // Callback via pending intent
1568 int code = (retCode >= 0) ? 1 : 0;
1569 pi.sendIntent(null, code, null,
1570 null, null);
1571 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001572 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001573 }
1574 }
1575 }
1576 });
1577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1580 synchronized (mPackages) {
1581 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001582
1583 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001585 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587 if (mResolveComponentName.equals(component)) {
1588 return mResolveActivity;
1589 }
1590 }
1591 return null;
1592 }
1593
1594 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1595 synchronized (mPackages) {
1596 PackageParser.Activity a = mReceivers.mActivities.get(component);
1597 if (Config.LOGV) Log.v(
1598 TAG, "getReceiverInfo " + component + ": " + a);
1599 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1600 return PackageParser.generateActivityInfo(a, flags);
1601 }
1602 }
1603 return null;
1604 }
1605
1606 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1607 synchronized (mPackages) {
1608 PackageParser.Service s = mServices.mServices.get(component);
1609 if (Config.LOGV) Log.v(
1610 TAG, "getServiceInfo " + component + ": " + s);
1611 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1612 return PackageParser.generateServiceInfo(s, flags);
1613 }
1614 }
1615 return null;
1616 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001617
Dianne Hackborn361199b2010-08-30 17:42:07 -07001618 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1619 synchronized (mPackages) {
1620 PackageParser.Provider p = mProvidersByComponent.get(component);
1621 if (Config.LOGV) Log.v(
1622 TAG, "getProviderInfo " + component + ": " + p);
1623 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1624 return PackageParser.generateProviderInfo(p, flags);
1625 }
1626 }
1627 return null;
1628 }
1629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 public String[] getSystemSharedLibraryNames() {
1631 Set<String> libSet;
1632 synchronized (mPackages) {
1633 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001634 int size = libSet.size();
1635 if (size > 0) {
1636 String[] libs = new String[size];
1637 libSet.toArray(libs);
1638 return libs;
1639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001641 return null;
1642 }
1643
1644 public FeatureInfo[] getSystemAvailableFeatures() {
1645 Collection<FeatureInfo> featSet;
1646 synchronized (mPackages) {
1647 featSet = mAvailableFeatures.values();
1648 int size = featSet.size();
1649 if (size > 0) {
1650 FeatureInfo[] features = new FeatureInfo[size+1];
1651 featSet.toArray(features);
1652 FeatureInfo fi = new FeatureInfo();
1653 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1654 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1655 features[size] = fi;
1656 return features;
1657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 }
1659 return null;
1660 }
1661
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001662 public boolean hasSystemFeature(String name) {
1663 synchronized (mPackages) {
1664 return mAvailableFeatures.containsKey(name);
1665 }
1666 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 public int checkPermission(String permName, String pkgName) {
1669 synchronized (mPackages) {
1670 PackageParser.Package p = mPackages.get(pkgName);
1671 if (p != null && p.mExtras != null) {
1672 PackageSetting ps = (PackageSetting)p.mExtras;
1673 if (ps.sharedUser != null) {
1674 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1675 return PackageManager.PERMISSION_GRANTED;
1676 }
1677 } else if (ps.grantedPermissions.contains(permName)) {
1678 return PackageManager.PERMISSION_GRANTED;
1679 }
1680 }
1681 }
1682 return PackageManager.PERMISSION_DENIED;
1683 }
1684
1685 public int checkUidPermission(String permName, int uid) {
1686 synchronized (mPackages) {
1687 Object obj = mSettings.getUserIdLP(uid);
1688 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001689 GrantedPermissions gp = (GrantedPermissions)obj;
1690 if (gp.grantedPermissions.contains(permName)) {
1691 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
1693 } else {
1694 HashSet<String> perms = mSystemPermissions.get(uid);
1695 if (perms != null && perms.contains(permName)) {
1696 return PackageManager.PERMISSION_GRANTED;
1697 }
1698 }
1699 }
1700 return PackageManager.PERMISSION_DENIED;
1701 }
1702
1703 private BasePermission findPermissionTreeLP(String permName) {
1704 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1705 if (permName.startsWith(bp.name) &&
1706 permName.length() > bp.name.length() &&
1707 permName.charAt(bp.name.length()) == '.') {
1708 return bp;
1709 }
1710 }
1711 return null;
1712 }
1713
1714 private BasePermission checkPermissionTreeLP(String permName) {
1715 if (permName != null) {
1716 BasePermission bp = findPermissionTreeLP(permName);
1717 if (bp != null) {
1718 if (bp.uid == Binder.getCallingUid()) {
1719 return bp;
1720 }
1721 throw new SecurityException("Calling uid "
1722 + Binder.getCallingUid()
1723 + " is not allowed to add to permission tree "
1724 + bp.name + " owned by uid " + bp.uid);
1725 }
1726 }
1727 throw new SecurityException("No permission tree found for " + permName);
1728 }
1729
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001730 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1731 if (s1 == null) {
1732 return s2 == null;
1733 }
1734 if (s2 == null) {
1735 return false;
1736 }
1737 if (s1.getClass() != s2.getClass()) {
1738 return false;
1739 }
1740 return s1.equals(s2);
1741 }
1742
1743 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1744 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001745 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001746 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1747 if (!compareStrings(pi1.name, pi2.name)) return false;
1748 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1749 // We'll take care of setting this one.
1750 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1751 // These are not currently stored in settings.
1752 //if (!compareStrings(pi1.group, pi2.group)) return false;
1753 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1754 //if (pi1.labelRes != pi2.labelRes) return false;
1755 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1756 return true;
1757 }
1758
1759 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1760 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1761 throw new SecurityException("Label must be specified in permission");
1762 }
1763 BasePermission tree = checkPermissionTreeLP(info.name);
1764 BasePermission bp = mSettings.mPermissions.get(info.name);
1765 boolean added = bp == null;
1766 boolean changed = true;
1767 if (added) {
1768 bp = new BasePermission(info.name, tree.sourcePackage,
1769 BasePermission.TYPE_DYNAMIC);
1770 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1771 throw new SecurityException(
1772 "Not allowed to modify non-dynamic permission "
1773 + info.name);
1774 } else {
1775 if (bp.protectionLevel == info.protectionLevel
1776 && bp.perm.owner.equals(tree.perm.owner)
1777 && bp.uid == tree.uid
1778 && comparePermissionInfos(bp.perm.info, info)) {
1779 changed = false;
1780 }
1781 }
1782 bp.protectionLevel = info.protectionLevel;
1783 bp.perm = new PackageParser.Permission(tree.perm.owner,
1784 new PermissionInfo(info));
1785 bp.perm.info.packageName = tree.perm.info.packageName;
1786 bp.uid = tree.uid;
1787 if (added) {
1788 mSettings.mPermissions.put(info.name, bp);
1789 }
1790 if (changed) {
1791 if (!async) {
1792 mSettings.writeLP();
1793 } else {
1794 scheduleWriteSettingsLocked();
1795 }
1796 }
1797 return added;
1798 }
1799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 public boolean addPermission(PermissionInfo info) {
1801 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001802 return addPermissionLocked(info, false);
1803 }
1804 }
1805
1806 public boolean addPermissionAsync(PermissionInfo info) {
1807 synchronized (mPackages) {
1808 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810 }
1811
1812 public void removePermission(String name) {
1813 synchronized (mPackages) {
1814 checkPermissionTreeLP(name);
1815 BasePermission bp = mSettings.mPermissions.get(name);
1816 if (bp != null) {
1817 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1818 throw new SecurityException(
1819 "Not allowed to modify non-dynamic permission "
1820 + name);
1821 }
1822 mSettings.mPermissions.remove(name);
1823 mSettings.writeLP();
1824 }
1825 }
1826 }
1827
Dianne Hackborn854060af2009-07-09 18:14:31 -07001828 public boolean isProtectedBroadcast(String actionName) {
1829 synchronized (mPackages) {
1830 return mProtectedBroadcasts.contains(actionName);
1831 }
1832 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 public int checkSignatures(String pkg1, String pkg2) {
1835 synchronized (mPackages) {
1836 PackageParser.Package p1 = mPackages.get(pkg1);
1837 PackageParser.Package p2 = mPackages.get(pkg2);
1838 if (p1 == null || p1.mExtras == null
1839 || p2 == null || p2.mExtras == null) {
1840 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1841 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001842 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
1844 }
1845
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001846 public int checkUidSignatures(int uid1, int uid2) {
1847 synchronized (mPackages) {
1848 Signature[] s1;
1849 Signature[] s2;
1850 Object obj = mSettings.getUserIdLP(uid1);
1851 if (obj != null) {
1852 if (obj instanceof SharedUserSetting) {
1853 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1854 } else if (obj instanceof PackageSetting) {
1855 s1 = ((PackageSetting)obj).signatures.mSignatures;
1856 } else {
1857 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1858 }
1859 } else {
1860 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1861 }
1862 obj = mSettings.getUserIdLP(uid2);
1863 if (obj != null) {
1864 if (obj instanceof SharedUserSetting) {
1865 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1866 } else if (obj instanceof PackageSetting) {
1867 s2 = ((PackageSetting)obj).signatures.mSignatures;
1868 } else {
1869 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1870 }
1871 } else {
1872 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1873 }
1874 return checkSignaturesLP(s1, s2);
1875 }
1876 }
1877
1878 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1879 if (s1 == null) {
1880 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1882 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1883 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001884 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1886 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001887 HashSet<Signature> set1 = new HashSet<Signature>();
1888 for (Signature sig : s1) {
1889 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001891 HashSet<Signature> set2 = new HashSet<Signature>();
1892 for (Signature sig : s2) {
1893 set2.add(sig);
1894 }
1895 // Make sure s2 contains all signatures in s1.
1896 if (set1.equals(set2)) {
1897 return PackageManager.SIGNATURE_MATCH;
1898 }
1899 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 }
1901
1902 public String[] getPackagesForUid(int uid) {
1903 synchronized (mPackages) {
1904 Object obj = mSettings.getUserIdLP(uid);
1905 if (obj instanceof SharedUserSetting) {
1906 SharedUserSetting sus = (SharedUserSetting)obj;
1907 final int N = sus.packages.size();
1908 String[] res = new String[N];
1909 Iterator<PackageSetting> it = sus.packages.iterator();
1910 int i=0;
1911 while (it.hasNext()) {
1912 res[i++] = it.next().name;
1913 }
1914 return res;
1915 } else if (obj instanceof PackageSetting) {
1916 PackageSetting ps = (PackageSetting)obj;
1917 return new String[] { ps.name };
1918 }
1919 }
1920 return null;
1921 }
1922
1923 public String getNameForUid(int uid) {
1924 synchronized (mPackages) {
1925 Object obj = mSettings.getUserIdLP(uid);
1926 if (obj instanceof SharedUserSetting) {
1927 SharedUserSetting sus = (SharedUserSetting)obj;
1928 return sus.name + ":" + sus.userId;
1929 } else if (obj instanceof PackageSetting) {
1930 PackageSetting ps = (PackageSetting)obj;
1931 return ps.name;
1932 }
1933 }
1934 return null;
1935 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 public int getUidForSharedUser(String sharedUserName) {
1938 if(sharedUserName == null) {
1939 return -1;
1940 }
1941 synchronized (mPackages) {
1942 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1943 if(suid == null) {
1944 return -1;
1945 }
1946 return suid.userId;
1947 }
1948 }
1949
1950 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1951 int flags) {
1952 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001953 return chooseBestActivity(intent, resolvedType, flags, query);
1954 }
1955
Mihai Predaeae850c2009-05-13 10:13:48 +02001956 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1957 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 if (query != null) {
1959 final int N = query.size();
1960 if (N == 1) {
1961 return query.get(0);
1962 } else if (N > 1) {
1963 // If there is more than one activity with the same priority,
1964 // then let the user decide between them.
1965 ResolveInfo r0 = query.get(0);
1966 ResolveInfo r1 = query.get(1);
1967 if (false) {
1968 System.out.println(r0.activityInfo.name +
1969 "=" + r0.priority + " vs " +
1970 r1.activityInfo.name +
1971 "=" + r1.priority);
1972 }
1973 // If the first activity has a higher priority, or a different
1974 // default, then it is always desireable to pick it.
1975 if (r0.priority != r1.priority
1976 || r0.preferredOrder != r1.preferredOrder
1977 || r0.isDefault != r1.isDefault) {
1978 return query.get(0);
1979 }
1980 // If we have saved a preference for a preferred activity for
1981 // this Intent, use that.
1982 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1983 flags, query, r0.priority);
1984 if (ri != null) {
1985 return ri;
1986 }
1987 return mResolveInfo;
1988 }
1989 }
1990 return null;
1991 }
1992
1993 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1994 int flags, List<ResolveInfo> query, int priority) {
1995 synchronized (mPackages) {
1996 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1997 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001998 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2000 if (prefs != null && prefs.size() > 0) {
2001 // First figure out how good the original match set is.
2002 // We will only allow preferred activities that came
2003 // from the same match quality.
2004 int match = 0;
2005 final int N = query.size();
2006 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2007 for (int j=0; j<N; j++) {
2008 ResolveInfo ri = query.get(j);
2009 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2010 + ": 0x" + Integer.toHexString(match));
2011 if (ri.match > match) match = ri.match;
2012 }
2013 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2014 + Integer.toHexString(match));
2015 match &= IntentFilter.MATCH_CATEGORY_MASK;
2016 final int M = prefs.size();
2017 for (int i=0; i<M; i++) {
2018 PreferredActivity pa = prefs.get(i);
2019 if (pa.mMatch != match) {
2020 continue;
2021 }
2022 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2023 if (DEBUG_PREFERRED) {
2024 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002025 if (ai != null) {
2026 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2027 } else {
2028 Log.v(TAG, " null");
2029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 }
2031 if (ai != null) {
2032 for (int j=0; j<N; j++) {
2033 ResolveInfo ri = query.get(j);
2034 if (!ri.activityInfo.applicationInfo.packageName
2035 .equals(ai.applicationInfo.packageName)) {
2036 continue;
2037 }
2038 if (!ri.activityInfo.name.equals(ai.name)) {
2039 continue;
2040 }
2041
2042 // Okay we found a previously set preferred app.
2043 // If the result set is different from when this
2044 // was created, we need to clear it and re-ask the
2045 // user their preference.
2046 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002047 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 + intent + " type " + resolvedType);
2049 mSettings.mPreferredActivities.removeFilter(pa);
2050 return null;
2051 }
2052
2053 // Yay!
2054 return ri;
2055 }
2056 }
2057 }
2058 }
2059 }
2060 return null;
2061 }
2062
2063 public List<ResolveInfo> queryIntentActivities(Intent intent,
2064 String resolvedType, int flags) {
2065 ComponentName comp = intent.getComponent();
2066 if (comp != null) {
2067 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2068 ActivityInfo ai = getActivityInfo(comp, flags);
2069 if (ai != null) {
2070 ResolveInfo ri = new ResolveInfo();
2071 ri.activityInfo = ai;
2072 list.add(ri);
2073 }
2074 return list;
2075 }
2076
2077 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002078 String pkgName = intent.getPackage();
2079 if (pkgName == null) {
2080 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2081 resolvedType, flags);
2082 }
2083 PackageParser.Package pkg = mPackages.get(pkgName);
2084 if (pkg != null) {
2085 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2086 resolvedType, flags, pkg.activities);
2087 }
2088 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
2090 }
2091
2092 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2093 Intent[] specifics, String[] specificTypes, Intent intent,
2094 String resolvedType, int flags) {
2095 final String resultsAction = intent.getAction();
2096
2097 List<ResolveInfo> results = queryIntentActivities(
2098 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2099 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2100
2101 int specificsPos = 0;
2102 int N;
2103
2104 // todo: note that the algorithm used here is O(N^2). This
2105 // isn't a problem in our current environment, but if we start running
2106 // into situations where we have more than 5 or 10 matches then this
2107 // should probably be changed to something smarter...
2108
2109 // First we go through and resolve each of the specific items
2110 // that were supplied, taking care of removing any corresponding
2111 // duplicate items in the generic resolve list.
2112 if (specifics != null) {
2113 for (int i=0; i<specifics.length; i++) {
2114 final Intent sintent = specifics[i];
2115 if (sintent == null) {
2116 continue;
2117 }
2118
2119 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2120 String action = sintent.getAction();
2121 if (resultsAction != null && resultsAction.equals(action)) {
2122 // If this action was explicitly requested, then don't
2123 // remove things that have it.
2124 action = null;
2125 }
2126 ComponentName comp = sintent.getComponent();
2127 ResolveInfo ri = null;
2128 ActivityInfo ai = null;
2129 if (comp == null) {
2130 ri = resolveIntent(
2131 sintent,
2132 specificTypes != null ? specificTypes[i] : null,
2133 flags);
2134 if (ri == null) {
2135 continue;
2136 }
2137 if (ri == mResolveInfo) {
2138 // ACK! Must do something better with this.
2139 }
2140 ai = ri.activityInfo;
2141 comp = new ComponentName(ai.applicationInfo.packageName,
2142 ai.name);
2143 } else {
2144 ai = getActivityInfo(comp, flags);
2145 if (ai == null) {
2146 continue;
2147 }
2148 }
2149
2150 // Look for any generic query activities that are duplicates
2151 // of this specific one, and remove them from the results.
2152 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2153 N = results.size();
2154 int j;
2155 for (j=specificsPos; j<N; j++) {
2156 ResolveInfo sri = results.get(j);
2157 if ((sri.activityInfo.name.equals(comp.getClassName())
2158 && sri.activityInfo.applicationInfo.packageName.equals(
2159 comp.getPackageName()))
2160 || (action != null && sri.filter.matchAction(action))) {
2161 results.remove(j);
2162 if (Config.LOGV) Log.v(
2163 TAG, "Removing duplicate item from " + j
2164 + " due to specific " + specificsPos);
2165 if (ri == null) {
2166 ri = sri;
2167 }
2168 j--;
2169 N--;
2170 }
2171 }
2172
2173 // Add this specific item to its proper place.
2174 if (ri == null) {
2175 ri = new ResolveInfo();
2176 ri.activityInfo = ai;
2177 }
2178 results.add(specificsPos, ri);
2179 ri.specificIndex = i;
2180 specificsPos++;
2181 }
2182 }
2183
2184 // Now we go through the remaining generic results and remove any
2185 // duplicate actions that are found here.
2186 N = results.size();
2187 for (int i=specificsPos; i<N-1; i++) {
2188 final ResolveInfo rii = results.get(i);
2189 if (rii.filter == null) {
2190 continue;
2191 }
2192
2193 // Iterate over all of the actions of this result's intent
2194 // filter... typically this should be just one.
2195 final Iterator<String> it = rii.filter.actionsIterator();
2196 if (it == null) {
2197 continue;
2198 }
2199 while (it.hasNext()) {
2200 final String action = it.next();
2201 if (resultsAction != null && resultsAction.equals(action)) {
2202 // If this action was explicitly requested, then don't
2203 // remove things that have it.
2204 continue;
2205 }
2206 for (int j=i+1; j<N; j++) {
2207 final ResolveInfo rij = results.get(j);
2208 if (rij.filter != null && rij.filter.hasAction(action)) {
2209 results.remove(j);
2210 if (Config.LOGV) Log.v(
2211 TAG, "Removing duplicate item from " + j
2212 + " due to action " + action + " at " + i);
2213 j--;
2214 N--;
2215 }
2216 }
2217 }
2218
2219 // If the caller didn't request filter information, drop it now
2220 // so we don't have to marshall/unmarshall it.
2221 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2222 rii.filter = null;
2223 }
2224 }
2225
2226 // Filter out the caller activity if so requested.
2227 if (caller != null) {
2228 N = results.size();
2229 for (int i=0; i<N; i++) {
2230 ActivityInfo ainfo = results.get(i).activityInfo;
2231 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2232 && caller.getClassName().equals(ainfo.name)) {
2233 results.remove(i);
2234 break;
2235 }
2236 }
2237 }
2238
2239 // If the caller didn't request filter information,
2240 // drop them now so we don't have to
2241 // marshall/unmarshall it.
2242 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2243 N = results.size();
2244 for (int i=0; i<N; i++) {
2245 results.get(i).filter = null;
2246 }
2247 }
2248
2249 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2250 return results;
2251 }
2252
2253 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2254 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002255 ComponentName comp = intent.getComponent();
2256 if (comp != null) {
2257 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2258 ActivityInfo ai = getReceiverInfo(comp, flags);
2259 if (ai != null) {
2260 ResolveInfo ri = new ResolveInfo();
2261 ri.activityInfo = ai;
2262 list.add(ri);
2263 }
2264 return list;
2265 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002268 String pkgName = intent.getPackage();
2269 if (pkgName == null) {
2270 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2271 resolvedType, flags);
2272 }
2273 PackageParser.Package pkg = mPackages.get(pkgName);
2274 if (pkg != null) {
2275 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2276 resolvedType, flags, pkg.receivers);
2277 }
2278 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 }
2280 }
2281
2282 public ResolveInfo resolveService(Intent intent, String resolvedType,
2283 int flags) {
2284 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2285 flags);
2286 if (query != null) {
2287 if (query.size() >= 1) {
2288 // If there is more than one service with the same priority,
2289 // just arbitrarily pick the first one.
2290 return query.get(0);
2291 }
2292 }
2293 return null;
2294 }
2295
2296 public List<ResolveInfo> queryIntentServices(Intent intent,
2297 String resolvedType, int flags) {
2298 ComponentName comp = intent.getComponent();
2299 if (comp != null) {
2300 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2301 ServiceInfo si = getServiceInfo(comp, flags);
2302 if (si != null) {
2303 ResolveInfo ri = new ResolveInfo();
2304 ri.serviceInfo = si;
2305 list.add(ri);
2306 }
2307 return list;
2308 }
2309
2310 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002311 String pkgName = intent.getPackage();
2312 if (pkgName == null) {
2313 return (List<ResolveInfo>)mServices.queryIntent(intent,
2314 resolvedType, flags);
2315 }
2316 PackageParser.Package pkg = mPackages.get(pkgName);
2317 if (pkg != null) {
2318 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2319 resolvedType, flags, pkg.services);
2320 }
2321 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 }
2323 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 public List<PackageInfo> getInstalledPackages(int flags) {
2326 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2327
2328 synchronized (mPackages) {
2329 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2330 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2331 while (i.hasNext()) {
2332 final PackageSetting ps = i.next();
2333 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2334 if(psPkg != null) {
2335 finalList.add(psPkg);
2336 }
2337 }
2338 }
2339 else {
2340 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2341 while (i.hasNext()) {
2342 final PackageParser.Package p = i.next();
2343 if (p.applicationInfo != null) {
2344 PackageInfo pi = generatePackageInfo(p, flags);
2345 if(pi != null) {
2346 finalList.add(pi);
2347 }
2348 }
2349 }
2350 }
2351 }
2352 return finalList;
2353 }
2354
2355 public List<ApplicationInfo> getInstalledApplications(int flags) {
2356 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2357 synchronized(mPackages) {
2358 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2359 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2360 while (i.hasNext()) {
2361 final PackageSetting ps = i.next();
2362 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2363 if(ai != null) {
2364 finalList.add(ai);
2365 }
2366 }
2367 }
2368 else {
2369 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2370 while (i.hasNext()) {
2371 final PackageParser.Package p = i.next();
2372 if (p.applicationInfo != null) {
2373 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2374 if(ai != null) {
2375 finalList.add(ai);
2376 }
2377 }
2378 }
2379 }
2380 }
2381 return finalList;
2382 }
2383
2384 public List<ApplicationInfo> getPersistentApplications(int flags) {
2385 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2386
2387 synchronized (mPackages) {
2388 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2389 while (i.hasNext()) {
2390 PackageParser.Package p = i.next();
2391 if (p.applicationInfo != null
2392 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002393 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002394 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 }
2396 }
2397 }
2398
2399 return finalList;
2400 }
2401
2402 public ProviderInfo resolveContentProvider(String name, int flags) {
2403 synchronized (mPackages) {
2404 final PackageParser.Provider provider = mProviders.get(name);
2405 return provider != null
2406 && mSettings.isEnabledLP(provider.info, flags)
2407 && (!mSafeMode || (provider.info.applicationInfo.flags
2408 &ApplicationInfo.FLAG_SYSTEM) != 0)
2409 ? PackageParser.generateProviderInfo(provider, flags)
2410 : null;
2411 }
2412 }
2413
Fred Quintana718d8a22009-04-29 17:53:20 -07002414 /**
2415 * @deprecated
2416 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 public void querySyncProviders(List outNames, List outInfo) {
2418 synchronized (mPackages) {
2419 Iterator<Map.Entry<String, PackageParser.Provider>> i
2420 = mProviders.entrySet().iterator();
2421
2422 while (i.hasNext()) {
2423 Map.Entry<String, PackageParser.Provider> entry = i.next();
2424 PackageParser.Provider p = entry.getValue();
2425
2426 if (p.syncable
2427 && (!mSafeMode || (p.info.applicationInfo.flags
2428 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2429 outNames.add(entry.getKey());
2430 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2431 }
2432 }
2433 }
2434 }
2435
2436 public List<ProviderInfo> queryContentProviders(String processName,
2437 int uid, int flags) {
2438 ArrayList<ProviderInfo> finalList = null;
2439
2440 synchronized (mPackages) {
2441 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2442 while (i.hasNext()) {
2443 PackageParser.Provider p = i.next();
2444 if (p.info.authority != null
2445 && (processName == null ||
2446 (p.info.processName.equals(processName)
2447 && p.info.applicationInfo.uid == uid))
2448 && mSettings.isEnabledLP(p.info, flags)
2449 && (!mSafeMode || (p.info.applicationInfo.flags
2450 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2451 if (finalList == null) {
2452 finalList = new ArrayList<ProviderInfo>(3);
2453 }
2454 finalList.add(PackageParser.generateProviderInfo(p,
2455 flags));
2456 }
2457 }
2458 }
2459
2460 if (finalList != null) {
2461 Collections.sort(finalList, mProviderInitOrderSorter);
2462 }
2463
2464 return finalList;
2465 }
2466
2467 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2468 int flags) {
2469 synchronized (mPackages) {
2470 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2471 return PackageParser.generateInstrumentationInfo(i, flags);
2472 }
2473 }
2474
2475 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2476 int flags) {
2477 ArrayList<InstrumentationInfo> finalList =
2478 new ArrayList<InstrumentationInfo>();
2479
2480 synchronized (mPackages) {
2481 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2482 while (i.hasNext()) {
2483 PackageParser.Instrumentation p = i.next();
2484 if (targetPackage == null
2485 || targetPackage.equals(p.info.targetPackage)) {
2486 finalList.add(PackageParser.generateInstrumentationInfo(p,
2487 flags));
2488 }
2489 }
2490 }
2491
2492 return finalList;
2493 }
2494
2495 private void scanDirLI(File dir, int flags, int scanMode) {
2496 Log.d(TAG, "Scanning app dir " + dir);
2497
2498 String[] files = dir.list();
2499
2500 int i;
2501 for (i=0; i<files.length; i++) {
2502 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002503 if (!isPackageFilename(files[i])) {
2504 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002505 continue;
2506 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002507 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002509 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002510 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2511 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002512 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002513 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002514 file.delete();
2515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
2517 }
2518
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002519 private static File getSettingsProblemFile() {
2520 File dataDir = Environment.getDataDirectory();
2521 File systemDir = new File(dataDir, "system");
2522 File fname = new File(systemDir, "uiderrors.txt");
2523 return fname;
2524 }
2525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 private static void reportSettingsProblem(int priority, String msg) {
2527 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002528 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 FileOutputStream out = new FileOutputStream(fname, true);
2530 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002531 SimpleDateFormat formatter = new SimpleDateFormat();
2532 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2533 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 pw.close();
2535 FileUtils.setPermissions(
2536 fname.toString(),
2537 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2538 -1, -1);
2539 } catch (java.io.IOException e) {
2540 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002541 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 }
2543
2544 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2545 PackageParser.Package pkg, File srcFile, int parseFlags) {
2546 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002547 if (ps != null
2548 && ps.codePath.equals(srcFile)
2549 && ps.getTimeStamp() == srcFile.lastModified()) {
2550 if (ps.signatures.mSignatures != null
2551 && ps.signatures.mSignatures.length != 0) {
2552 // Optimization: reuse the existing cached certificates
2553 // if the package appears to be unchanged.
2554 pkg.mSignatures = ps.signatures.mSignatures;
2555 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 }
Jeff Browne7600722010-04-07 18:28:23 -07002557
2558 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002559 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002560 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2561 }
2562
2563 if (!pp.collectCertificates(pkg, parseFlags)) {
2564 mLastScanError = pp.getParseError();
2565 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 }
2567 }
2568 return true;
2569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 /*
2572 * Scan a package and return the newly parsed package.
2573 * Returns null in case of errors and the error code is stored in mLastScanError
2574 */
2575 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002576 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002578 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002580 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002583 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 if (pkg == null) {
2585 mLastScanError = pp.getParseError();
2586 return null;
2587 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002588 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 PackageSetting updatedPkg;
2590 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002591 // Look to see if we already know about this package.
2592 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002593 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002594 // This package has been renamed to its original name. Let's
2595 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002596 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002597 }
2598 // If there was no original package, see one for the real package name.
2599 if (ps == null) {
2600 ps = mSettings.peekPackageLP(pkg.packageName);
2601 }
2602 // Check to see if this package could be hiding/updating a system
2603 // package. Must look for it either under the original or real
2604 // package name depending on our state.
2605 updatedPkg = mSettings.mDisabledSysPackages.get(
2606 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002608 // First check if this is a system package that may involve an update
2609 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002610 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002611 // The path has changed from what was last scanned... check the
2612 // version of the new path against what we have stored to determine
2613 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002614 if (pkg.mVersionCode < ps.versionCode) {
2615 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002616 // Ignore entry. Skip it.
2617 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2618 + "ignored: updated version " + ps.versionCode
2619 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002620 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2621 return null;
2622 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002623 // The current app on the system partion is better than
2624 // what we have updated to on the data partition; switch
2625 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002626 // At this point, its safely assumed that package installation for
2627 // apps in system partition will go through. If not there won't be a working
2628 // version of the app
2629 synchronized (mPackages) {
2630 // Just remove the loaded entries from package lists.
2631 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002632 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002633 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002634 + "reverting from " + ps.codePathString
2635 + ": new version " + pkg.mVersionCode
2636 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002637 InstallArgs args = new FileInstallArgs(ps.codePathString,
2638 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002639 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002640 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 }
2643 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002644 if (updatedPkg != null) {
2645 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2646 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2647 }
2648 // Verify certificates against what was last scanned
2649 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002650 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002651 return null;
2652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 // The apk is forward locked (not public) if its code and resources
2654 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002655 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002657 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002658 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002659
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002660 String codePath = null;
2661 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002662 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2663 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002664 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002665 } else {
2666 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002667 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002668 }
2669 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002670 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002671 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002672 codePath = pkg.mScanPath;
2673 // Set application objects path explicitly.
2674 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002676 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 }
2678
Kenny Root85387d72010-08-26 10:13:11 -07002679 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2680 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002681 pkg.mPath = pkg.mScanPath = destCodePath;
2682 pkg.applicationInfo.sourceDir = destCodePath;
2683 pkg.applicationInfo.publicSourceDir = destResPath;
2684 }
2685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 private static String fixProcessName(String defProcessName,
2687 String processName, int uid) {
2688 if (processName == null) {
2689 return defProcessName;
2690 }
2691 return processName;
2692 }
2693
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002694 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002695 PackageParser.Package pkg) {
2696 if (pkgSetting.signatures.mSignatures != null) {
2697 // Already existing package. Make sure signatures match
2698 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2699 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002700 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002701 + " signatures do not match the previously installed version; ignoring!");
2702 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 return false;
2704 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002705 }
2706 // Check for shared user signatures
2707 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2708 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2709 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2710 Slog.e(TAG, "Package " + pkg.packageName
2711 + " has no signatures that match those in shared user "
2712 + pkgSetting.sharedUser.name + "; ignoring!");
2713 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2714 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 }
2717 return true;
2718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002719
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002720 public boolean performDexOpt(String packageName) {
2721 if (!mNoDexOpt) {
2722 return false;
2723 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002724
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002725 PackageParser.Package p;
2726 synchronized (mPackages) {
2727 p = mPackages.get(packageName);
2728 if (p == null || p.mDidDexOpt) {
2729 return false;
2730 }
2731 }
2732 synchronized (mInstallLock) {
2733 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2734 }
2735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002736
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002737 static final int DEX_OPT_SKIPPED = 0;
2738 static final int DEX_OPT_PERFORMED = 1;
2739 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002740
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002741 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2742 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002743 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002744 String path = pkg.mScanPath;
2745 int ret = 0;
2746 try {
2747 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002748 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002749 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002750 pkg.mDidDexOpt = true;
2751 performed = true;
2752 }
2753 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002754 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002755 ret = -1;
2756 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002757 Slog.w(TAG, "IOException reading apk: " + path, e);
2758 ret = -1;
2759 } catch (dalvik.system.StaleDexCacheError e) {
2760 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2761 ret = -1;
2762 } catch (Exception e) {
2763 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002764 ret = -1;
2765 }
2766 if (ret < 0) {
2767 //error from installer
2768 return DEX_OPT_FAILED;
2769 }
2770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002771
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002772 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2773 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002774
2775 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2776 return Environment.isEncryptedFilesystemEnabled() &&
2777 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2778 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002779
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002780 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2781 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002782 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002783 + " to " + newPkg.packageName
2784 + ": old package not in system partition");
2785 return false;
2786 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002787 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002788 + " to " + newPkg.packageName
2789 + ": old package still exists");
2790 return false;
2791 }
2792 return true;
2793 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002794
2795 private File getDataPathForPackage(PackageParser.Package pkg) {
2796 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2797 File dataPath;
2798 if (useEncryptedFSDir) {
2799 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2800 } else {
2801 dataPath = new File(mAppDataDir, pkg.packageName);
2802 }
2803 return dataPath;
2804 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002805
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002806 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2807 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002808 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002809 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2810 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002811 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002812 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002813 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2814 return null;
2815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 mScanningPath = scanFile;
2817 if (pkg == null) {
2818 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2819 return null;
2820 }
2821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2823 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2824 }
2825
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002826 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 synchronized (mPackages) {
2828 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002829 Slog.w(TAG, "*************************************************");
2830 Slog.w(TAG, "Core android package being redefined. Skipping.");
2831 Slog.w(TAG, " file=" + mScanningPath);
2832 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2834 return null;
2835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 // Set up information for our fall-back user intent resolution
2838 // activity.
2839 mPlatformPackage = pkg;
2840 pkg.mVersionCode = mSdkVersion;
2841 mAndroidApplication = pkg.applicationInfo;
2842 mResolveActivity.applicationInfo = mAndroidApplication;
2843 mResolveActivity.name = ResolverActivity.class.getName();
2844 mResolveActivity.packageName = mAndroidApplication.packageName;
2845 mResolveActivity.processName = mAndroidApplication.processName;
2846 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2847 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2848 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2849 mResolveActivity.exported = true;
2850 mResolveActivity.enabled = true;
2851 mResolveInfo.activityInfo = mResolveActivity;
2852 mResolveInfo.priority = 0;
2853 mResolveInfo.preferredOrder = 0;
2854 mResolveInfo.match = 0;
2855 mResolveComponentName = new ComponentName(
2856 mAndroidApplication.packageName, mResolveActivity.name);
2857 }
2858 }
2859
2860 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002861 TAG, "Scanning package " + pkg.packageName);
2862 if (mPackages.containsKey(pkg.packageName)
2863 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002864 Slog.w(TAG, "*************************************************");
2865 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002867 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2869 return null;
2870 }
2871
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002872 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002873 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2874 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 SharedUserSetting suid = null;
2877 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002878
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002879 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2880 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002881 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002882 pkg.mRealPackage = null;
2883 pkg.mAdoptPermissions = null;
2884 }
2885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 synchronized (mPackages) {
2887 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002888 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2889 if (mTmpSharedLibraries == null ||
2890 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2891 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2892 }
2893 int num = 0;
2894 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2895 for (int i=0; i<N; i++) {
2896 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002898 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002900 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2902 return null;
2903 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002904 mTmpSharedLibraries[num] = file;
2905 num++;
2906 }
2907 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2908 for (int i=0; i<N; i++) {
2909 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2910 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002911 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002912 + " desires unavailable shared library "
2913 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2914 } else {
2915 mTmpSharedLibraries[num] = file;
2916 num++;
2917 }
2918 }
2919 if (num > 0) {
2920 pkg.usesLibraryFiles = new String[num];
2921 System.arraycopy(mTmpSharedLibraries, 0,
2922 pkg.usesLibraryFiles, 0, num);
2923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002924
Dianne Hackborn49237342009-08-27 20:08:01 -07002925 if (pkg.reqFeatures != null) {
2926 N = pkg.reqFeatures.size();
2927 for (int i=0; i<N; i++) {
2928 FeatureInfo fi = pkg.reqFeatures.get(i);
2929 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2930 // Don't care.
2931 continue;
2932 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002933
Dianne Hackborn49237342009-08-27 20:08:01 -07002934 if (fi.name != null) {
2935 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002936 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002937 + " requires unavailable feature "
2938 + fi.name + "; failing!");
2939 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2940 return null;
2941 }
2942 }
2943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 }
2945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 if (pkg.mSharedUserId != null) {
2948 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2949 pkg.applicationInfo.flags, true);
2950 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002951 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 + " for shared user failed");
2953 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2954 return null;
2955 }
2956 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2957 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2958 + suid.userId + "): packages=" + suid.packages);
2959 }
2960 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002961
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002962 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002963 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002964 Log.w(TAG, "WAITING FOR DEBUGGER");
2965 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002966 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2967 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002968 }
2969 }
2970
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002971 // Check if we are renaming from an original package name.
2972 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002973 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002974 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002975 // This package may need to be renamed to a previously
2976 // installed name. Let's check on that...
2977 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002978 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002979 // This package had originally been installed as the
2980 // original name, and we have already taken care of
2981 // transitioning to the new one. Just update the new
2982 // one to continue using the old name.
2983 realName = pkg.mRealPackage;
2984 if (!pkg.packageName.equals(renamed)) {
2985 // Callers into this function may have already taken
2986 // care of renaming the package; only do it here if
2987 // it is not already done.
2988 pkg.setPackageName(renamed);
2989 }
2990
Dianne Hackbornc1552392010-03-03 16:19:01 -08002991 } else {
2992 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2993 if ((origPackage=mSettings.peekPackageLP(
2994 pkg.mOriginalPackages.get(i))) != null) {
2995 // We do have the package already installed under its
2996 // original name... should we use it?
2997 if (!verifyPackageUpdate(origPackage, pkg)) {
2998 // New package is not compatible with original.
2999 origPackage = null;
3000 continue;
3001 } else if (origPackage.sharedUser != null) {
3002 // Make sure uid is compatible between packages.
3003 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003004 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003005 + " to " + pkg.packageName + ": old uid "
3006 + origPackage.sharedUser.name
3007 + " differs from " + pkg.mSharedUserId);
3008 origPackage = null;
3009 continue;
3010 }
3011 } else {
3012 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3013 + pkg.packageName + " to old name " + origPackage.name);
3014 }
3015 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003016 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003017 }
3018 }
3019 }
3020
3021 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003022 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003023 + " was transferred to another, but its .apk remains");
3024 }
3025
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003026 // Just create the setting, don't add it yet. For already existing packages
3027 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003028 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003029 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3030 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003032 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3034 return null;
3035 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003036
3037 if (pkgSetting.origPackage != null) {
3038 // If we are first transitioning from an original package,
3039 // fix up the new package's name now. We need to do this after
3040 // looking up the package under its new name, so getPackageLP
3041 // can take care of fiddling things correctly.
3042 pkg.setPackageName(origPackage.name);
3043
3044 // File a report about this.
3045 String msg = "New package " + pkgSetting.realName
3046 + " renamed to replace old package " + pkgSetting.name;
3047 reportSettingsProblem(Log.WARN, msg);
3048
3049 // Make a note of it.
3050 mTransferedPackages.add(origPackage.name);
3051
3052 // No longer need to retain this.
3053 pkgSetting.origPackage = null;
3054 }
3055
3056 if (realName != null) {
3057 // Make a note of it.
3058 mTransferedPackages.add(pkg.packageName);
3059 }
3060
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003061 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 pkg.applicationInfo.uid = pkgSetting.userId;
3066 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003067
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003068 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003069 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 return null;
3071 }
3072 // The signature has changed, but this package is in the system
3073 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003074 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 // However... if this package is part of a shared user, but it
3076 // doesn't match the signature of the shared user, let's fail.
3077 // What this means is that you can't change the signatures
3078 // associated with an overall shared user, which doesn't seem all
3079 // that unreasonable.
3080 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003081 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3082 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3083 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3085 return null;
3086 }
3087 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003088 // File a report about this.
3089 String msg = "System package " + pkg.packageName
3090 + " signature changed; retaining data.";
3091 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003093
The Android Open Source Project10592532009-03-18 17:39:46 -07003094 // Verify that this new package doesn't have any content providers
3095 // that conflict with existing packages. Only do this if the
3096 // package isn't already installed, since we don't want to break
3097 // things that are installed.
3098 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3099 int N = pkg.providers.size();
3100 int i;
3101 for (i=0; i<N; i++) {
3102 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003103 if (p.info.authority != null) {
3104 String names[] = p.info.authority.split(";");
3105 for (int j = 0; j < names.length; j++) {
3106 if (mProviders.containsKey(names[j])) {
3107 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003108 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003109 " (in package " + pkg.applicationInfo.packageName +
3110 ") is already used by "
3111 + ((other != null && other.getComponentName() != null)
3112 ? other.getComponentName().getPackageName() : "?"));
3113 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3114 return null;
3115 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003116 }
3117 }
3118 }
3119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 }
3121
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003122 final String pkgName = pkg.packageName;
3123
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003124 if (pkg.mAdoptPermissions != null) {
3125 // This package wants to adopt ownership of permissions from
3126 // another package.
3127 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3128 String origName = pkg.mAdoptPermissions.get(i);
3129 PackageSetting orig = mSettings.peekPackageLP(origName);
3130 if (orig != null) {
3131 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003132 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003133 + origName + " to " + pkg.packageName);
3134 mSettings.transferPermissions(origName, pkg.packageName);
3135 }
3136 }
3137 }
3138 }
3139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 long scanFileTime = scanFile.lastModified();
3141 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3142 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3143 pkg.applicationInfo.processName = fixProcessName(
3144 pkg.applicationInfo.packageName,
3145 pkg.applicationInfo.processName,
3146 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147
3148 File dataPath;
3149 if (mPlatformPackage == pkg) {
3150 // The system package is special.
3151 dataPath = new File (Environment.getDataDirectory(), "system");
3152 pkg.applicationInfo.dataDir = dataPath.getPath();
3153 } else {
3154 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003155 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003156 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003157
3158 boolean uidError = false;
3159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 if (dataPath.exists()) {
3161 mOutPermissions[1] = 0;
3162 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003163
3164 // If we have mismatched owners for the data path, we have a
3165 // problem (unless we're running in the simulator.)
3166 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 boolean recovered = false;
3168 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3169 // If this is a system app, we can at least delete its
3170 // current data so the application will still work.
3171 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003172 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003173 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 // Old data gone!
3175 String msg = "System package " + pkg.packageName
3176 + " has changed from uid: "
3177 + mOutPermissions[1] + " to "
3178 + pkg.applicationInfo.uid + "; old data erased";
3179 reportSettingsProblem(Log.WARN, msg);
3180 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003183 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 pkg.applicationInfo.uid);
3185 if (ret == -1) {
3186 // Ack should not happen!
3187 msg = "System package " + pkg.packageName
3188 + " could not have data directory re-created after delete.";
3189 reportSettingsProblem(Log.WARN, msg);
3190 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3191 return null;
3192 }
3193 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 if (!recovered) {
3196 mHasSystemUidErrors = true;
3197 }
3198 }
3199 if (!recovered) {
3200 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3201 + pkg.applicationInfo.uid + "/fs_"
3202 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003203 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 String msg = "Package " + pkg.packageName
3205 + " has mismatched uid: "
3206 + mOutPermissions[1] + " on disk, "
3207 + pkg.applicationInfo.uid + " in settings";
3208 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003209 mSettings.mReadMessages.append(msg);
3210 mSettings.mReadMessages.append('\n');
3211 uidError = true;
3212 if (!pkgSetting.uidError) {
3213 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 }
3216 }
3217 }
3218 pkg.applicationInfo.dataDir = dataPath.getPath();
3219 } else {
3220 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3221 Log.v(TAG, "Want this data dir: " + dataPath);
3222 //invoke installer to do the actual installation
3223 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003224 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 pkg.applicationInfo.uid);
3226 if(ret < 0) {
3227 // Error from installer
3228 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3229 return null;
3230 }
3231 } else {
3232 dataPath.mkdirs();
3233 if (dataPath.exists()) {
3234 FileUtils.setPermissions(
3235 dataPath.toString(),
3236 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3237 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3238 }
3239 }
3240 if (dataPath.exists()) {
3241 pkg.applicationInfo.dataDir = dataPath.getPath();
3242 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003243 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 pkg.applicationInfo.dataDir = null;
3245 }
3246 }
Kenny Root85387d72010-08-26 10:13:11 -07003247
Kenny Root806cc132010-09-12 08:34:19 -07003248 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3249
Kenny Root85387d72010-08-26 10:13:11 -07003250 /*
3251 * Set the data dir to the default "/data/data/<package name>/lib"
3252 * if we got here without anyone telling us different (e.g., apps
3253 * stored on SD card have their native libraries stored in the ASEC
3254 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003255 *
3256 * This happens during an upgrade from a package settings file that
3257 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003258 */
Kenny Root806cc132010-09-12 08:34:19 -07003259 if (pkgSetting.nativeLibraryPathString == null && pkg.applicationInfo.dataDir != null) {
3260 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3261 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3262 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
Kenny Root85387d72010-08-26 10:13:11 -07003263 }
3264
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003265 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 }
3267
Kenny Root85387d72010-08-26 10:13:11 -07003268 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 if (mInstaller != null) {
3270 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003271 /* Note: We don't want to unpack the native binaries for
3272 * system applications, unless they have been updated
3273 * (the binaries are already under /system/lib).
3274 * Also, don't unpack libs for apps on the external card
3275 * since they should have their libraries in the ASEC
3276 * container already.
3277 *
3278 * In other words, we're going to unpack the binaries
3279 * only for non-system apps and system app upgrades.
3280 */
3281 if ((!isSystemApp(pkg) || isUpdatedSystemApp(pkg)) && !isExternal(pkg)) {
3282 Log.i(TAG, path + " changed; unpacking");
3283 File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
Kenny Root85387d72010-08-26 10:13:11 -07003284 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003286 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003287
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003288 if ((scanMode&SCAN_NO_DEX) == 0) {
3289 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3291 return null;
3292 }
3293 }
3294 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 if (mFactoryTest && pkg.requestedPermissions.contains(
3297 android.Manifest.permission.FACTORY_TEST)) {
3298 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3299 }
3300
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003301 // Request the ActivityManager to kill the process(only for existing packages)
3302 // so that we do not end up in a confused state while the user is still using the older
3303 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003304 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003305 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003306 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003307 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003310 // We don't expect installation to fail beyond this point,
3311 if ((scanMode&SCAN_MONITOR) != 0) {
3312 mAppDirs.put(pkg.mPath, pkg);
3313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003315 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003317 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003318 // Make sure we don't accidentally delete its data.
3319 mSettings.mPackagesToBeCleaned.remove(pkgName);
3320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 int N = pkg.providers.size();
3322 StringBuilder r = null;
3323 int i;
3324 for (i=0; i<N; i++) {
3325 PackageParser.Provider p = pkg.providers.get(i);
3326 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3327 p.info.processName, pkg.applicationInfo.uid);
3328 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3329 p.info.name), p);
3330 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003331 if (p.info.authority != null) {
3332 String names[] = p.info.authority.split(";");
3333 p.info.authority = null;
3334 for (int j = 0; j < names.length; j++) {
3335 if (j == 1 && p.syncable) {
3336 // We only want the first authority for a provider to possibly be
3337 // syncable, so if we already added this provider using a different
3338 // authority clear the syncable flag. We copy the provider before
3339 // changing it because the mProviders object contains a reference
3340 // to a provider that we don't want to change.
3341 // Only do this for the second authority since the resulting provider
3342 // object can be the same for all future authorities for this provider.
3343 p = new PackageParser.Provider(p);
3344 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003346 if (!mProviders.containsKey(names[j])) {
3347 mProviders.put(names[j], p);
3348 if (p.info.authority == null) {
3349 p.info.authority = names[j];
3350 } else {
3351 p.info.authority = p.info.authority + ";" + names[j];
3352 }
3353 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3354 Log.d(TAG, "Registered content provider: " + names[j] +
3355 ", className = " + p.info.name +
3356 ", isSyncable = " + p.info.isSyncable);
3357 } else {
3358 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003359 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003360 " (in package " + pkg.applicationInfo.packageName +
3361 "): name already used by "
3362 + ((other != null && other.getComponentName() != null)
3363 ? other.getComponentName().getPackageName() : "?"));
3364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 }
3366 }
3367 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3368 if (r == null) {
3369 r = new StringBuilder(256);
3370 } else {
3371 r.append(' ');
3372 }
3373 r.append(p.info.name);
3374 }
3375 }
3376 if (r != null) {
3377 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3378 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 N = pkg.services.size();
3381 r = null;
3382 for (i=0; i<N; i++) {
3383 PackageParser.Service s = pkg.services.get(i);
3384 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3385 s.info.processName, pkg.applicationInfo.uid);
3386 mServices.addService(s);
3387 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3388 if (r == null) {
3389 r = new StringBuilder(256);
3390 } else {
3391 r.append(' ');
3392 }
3393 r.append(s.info.name);
3394 }
3395 }
3396 if (r != null) {
3397 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3398 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 N = pkg.receivers.size();
3401 r = null;
3402 for (i=0; i<N; i++) {
3403 PackageParser.Activity a = pkg.receivers.get(i);
3404 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3405 a.info.processName, pkg.applicationInfo.uid);
3406 mReceivers.addActivity(a, "receiver");
3407 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3408 if (r == null) {
3409 r = new StringBuilder(256);
3410 } else {
3411 r.append(' ');
3412 }
3413 r.append(a.info.name);
3414 }
3415 }
3416 if (r != null) {
3417 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3418 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 N = pkg.activities.size();
3421 r = null;
3422 for (i=0; i<N; i++) {
3423 PackageParser.Activity a = pkg.activities.get(i);
3424 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3425 a.info.processName, pkg.applicationInfo.uid);
3426 mActivities.addActivity(a, "activity");
3427 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3428 if (r == null) {
3429 r = new StringBuilder(256);
3430 } else {
3431 r.append(' ');
3432 }
3433 r.append(a.info.name);
3434 }
3435 }
3436 if (r != null) {
3437 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3438 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 N = pkg.permissionGroups.size();
3441 r = null;
3442 for (i=0; i<N; i++) {
3443 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3444 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3445 if (cur == null) {
3446 mPermissionGroups.put(pg.info.name, pg);
3447 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3448 if (r == null) {
3449 r = new StringBuilder(256);
3450 } else {
3451 r.append(' ');
3452 }
3453 r.append(pg.info.name);
3454 }
3455 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003456 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 + pg.info.packageName + " ignored: original from "
3458 + cur.info.packageName);
3459 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3460 if (r == null) {
3461 r = new StringBuilder(256);
3462 } else {
3463 r.append(' ');
3464 }
3465 r.append("DUP:");
3466 r.append(pg.info.name);
3467 }
3468 }
3469 }
3470 if (r != null) {
3471 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 N = pkg.permissions.size();
3475 r = null;
3476 for (i=0; i<N; i++) {
3477 PackageParser.Permission p = pkg.permissions.get(i);
3478 HashMap<String, BasePermission> permissionMap =
3479 p.tree ? mSettings.mPermissionTrees
3480 : mSettings.mPermissions;
3481 p.group = mPermissionGroups.get(p.info.group);
3482 if (p.info.group == null || p.group != null) {
3483 BasePermission bp = permissionMap.get(p.info.name);
3484 if (bp == null) {
3485 bp = new BasePermission(p.info.name, p.info.packageName,
3486 BasePermission.TYPE_NORMAL);
3487 permissionMap.put(p.info.name, bp);
3488 }
3489 if (bp.perm == null) {
3490 if (bp.sourcePackage == null
3491 || bp.sourcePackage.equals(p.info.packageName)) {
3492 BasePermission tree = findPermissionTreeLP(p.info.name);
3493 if (tree == null
3494 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003495 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 bp.perm = p;
3497 bp.uid = pkg.applicationInfo.uid;
3498 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3499 if (r == null) {
3500 r = new StringBuilder(256);
3501 } else {
3502 r.append(' ');
3503 }
3504 r.append(p.info.name);
3505 }
3506 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003507 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003508 + p.info.packageName + " ignored: base tree "
3509 + tree.name + " is from package "
3510 + tree.sourcePackage);
3511 }
3512 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003513 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003514 + p.info.packageName + " ignored: original from "
3515 + bp.sourcePackage);
3516 }
3517 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3518 if (r == null) {
3519 r = new StringBuilder(256);
3520 } else {
3521 r.append(' ');
3522 }
3523 r.append("DUP:");
3524 r.append(p.info.name);
3525 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003526 if (bp.perm == p) {
3527 bp.protectionLevel = p.info.protectionLevel;
3528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003530 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 + p.info.packageName + " ignored: no group "
3532 + p.group);
3533 }
3534 }
3535 if (r != null) {
3536 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3537 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 N = pkg.instrumentation.size();
3540 r = null;
3541 for (i=0; i<N; i++) {
3542 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3543 a.info.packageName = pkg.applicationInfo.packageName;
3544 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3545 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3546 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003547 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003548 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3550 if (r == null) {
3551 r = new StringBuilder(256);
3552 } else {
3553 r.append(' ');
3554 }
3555 r.append(a.info.name);
3556 }
3557 }
3558 if (r != null) {
3559 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3560 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003561
Dianne Hackborn854060af2009-07-09 18:14:31 -07003562 if (pkg.protectedBroadcasts != null) {
3563 N = pkg.protectedBroadcasts.size();
3564 for (i=0; i<N; i++) {
3565 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3566 }
3567 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569 pkgSetting.setTimeStamp(scanFileTime);
3570 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003572 return pkg;
3573 }
3574
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003575 private void killApplication(String pkgName, int uid) {
3576 // Request the ActivityManager to kill the process(only for existing packages)
3577 // so that we do not end up in a confused state while the user is still using the older
3578 // version of the application while the new one gets installed.
3579 IActivityManager am = ActivityManagerNative.getDefault();
3580 if (am != null) {
3581 try {
3582 am.killApplicationWithUid(pkgName, uid);
3583 } catch (RemoteException e) {
3584 }
3585 }
3586 }
3587
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003588 // Return the path of the directory that will contain the native binaries
3589 // of a given installed package. This is relative to the data path.
3590 //
Kenny Root85387d72010-08-26 10:13:11 -07003591 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3592 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3593 if (nativeLibraryDir != null) {
3594 return new File(nativeLibraryDir);
3595 } else {
3596 // Fall back for old packages
3597 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3598 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003599 }
3600
Kenny Root85387d72010-08-26 10:13:11 -07003601 // Convenience call for removeNativeBinariesLI(File)
3602 private void removeNativeBinariesLI(PackageParser.Package pkg) {
3603 File nativeLibraryDir = getNativeBinaryDirForPackage(pkg);
3604 removeNativeBinariesLI(nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003605 }
3606
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003607 // Remove the native binaries of a given package. This simply
3608 // gets rid of the files in the 'lib' sub-directory.
Kenny Root85387d72010-08-26 10:13:11 -07003609 public void removeNativeBinariesLI(File binaryDir) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003610 if (DEBUG_NATIVE) {
Kenny Root85387d72010-08-26 10:13:11 -07003611 Slog.w(TAG, "Deleting native binaries from: " + binaryDir.getPath());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003612 }
3613
3614 // Just remove any file in the directory. Since the directory
3615 // is owned by the 'system' UID, the application is not supposed
3616 // to have written anything there.
3617 //
3618 if (binaryDir.exists()) {
Kenny Root85387d72010-08-26 10:13:11 -07003619 File[] binaries = binaryDir.listFiles();
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003620 if (binaries != null) {
Kenny Root85387d72010-08-26 10:13:11 -07003621 for (int nn = 0; nn < binaries.length; nn++) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003622 if (DEBUG_NATIVE) {
Kenny Root85387d72010-08-26 10:13:11 -07003623 Slog.d(TAG, " Deleting " + binaries[nn].getName());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003624 }
3625 if (!binaries[nn].delete()) {
Kenny Root85387d72010-08-26 10:13:11 -07003626 Slog.w(TAG, "Could not delete native binary: " + binaries[nn].getPath());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003627 }
3628 }
3629 }
3630 // Do not delete 'lib' directory itself, or this will prevent
3631 // installation of future updates.
3632 }
3633 }
3634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3636 if (chatty && Config.LOGD) Log.d(
3637 TAG, "Removing package " + pkg.applicationInfo.packageName );
3638
3639 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642 mPackages.remove(pkg.applicationInfo.packageName);
3643 if (pkg.mPath != null) {
3644 mAppDirs.remove(pkg.mPath);
3645 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 PackageSetting ps = (PackageSetting)pkg.mExtras;
3648 if (ps != null && ps.sharedUser != null) {
3649 // XXX don't do this until the data is removed.
3650 if (false) {
3651 ps.sharedUser.packages.remove(ps);
3652 if (ps.sharedUser.packages.size() == 0) {
3653 // Remove.
3654 }
3655 }
3656 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 int N = pkg.providers.size();
3659 StringBuilder r = null;
3660 int i;
3661 for (i=0; i<N; i++) {
3662 PackageParser.Provider p = pkg.providers.get(i);
3663 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3664 p.info.name));
3665 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 /* The is another ContentProvider with this authority when
3668 * this app was installed so this authority is null,
3669 * Ignore it as we don't have to unregister the provider.
3670 */
3671 continue;
3672 }
3673 String names[] = p.info.authority.split(";");
3674 for (int j = 0; j < names.length; j++) {
3675 if (mProviders.get(names[j]) == p) {
3676 mProviders.remove(names[j]);
3677 if (chatty && Config.LOGD) Log.d(
3678 TAG, "Unregistered content provider: " + names[j] +
3679 ", className = " + p.info.name +
3680 ", isSyncable = " + p.info.isSyncable);
3681 }
3682 }
3683 if (chatty) {
3684 if (r == null) {
3685 r = new StringBuilder(256);
3686 } else {
3687 r.append(' ');
3688 }
3689 r.append(p.info.name);
3690 }
3691 }
3692 if (r != null) {
3693 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3694 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 N = pkg.services.size();
3697 r = null;
3698 for (i=0; i<N; i++) {
3699 PackageParser.Service s = pkg.services.get(i);
3700 mServices.removeService(s);
3701 if (chatty) {
3702 if (r == null) {
3703 r = new StringBuilder(256);
3704 } else {
3705 r.append(' ');
3706 }
3707 r.append(s.info.name);
3708 }
3709 }
3710 if (r != null) {
3711 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 N = pkg.receivers.size();
3715 r = null;
3716 for (i=0; i<N; i++) {
3717 PackageParser.Activity a = pkg.receivers.get(i);
3718 mReceivers.removeActivity(a, "receiver");
3719 if (chatty) {
3720 if (r == null) {
3721 r = new StringBuilder(256);
3722 } else {
3723 r.append(' ');
3724 }
3725 r.append(a.info.name);
3726 }
3727 }
3728 if (r != null) {
3729 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3730 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 N = pkg.activities.size();
3733 r = null;
3734 for (i=0; i<N; i++) {
3735 PackageParser.Activity a = pkg.activities.get(i);
3736 mActivities.removeActivity(a, "activity");
3737 if (chatty) {
3738 if (r == null) {
3739 r = new StringBuilder(256);
3740 } else {
3741 r.append(' ');
3742 }
3743 r.append(a.info.name);
3744 }
3745 }
3746 if (r != null) {
3747 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3748 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750 N = pkg.permissions.size();
3751 r = null;
3752 for (i=0; i<N; i++) {
3753 PackageParser.Permission p = pkg.permissions.get(i);
3754 boolean tree = false;
3755 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3756 if (bp == null) {
3757 tree = true;
3758 bp = mSettings.mPermissionTrees.get(p.info.name);
3759 }
3760 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003761 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 if (chatty) {
3763 if (r == null) {
3764 r = new StringBuilder(256);
3765 } else {
3766 r.append(' ');
3767 }
3768 r.append(p.info.name);
3769 }
3770 }
3771 }
3772 if (r != null) {
3773 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3774 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 N = pkg.instrumentation.size();
3777 r = null;
3778 for (i=0; i<N; i++) {
3779 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003780 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 if (chatty) {
3782 if (r == null) {
3783 r = new StringBuilder(256);
3784 } else {
3785 r.append(' ');
3786 }
3787 r.append(a.info.name);
3788 }
3789 }
3790 if (r != null) {
3791 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3792 }
3793 }
3794 }
3795
3796 private static final boolean isPackageFilename(String name) {
3797 return name != null && name.endsWith(".apk");
3798 }
3799
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003800 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3801 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3802 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3803 return true;
3804 }
3805 }
3806 return false;
3807 }
3808
3809 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003810 PackageParser.Package pkgInfo, boolean grantPermissions,
3811 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 // Make sure there are no dangling permission trees.
3813 Iterator<BasePermission> it = mSettings.mPermissionTrees
3814 .values().iterator();
3815 while (it.hasNext()) {
3816 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003817 if (bp.packageSetting == null) {
3818 // We may not yet have parsed the package, so just see if
3819 // we still know about its settings.
3820 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3821 }
3822 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003823 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003824 + " from package " + bp.sourcePackage);
3825 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003826 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3827 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3828 Slog.i(TAG, "Removing old permission tree: " + bp.name
3829 + " from package " + bp.sourcePackage);
3830 grantPermissions = true;
3831 it.remove();
3832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 }
3834 }
3835
3836 // Make sure all dynamic permissions have been assigned to a package,
3837 // and make sure there are no dangling permissions.
3838 it = mSettings.mPermissions.values().iterator();
3839 while (it.hasNext()) {
3840 BasePermission bp = it.next();
3841 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3842 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3843 + bp.name + " pkg=" + bp.sourcePackage
3844 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003845 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 BasePermission tree = findPermissionTreeLP(bp.name);
3847 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003848 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 bp.perm = new PackageParser.Permission(tree.perm.owner,
3850 new PermissionInfo(bp.pendingInfo));
3851 bp.perm.info.packageName = tree.perm.info.packageName;
3852 bp.perm.info.name = bp.name;
3853 bp.uid = tree.uid;
3854 }
3855 }
3856 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003857 if (bp.packageSetting == null) {
3858 // We may not yet have parsed the package, so just see if
3859 // we still know about its settings.
3860 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3861 }
3862 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003863 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 + " from package " + bp.sourcePackage);
3865 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003866 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3867 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3868 Slog.i(TAG, "Removing old permission: " + bp.name
3869 + " from package " + bp.sourcePackage);
3870 grantPermissions = true;
3871 it.remove();
3872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 }
3874 }
3875
3876 // Now update the permissions for all packages, in particular
3877 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003878 if (grantPermissions) {
3879 for (PackageParser.Package pkg : mPackages.values()) {
3880 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003881 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003882 }
3883 }
3884 }
3885
3886 if (pkgInfo != null) {
3887 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 }
3889 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3892 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3893 if (ps == null) {
3894 return;
3895 }
3896 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003897 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 if (replace) {
3900 ps.permissionsFixed = false;
3901 if (gp == ps) {
3902 gp.grantedPermissions.clear();
3903 gp.gids = mGlobalGids;
3904 }
3905 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 if (gp.gids == null) {
3908 gp.gids = mGlobalGids;
3909 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 final int N = pkg.requestedPermissions.size();
3912 for (int i=0; i<N; i++) {
3913 String name = pkg.requestedPermissions.get(i);
3914 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 if (false) {
3916 if (gp != ps) {
3917 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003918 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 }
3920 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003921 if (bp != null && bp.packageSetting != null) {
3922 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003923 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003924 boolean allowedSig = false;
3925 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3926 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003928 } else if (bp.packageSetting == null) {
3929 // This permission is invalid; skip it.
3930 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003931 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3932 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3933 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003935 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003937 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003938 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 // For updated system applications, the signatureOrSystem permission
3940 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003941 if (isUpdatedSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3943 if(sysPs.grantedPermissions.contains(perm)) {
3944 allowed = true;
3945 } else {
3946 allowed = false;
3947 }
3948 } else {
3949 allowed = true;
3950 }
3951 }
3952 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003953 if (allowed) {
3954 allowedSig = true;
3955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 } else {
3957 allowed = false;
3958 }
3959 if (false) {
3960 if (gp != ps) {
3961 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3962 }
3963 }
3964 if (allowed) {
3965 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3966 && ps.permissionsFixed) {
3967 // If this is an existing, non-system package, then
3968 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003969 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003971 // Except... if this is a permission that was added
3972 // to the platform (note: need to only do this when
3973 // updating the platform).
3974 final int NP = PackageParser.NEW_PERMISSIONS.length;
3975 for (int ip=0; ip<NP; ip++) {
3976 final PackageParser.NewPermissionInfo npi
3977 = PackageParser.NEW_PERMISSIONS[ip];
3978 if (npi.name.equals(perm)
3979 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3980 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003981 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003982 + pkg.packageName);
3983 break;
3984 }
3985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 }
3987 }
3988 if (allowed) {
3989 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003990 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 gp.grantedPermissions.add(perm);
3992 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003993 } else if (!ps.haveGids) {
3994 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 }
3996 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003997 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 + " to package " + pkg.packageName
3999 + " because it was previously installed without");
4000 }
4001 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004002 if (gp.grantedPermissions.remove(perm)) {
4003 changedPermission = true;
4004 gp.gids = removeInts(gp.gids, bp.gids);
4005 Slog.i(TAG, "Un-granting permission " + perm
4006 + " from package " + pkg.packageName
4007 + " (protectionLevel=" + bp.protectionLevel
4008 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4009 + ")");
4010 } else {
4011 Slog.w(TAG, "Not granting permission " + perm
4012 + " to package " + pkg.packageName
4013 + " (protectionLevel=" + bp.protectionLevel
4014 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4015 + ")");
4016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 }
4018 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004019 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 + " in package " + pkg.packageName);
4021 }
4022 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004023
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004024 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004025 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4026 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 // This is the first that we have heard about this package, so the
4028 // permissions we have now selected are fixed until explicitly
4029 // changed.
4030 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004032 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 private final class ActivityIntentResolver
4036 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004037 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004039 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 }
4041
Mihai Preda074edef2009-05-18 17:13:31 +02004042 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004044 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4046 }
4047
Mihai Predaeae850c2009-05-13 10:13:48 +02004048 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4049 ArrayList<PackageParser.Activity> packageActivities) {
4050 if (packageActivities == null) {
4051 return null;
4052 }
4053 mFlags = flags;
4054 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4055 int N = packageActivities.size();
4056 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4057 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004058
4059 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004060 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004061 intentFilters = packageActivities.get(i).intents;
4062 if (intentFilters != null && intentFilters.size() > 0) {
4063 listCut.add(intentFilters);
4064 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004065 }
4066 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4067 }
4068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004069 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004070 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 if (SHOW_INFO || Config.LOGV) Log.v(
4072 TAG, " " + type + " " +
4073 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4074 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4075 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004076 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4078 if (SHOW_INFO || Config.LOGV) {
4079 Log.v(TAG, " IntentFilter:");
4080 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4081 }
4082 if (!intent.debugCheck()) {
4083 Log.w(TAG, "==> For Activity " + a.info.name);
4084 }
4085 addFilter(intent);
4086 }
4087 }
4088
4089 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004090 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 if (SHOW_INFO || Config.LOGV) Log.v(
4092 TAG, " " + type + " " +
4093 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4094 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4095 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004096 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4098 if (SHOW_INFO || Config.LOGV) {
4099 Log.v(TAG, " IntentFilter:");
4100 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4101 }
4102 removeFilter(intent);
4103 }
4104 }
4105
4106 @Override
4107 protected boolean allowFilterResult(
4108 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4109 ActivityInfo filterAi = filter.activity.info;
4110 for (int i=dest.size()-1; i>=0; i--) {
4111 ActivityInfo destAi = dest.get(i).activityInfo;
4112 if (destAi.name == filterAi.name
4113 && destAi.packageName == filterAi.packageName) {
4114 return false;
4115 }
4116 }
4117 return true;
4118 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004121 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4122 return info.activity.owner.packageName;
4123 }
4124
4125 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4127 int match) {
4128 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4129 return null;
4130 }
4131 final PackageParser.Activity activity = info.activity;
4132 if (mSafeMode && (activity.info.applicationInfo.flags
4133 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4134 return null;
4135 }
4136 final ResolveInfo res = new ResolveInfo();
4137 res.activityInfo = PackageParser.generateActivityInfo(activity,
4138 mFlags);
4139 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4140 res.filter = info;
4141 }
4142 res.priority = info.getPriority();
4143 res.preferredOrder = activity.owner.mPreferredOrder;
4144 //System.out.println("Result: " + res.activityInfo.className +
4145 // " = " + res.priority);
4146 res.match = match;
4147 res.isDefault = info.hasDefault;
4148 res.labelRes = info.labelRes;
4149 res.nonLocalizedLabel = info.nonLocalizedLabel;
4150 res.icon = info.icon;
4151 return res;
4152 }
4153
4154 @Override
4155 protected void sortResults(List<ResolveInfo> results) {
4156 Collections.sort(results, mResolvePrioritySorter);
4157 }
4158
4159 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004160 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004161 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004162 out.print(prefix); out.print(
4163 Integer.toHexString(System.identityHashCode(filter.activity)));
4164 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004165 out.print(filter.activity.getComponentShortName());
4166 out.print(" filter ");
4167 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168 }
4169
4170// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4171// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4172// final List<ResolveInfo> retList = Lists.newArrayList();
4173// while (i.hasNext()) {
4174// final ResolveInfo resolveInfo = i.next();
4175// if (isEnabledLP(resolveInfo.activityInfo)) {
4176// retList.add(resolveInfo);
4177// }
4178// }
4179// return retList;
4180// }
4181
4182 // Keys are String (activity class name), values are Activity.
4183 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4184 = new HashMap<ComponentName, PackageParser.Activity>();
4185 private int mFlags;
4186 }
4187
4188 private final class ServiceIntentResolver
4189 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004190 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004192 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193 }
4194
Mihai Preda074edef2009-05-18 17:13:31 +02004195 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004197 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004198 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4199 }
4200
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004201 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4202 ArrayList<PackageParser.Service> packageServices) {
4203 if (packageServices == null) {
4204 return null;
4205 }
4206 mFlags = flags;
4207 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4208 int N = packageServices.size();
4209 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4210 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4211
4212 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4213 for (int i = 0; i < N; ++i) {
4214 intentFilters = packageServices.get(i).intents;
4215 if (intentFilters != null && intentFilters.size() > 0) {
4216 listCut.add(intentFilters);
4217 }
4218 }
4219 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4220 }
4221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004222 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004223 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 if (SHOW_INFO || Config.LOGV) Log.v(
4225 TAG, " " + (s.info.nonLocalizedLabel != null
4226 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4227 if (SHOW_INFO || Config.LOGV) Log.v(
4228 TAG, " Class=" + s.info.name);
4229 int NI = s.intents.size();
4230 int j;
4231 for (j=0; j<NI; j++) {
4232 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4233 if (SHOW_INFO || Config.LOGV) {
4234 Log.v(TAG, " IntentFilter:");
4235 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4236 }
4237 if (!intent.debugCheck()) {
4238 Log.w(TAG, "==> For Service " + s.info.name);
4239 }
4240 addFilter(intent);
4241 }
4242 }
4243
4244 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004245 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246 if (SHOW_INFO || Config.LOGV) Log.v(
4247 TAG, " " + (s.info.nonLocalizedLabel != null
4248 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4249 if (SHOW_INFO || Config.LOGV) Log.v(
4250 TAG, " Class=" + s.info.name);
4251 int NI = s.intents.size();
4252 int j;
4253 for (j=0; j<NI; j++) {
4254 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4255 if (SHOW_INFO || Config.LOGV) {
4256 Log.v(TAG, " IntentFilter:");
4257 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4258 }
4259 removeFilter(intent);
4260 }
4261 }
4262
4263 @Override
4264 protected boolean allowFilterResult(
4265 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4266 ServiceInfo filterSi = filter.service.info;
4267 for (int i=dest.size()-1; i>=0; i--) {
4268 ServiceInfo destAi = dest.get(i).serviceInfo;
4269 if (destAi.name == filterSi.name
4270 && destAi.packageName == filterSi.packageName) {
4271 return false;
4272 }
4273 }
4274 return true;
4275 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004278 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4279 return info.service.owner.packageName;
4280 }
4281
4282 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4284 int match) {
4285 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4286 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4287 return null;
4288 }
4289 final PackageParser.Service service = info.service;
4290 if (mSafeMode && (service.info.applicationInfo.flags
4291 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4292 return null;
4293 }
4294 final ResolveInfo res = new ResolveInfo();
4295 res.serviceInfo = PackageParser.generateServiceInfo(service,
4296 mFlags);
4297 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4298 res.filter = filter;
4299 }
4300 res.priority = info.getPriority();
4301 res.preferredOrder = service.owner.mPreferredOrder;
4302 //System.out.println("Result: " + res.activityInfo.className +
4303 // " = " + res.priority);
4304 res.match = match;
4305 res.isDefault = info.hasDefault;
4306 res.labelRes = info.labelRes;
4307 res.nonLocalizedLabel = info.nonLocalizedLabel;
4308 res.icon = info.icon;
4309 return res;
4310 }
4311
4312 @Override
4313 protected void sortResults(List<ResolveInfo> results) {
4314 Collections.sort(results, mResolvePrioritySorter);
4315 }
4316
4317 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004318 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004320 out.print(prefix); out.print(
4321 Integer.toHexString(System.identityHashCode(filter.service)));
4322 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004323 out.print(filter.service.getComponentShortName());
4324 out.print(" filter ");
4325 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 }
4327
4328// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4329// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4330// final List<ResolveInfo> retList = Lists.newArrayList();
4331// while (i.hasNext()) {
4332// final ResolveInfo resolveInfo = (ResolveInfo) i;
4333// if (isEnabledLP(resolveInfo.serviceInfo)) {
4334// retList.add(resolveInfo);
4335// }
4336// }
4337// return retList;
4338// }
4339
4340 // Keys are String (activity class name), values are Activity.
4341 private final HashMap<ComponentName, PackageParser.Service> mServices
4342 = new HashMap<ComponentName, PackageParser.Service>();
4343 private int mFlags;
4344 };
4345
4346 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4347 new Comparator<ResolveInfo>() {
4348 public int compare(ResolveInfo r1, ResolveInfo r2) {
4349 int v1 = r1.priority;
4350 int v2 = r2.priority;
4351 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4352 if (v1 != v2) {
4353 return (v1 > v2) ? -1 : 1;
4354 }
4355 v1 = r1.preferredOrder;
4356 v2 = r2.preferredOrder;
4357 if (v1 != v2) {
4358 return (v1 > v2) ? -1 : 1;
4359 }
4360 if (r1.isDefault != r2.isDefault) {
4361 return r1.isDefault ? -1 : 1;
4362 }
4363 v1 = r1.match;
4364 v2 = r2.match;
4365 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4366 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4367 }
4368 };
4369
4370 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4371 new Comparator<ProviderInfo>() {
4372 public int compare(ProviderInfo p1, ProviderInfo p2) {
4373 final int v1 = p1.initOrder;
4374 final int v2 = p2.initOrder;
4375 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4376 }
4377 };
4378
Kenny Root93565c4b2010-06-18 15:46:06 -07004379 private static final boolean DEBUG_OBB = false;
4380
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004381 private static final void sendPackageBroadcast(String action, String pkg,
4382 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 IActivityManager am = ActivityManagerNative.getDefault();
4384 if (am != null) {
4385 try {
4386 final Intent intent = new Intent(action,
4387 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4388 if (extras != null) {
4389 intent.putExtras(extras);
4390 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004391 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004392 am.broadcastIntent(null, intent, null, finishedReceiver,
4393 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004394 } catch (RemoteException ex) {
4395 }
4396 }
4397 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004398
4399 public String nextPackageToClean(String lastPackage) {
4400 synchronized (mPackages) {
4401 if (!mMediaMounted) {
4402 // If the external storage is no longer mounted at this point,
4403 // the caller may not have been able to delete all of this
4404 // packages files and can not delete any more. Bail.
4405 return null;
4406 }
4407 if (lastPackage != null) {
4408 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4409 }
4410 return mSettings.mPackagesToBeCleaned.size() > 0
4411 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4412 }
4413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004415 void schedulePackageCleaning(String packageName) {
4416 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4417 }
4418
4419 void startCleaningPackages() {
4420 synchronized (mPackages) {
4421 if (!mMediaMounted) {
4422 return;
4423 }
4424 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4425 return;
4426 }
4427 }
4428 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4429 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4430 IActivityManager am = ActivityManagerNative.getDefault();
4431 if (am != null) {
4432 try {
4433 am.startService(null, intent, null);
4434 } catch (RemoteException e) {
4435 }
4436 }
4437 }
4438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004439 private final class AppDirObserver extends FileObserver {
4440 public AppDirObserver(String path, int mask, boolean isrom) {
4441 super(path, mask);
4442 mRootDir = path;
4443 mIsRom = isrom;
4444 }
4445
4446 public void onEvent(int event, String path) {
4447 String removedPackage = null;
4448 int removedUid = -1;
4449 String addedPackage = null;
4450 int addedUid = -1;
4451
4452 synchronized (mInstallLock) {
4453 String fullPathStr = null;
4454 File fullPath = null;
4455 if (path != null) {
4456 fullPath = new File(mRootDir, path);
4457 fullPathStr = fullPath.getPath();
4458 }
4459
4460 if (Config.LOGV) Log.v(
4461 TAG, "File " + fullPathStr + " changed: "
4462 + Integer.toHexString(event));
4463
4464 if (!isPackageFilename(path)) {
4465 if (Config.LOGV) Log.v(
4466 TAG, "Ignoring change of non-package file: " + fullPathStr);
4467 return;
4468 }
4469
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004470 // Ignore packages that are being installed or
4471 // have just been installed.
4472 if (ignoreCodePath(fullPathStr)) {
4473 return;
4474 }
4475 PackageParser.Package p = null;
4476 synchronized (mPackages) {
4477 p = mAppDirs.get(fullPathStr);
4478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004479 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004480 if (p != null) {
4481 removePackageLI(p, true);
4482 removedPackage = p.applicationInfo.packageName;
4483 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484 }
4485 }
4486
4487 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004489 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004490 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4491 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004492 PackageParser.PARSE_CHATTY |
4493 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004494 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 if (p != null) {
4496 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004497 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004498 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499 }
4500 addedPackage = p.applicationInfo.packageName;
4501 addedUid = p.applicationInfo.uid;
4502 }
4503 }
4504 }
4505
4506 synchronized (mPackages) {
4507 mSettings.writeLP();
4508 }
4509 }
4510
4511 if (removedPackage != null) {
4512 Bundle extras = new Bundle(1);
4513 extras.putInt(Intent.EXTRA_UID, removedUid);
4514 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004515 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4516 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 }
4518 if (addedPackage != null) {
4519 Bundle extras = new Bundle(1);
4520 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004521 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4522 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004523 }
4524 }
4525
4526 private final String mRootDir;
4527 private final boolean mIsRom;
4528 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 /* Called when a downloaded package installation has been confirmed by the user */
4531 public void installPackage(
4532 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004533 installPackage(packageURI, observer, flags, null);
4534 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004535
Jacek Surazski65e13172009-04-28 15:26:38 +02004536 /* Called when a downloaded package installation has been confirmed by the user */
4537 public void installPackage(
4538 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4539 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004540 mContext.enforceCallingOrSelfPermission(
4541 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004542
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004543 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004544 msg.obj = new InstallParams(packageURI, observer, flags,
4545 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004546 mHandler.sendMessage(msg);
4547 }
4548
Christopher Tate1bb69062010-02-19 17:02:12 -08004549 public void finishPackageInstall(int token) {
4550 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4551 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4552 mHandler.sendMessage(msg);
4553 }
4554
Kenny Root93565c4b2010-06-18 15:46:06 -07004555 public void setPackageObbPath(String packageName, String path) {
4556 if (DEBUG_OBB)
4557 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4558 PackageSetting pkgSetting;
4559 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004560 final int permission = mContext.checkCallingPermission(
4561 android.Manifest.permission.INSTALL_PACKAGES);
4562 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004563 synchronized (mPackages) {
4564 pkgSetting = mSettings.mPackages.get(packageName);
4565 if (pkgSetting == null) {
4566 throw new IllegalArgumentException("Unknown package: " + packageName);
4567 }
4568 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4569 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4570 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4571 + pkgSetting.userId);
4572 }
4573 pkgSetting.obbPathString = path;
4574 mSettings.writeLP();
4575 }
4576 }
4577
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004578 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004579 // Queue up an async operation since the package installation may take a little while.
4580 mHandler.post(new Runnable() {
4581 public void run() {
4582 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004583 // Result object to be returned
4584 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004585 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004586 res.uid = -1;
4587 res.pkg = null;
4588 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004589 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004590 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004591 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004592 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004593 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004594 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004596
4597 // A restore should be performed at this point if (a) the install
4598 // succeeded, (b) the operation is not an update, and (c) the new
4599 // package has a backupAgent defined.
4600 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004601 boolean doRestore = (!update
4602 && res.pkg != null
4603 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004604
4605 // Set up the post-install work request bookkeeping. This will be used
4606 // and cleaned up by the post-install event handling regardless of whether
4607 // there's a restore pass performed. Token values are >= 1.
4608 int token;
4609 if (mNextInstallToken < 0) mNextInstallToken = 1;
4610 token = mNextInstallToken++;
4611
4612 PostInstallData data = new PostInstallData(args, res);
4613 mRunningInstalls.put(token, data);
4614 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4615
4616 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4617 // Pass responsibility to the Backup Manager. It will perform a
4618 // restore if appropriate, then pass responsibility back to the
4619 // Package Manager to run the post-install observer callbacks
4620 // and broadcasts.
4621 IBackupManager bm = IBackupManager.Stub.asInterface(
4622 ServiceManager.getService(Context.BACKUP_SERVICE));
4623 if (bm != null) {
4624 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4625 + " to BM for possible restore");
4626 try {
4627 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4628 } catch (RemoteException e) {
4629 // can't happen; the backup manager is local
4630 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004631 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004632 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004633 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004634 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004635 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004636 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004638 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004639
4640 if (!doRestore) {
4641 // No restore possible, or the Backup Manager was mysteriously not
4642 // available -- just fire the post-install work request directly.
4643 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4644 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4645 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004647 }
4648 });
4649 }
4650
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004651 abstract class HandlerParams {
4652 final static int MAX_RETRIES = 4;
4653 int retry = 0;
4654 final void startCopy() {
4655 try {
4656 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4657 retry++;
4658 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004659 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004660 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4661 handleServiceError();
4662 return;
4663 } else {
4664 handleStartCopy();
4665 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4666 mHandler.sendEmptyMessage(MCS_UNBIND);
4667 }
4668 } catch (RemoteException e) {
4669 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4670 mHandler.sendEmptyMessage(MCS_RECONNECT);
4671 }
4672 handleReturnCode();
4673 }
4674
4675 final void serviceError() {
4676 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4677 handleServiceError();
4678 handleReturnCode();
4679 }
4680 abstract void handleStartCopy() throws RemoteException;
4681 abstract void handleServiceError();
4682 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004683 }
4684
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004685 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004686 final IPackageInstallObserver observer;
4687 int flags;
4688 final Uri packageURI;
4689 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004690 private InstallArgs mArgs;
4691 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004692 InstallParams(Uri packageURI,
4693 IPackageInstallObserver observer, int flags,
4694 String installerPackageName) {
4695 this.packageURI = packageURI;
4696 this.flags = flags;
4697 this.observer = observer;
4698 this.installerPackageName = installerPackageName;
4699 }
4700
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004701 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4702 String packageName = pkgLite.packageName;
4703 int installLocation = pkgLite.installLocation;
4704 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4705 synchronized (mPackages) {
4706 PackageParser.Package pkg = mPackages.get(packageName);
4707 if (pkg != null) {
4708 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4709 // Check for updated system application.
4710 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4711 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004712 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004713 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4714 }
4715 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4716 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004717 if (onSd) {
4718 // Install flag overrides everything.
4719 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4720 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004721 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004722 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4723 // Application explicitly specified internal.
4724 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4725 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4726 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004727 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004728 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004729 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004730 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4731 }
4732 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004733 }
4734 }
4735 } else {
4736 // Invalid install. Return error code
4737 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4738 }
4739 }
4740 }
4741 // All the special cases have been taken care of.
4742 // Return result based on recommended install location.
4743 if (onSd) {
4744 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4745 }
4746 return pkgLite.recommendedInstallLocation;
4747 }
4748
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004749 /*
4750 * Invoke remote method to get package information and install
4751 * location values. Override install location based on default
4752 * policy if needed and then create install arguments based
4753 * on the install location.
4754 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004755 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004756 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004757 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4758 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004759 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4760 if (onInt && onSd) {
4761 // Check if both bits are set.
4762 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4763 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4764 } else if (fwdLocked && onSd) {
4765 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004766 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004767 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004768 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004769 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004770 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004771 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004772 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4773 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4774 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4775 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4776 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004777 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4778 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4779 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004780 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4781 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004782 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004783 // Override with defaults if needed.
4784 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004785 if (!onSd && !onInt) {
4786 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004787 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4788 // Set the flag to install on external media.
4789 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004790 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004791 } else {
4792 // Make sure the flag for installing on external
4793 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004794 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004795 flags &= ~PackageManager.INSTALL_EXTERNAL;
4796 }
4797 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004798 }
4799 }
4800 // Create the file args now.
4801 mArgs = createInstallArgs(this);
4802 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4803 // Create copy only if we are not in an erroneous state.
4804 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004805 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004806 }
4807 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004808 }
4809
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004810 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004811 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004812 // If mArgs is null, then MCS couldn't be reached. When it
4813 // reconnects, it will try again to install. At that point, this
4814 // will succeed.
4815 if (mArgs != null) {
4816 processPendingInstall(mArgs, mRet);
4817 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004818 }
4819
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004820 @Override
4821 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004822 mArgs = createInstallArgs(this);
4823 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004824 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004825 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004826
4827 /*
4828 * Utility class used in movePackage api.
4829 * srcArgs and targetArgs are not set for invalid flags and make
4830 * sure to do null checks when invoking methods on them.
4831 * We probably want to return ErrorPrams for both failed installs
4832 * and moves.
4833 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004834 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004835 final IPackageMoveObserver observer;
4836 final int flags;
4837 final String packageName;
4838 final InstallArgs srcArgs;
4839 final InstallArgs targetArgs;
4840 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004841
4842 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4843 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004844 this.srcArgs = srcArgs;
4845 this.observer = observer;
4846 this.flags = flags;
4847 this.packageName = packageName;
4848 if (srcArgs != null) {
4849 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004850 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004851 } else {
4852 targetArgs = null;
4853 }
4854 }
4855
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004856 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004857 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4858 // Check for storage space on target medium
4859 if (!targetArgs.checkFreeStorage(mContainerService)) {
4860 Log.w(TAG, "Insufficient storage to install");
4861 return;
4862 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004863 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004864 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004865 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004866 if (DEBUG_SD_INSTALL) {
4867 StringBuilder builder = new StringBuilder();
4868 if (srcArgs != null) {
4869 builder.append("src: ");
4870 builder.append(srcArgs.getCodePath());
4871 }
4872 if (targetArgs != null) {
4873 builder.append(" target : ");
4874 builder.append(targetArgs.getCodePath());
4875 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004876 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004877 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004878 }
4879
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004880 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004881 void handleReturnCode() {
4882 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004883 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4884 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4885 currentStatus = PackageManager.MOVE_SUCCEEDED;
4886 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4887 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4888 }
4889 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004890 }
4891
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004892 @Override
4893 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004894 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004895 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004896 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004897
4898 private InstallArgs createInstallArgs(InstallParams params) {
4899 if (installOnSd(params.flags)) {
4900 return new SdInstallArgs(params);
4901 } else {
4902 return new FileInstallArgs(params);
4903 }
4904 }
4905
Kenny Root85387d72010-08-26 10:13:11 -07004906 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4907 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004908 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004909 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004910 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004911 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004912 }
4913 }
4914
Kenny Root85387d72010-08-26 10:13:11 -07004915 // Used by package mover
4916 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004917 if (installOnSd(flags)) {
4918 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4919 return new SdInstallArgs(packageURI, cid);
4920 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004921 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004922 }
4923 }
4924
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004925 static abstract class InstallArgs {
4926 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004927 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004928 final int flags;
4929 final Uri packageURI;
4930 final String installerPackageName;
4931
4932 InstallArgs(Uri packageURI,
4933 IPackageInstallObserver observer, int flags,
4934 String installerPackageName) {
4935 this.packageURI = packageURI;
4936 this.flags = flags;
4937 this.observer = observer;
4938 this.installerPackageName = installerPackageName;
4939 }
4940
4941 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004942 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004943 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004944 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004945 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004946 abstract String getCodePath();
4947 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004948 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004949 // Need installer lock especially for dex file removal.
4950 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004951 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004952 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004953 }
4954
4955 class FileInstallArgs extends InstallArgs {
4956 File installDir;
4957 String codeFileName;
4958 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004959 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004960 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004961
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004962 FileInstallArgs(InstallParams params) {
4963 super(params.packageURI, params.observer,
4964 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004965 }
4966
Kenny Root85387d72010-08-26 10:13:11 -07004967 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004968 super(null, null, 0, null);
4969 File codeFile = new File(fullCodePath);
4970 installDir = codeFile.getParentFile();
4971 codeFileName = fullCodePath;
4972 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004973 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004974 }
4975
Kenny Root85387d72010-08-26 10:13:11 -07004976 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004977 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004978 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004979 String apkName = getNextCodePath(null, pkgName, ".apk");
4980 codeFileName = new File(installDir, apkName + ".apk").getPath();
4981 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004982 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004983 }
4984
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004985 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4986 return imcs.checkFreeStorage(false, packageURI);
4987 }
4988
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004989 String getCodePath() {
4990 return codeFileName;
4991 }
4992
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004993 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07004994 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004995 codeFileName = createTempPackageFile(installDir).getPath();
4996 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004997 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004998 }
4999
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005000 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005001 if (temp) {
5002 // Generate temp file name
5003 createCopyFile();
5004 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005005 // Get a ParcelFileDescriptor to write to the output file
5006 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005007 if (!created) {
5008 try {
5009 codeFile.createNewFile();
5010 // Set permissions
5011 if (!setPermissions()) {
5012 // Failed setting permissions.
5013 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5014 }
5015 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005016 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005017 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5018 }
5019 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005020 ParcelFileDescriptor out = null;
5021 try {
Kenny Root85387d72010-08-26 10:13:11 -07005022 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005023 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005024 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005025 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5026 }
5027 // Copy the resource now
5028 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5029 try {
5030 if (imcs.copyResource(packageURI, out)) {
5031 ret = PackageManager.INSTALL_SUCCEEDED;
5032 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005033 } finally {
5034 try { if (out != null) out.close(); } catch (IOException e) {}
5035 }
Kenny Root85387d72010-08-26 10:13:11 -07005036
5037 if (!temp) {
5038 NativeLibraryHelper.copyNativeBinariesLI(codeFile, new File(libraryPath));
5039 }
5040
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005041 return ret;
5042 }
5043
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005044 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005045 if (status != PackageManager.INSTALL_SUCCEEDED) {
5046 cleanUp();
5047 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005048 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005049 }
5050
5051 boolean doRename(int status, final String pkgName, String oldCodePath) {
5052 if (status != PackageManager.INSTALL_SUCCEEDED) {
5053 cleanUp();
5054 return false;
5055 } else {
5056 // Rename based on packageName
5057 File codeFile = new File(getCodePath());
5058 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5059 File desFile = new File(installDir, apkName + ".apk");
5060 if (!codeFile.renameTo(desFile)) {
5061 return false;
5062 }
5063 // Reset paths since the file has been renamed.
5064 codeFileName = desFile.getPath();
5065 resourceFileName = getResourcePathFromCodePath();
5066 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005067 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005068 // Failed setting permissions.
5069 return false;
5070 }
5071 return true;
5072 }
5073 }
5074
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005075 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005076 if (status != PackageManager.INSTALL_SUCCEEDED) {
5077 cleanUp();
5078 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005079 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005080 }
5081
5082 String getResourcePath() {
5083 return resourceFileName;
5084 }
5085
5086 String getResourcePathFromCodePath() {
5087 String codePath = getCodePath();
5088 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5089 String apkNameOnly = getApkName(codePath);
5090 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5091 } else {
5092 return codePath;
5093 }
5094 }
5095
Kenny Root85387d72010-08-26 10:13:11 -07005096 @Override
5097 String getNativeLibraryPath() {
5098 return libraryPath;
5099 }
5100
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005101 private boolean cleanUp() {
5102 boolean ret = true;
5103 String sourceDir = getCodePath();
5104 String publicSourceDir = getResourcePath();
5105 if (sourceDir != null) {
5106 File sourceFile = new File(sourceDir);
5107 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005108 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005109 ret = false;
5110 }
5111 // Delete application's code and resources
5112 sourceFile.delete();
5113 }
5114 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5115 final File publicSourceFile = new File(publicSourceDir);
5116 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005117 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005118 }
5119 if (publicSourceFile.exists()) {
5120 publicSourceFile.delete();
5121 }
5122 }
5123 return ret;
5124 }
5125
5126 void cleanUpResourcesLI() {
5127 String sourceDir = getCodePath();
5128 if (cleanUp() && mInstaller != null) {
5129 int retCode = mInstaller.rmdex(sourceDir);
5130 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005131 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005132 + " at location "
5133 + sourceDir + ", retcode=" + retCode);
5134 // we don't consider this to be a failure of the core package deletion
5135 }
5136 }
Kenny Root85387d72010-08-26 10:13:11 -07005137 if (libraryPath != null) {
5138 removeNativeBinariesLI(new File(libraryPath));
5139 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005140 }
5141
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005142 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005143 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005144 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005145 final int filePermissions =
5146 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5147 |FileUtils.S_IROTH;
5148 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5149 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005150 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005151 getCodePath()
5152 + ". The return code was: " + retCode);
5153 // TODO Define new internal error
5154 return false;
5155 }
5156 return true;
5157 }
5158 return true;
5159 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005160
5161 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005162 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005163 cleanUpResourcesLI();
5164 return true;
5165 }
Kenny Root85387d72010-08-26 10:13:11 -07005166
5167 private boolean isFwdLocked() {
5168 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5169 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005170 }
5171
5172 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005173 static final String RES_FILE_NAME = "pkg.apk";
5174
Kenny Root85387d72010-08-26 10:13:11 -07005175 String cid;
5176 String packagePath;
5177 String libraryPath;
5178
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005179 SdInstallArgs(InstallParams params) {
5180 super(params.packageURI, params.observer,
5181 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005182 }
5183
Kenny Root85387d72010-08-26 10:13:11 -07005184 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005185 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005186 // Extract cid from fullCodePath
5187 int eidx = fullCodePath.lastIndexOf("/");
5188 String subStr1 = fullCodePath.substring(0, eidx);
5189 int sidx = subStr1.lastIndexOf("/");
5190 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005191 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005192 }
5193
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005194 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005195 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5196 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005197 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005198 }
5199
5200 SdInstallArgs(Uri packageURI, String cid) {
5201 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005202 this.cid = cid;
5203 }
5204
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005205 void createCopyFile() {
5206 cid = getTempContainerId();
5207 }
5208
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005209 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5210 return imcs.checkFreeStorage(true, packageURI);
5211 }
5212
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005213 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005214 if (temp) {
5215 createCopyFile();
5216 }
Kenny Root85387d72010-08-26 10:13:11 -07005217 String newCachePath = imcs.copyResourceToContainer(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005218 packageURI, cid,
5219 getEncryptKey(), RES_FILE_NAME);
Kenny Root85387d72010-08-26 10:13:11 -07005220 if (newCachePath != null) {
5221 setCachePath(newCachePath);
5222 return PackageManager.INSTALL_SUCCEEDED;
5223 } else {
5224 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5225 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005226 }
5227
5228 @Override
5229 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005230 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005231 }
5232
5233 @Override
5234 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005235 return packagePath;
5236 }
5237
5238 @Override
5239 String getNativeLibraryPath() {
5240 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005241 }
5242
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005243 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005244 if (status != PackageManager.INSTALL_SUCCEEDED) {
5245 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005246 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005247 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005248 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005249 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005250 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5251 Process.SYSTEM_UID);
5252 if (newCachePath != null) {
5253 setCachePath(newCachePath);
5254 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005255 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5256 }
5257 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005258 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005259 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005260 }
5261
5262 boolean doRename(int status, final String pkgName,
5263 String oldCodePath) {
5264 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005265 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005266 if (PackageHelper.isContainerMounted(cid)) {
5267 // Unmount the container
5268 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005269 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005270 return false;
5271 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005272 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005273 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005274 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5275 " which might be stale. Will try to clean up.");
5276 // Clean up the stale container and proceed to recreate.
5277 if (!PackageHelper.destroySdDir(newCacheId)) {
5278 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5279 return false;
5280 }
5281 // Successfully cleaned up stale container. Try to rename again.
5282 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5283 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5284 + " inspite of cleaning it up.");
5285 return false;
5286 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005287 }
5288 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005289 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005290 newCachePath = PackageHelper.mountSdDir(newCacheId,
5291 getEncryptKey(), Process.SYSTEM_UID);
5292 } else {
5293 newCachePath = PackageHelper.getSdDir(newCacheId);
5294 }
5295 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005296 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005297 return false;
5298 }
5299 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005300 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005301 " at new path: " + newCachePath);
5302 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005303 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005304 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005305 }
5306
Kenny Root85387d72010-08-26 10:13:11 -07005307 private void setCachePath(String newCachePath) {
5308 File cachePath = new File(newCachePath);
5309 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5310 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5311 }
5312
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005313 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005314 if (status != PackageManager.INSTALL_SUCCEEDED) {
5315 cleanUp();
5316 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005317 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005318 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005319 PackageHelper.mountSdDir(cid,
5320 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005321 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005322 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005323 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005324 }
5325
5326 private void cleanUp() {
5327 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005328 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005329 }
5330
5331 void cleanUpResourcesLI() {
5332 String sourceFile = getCodePath();
5333 // Remove dex file
5334 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005335 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005336 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005337 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005338 + " at location "
5339 + sourceFile.toString() + ", retcode=" + retCode);
5340 // we don't consider this to be a failure of the core package deletion
5341 }
5342 }
5343 cleanUp();
5344 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005345
5346 boolean matchContainer(String app) {
5347 if (cid.startsWith(app)) {
5348 return true;
5349 }
5350 return false;
5351 }
5352
5353 String getPackageName() {
5354 int idx = cid.lastIndexOf("-");
5355 if (idx == -1) {
5356 return cid;
5357 }
5358 return cid.substring(0, idx);
5359 }
5360
5361 boolean doPostDeleteLI(boolean delete) {
5362 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005363 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005364 if (mounted) {
5365 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005366 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005367 }
5368 if (ret && delete) {
5369 cleanUpResourcesLI();
5370 }
5371 return ret;
5372 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005373 };
5374
5375 // Utility method used to create code paths based on package name and available index.
5376 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5377 String idxStr = "";
5378 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005379 // Fall back to default value of idx=1 if prefix is not
5380 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005381 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005382 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005383 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005384 if (subStr.endsWith(suffix)) {
5385 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005386 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005387 // If oldCodePath already contains prefix find out the
5388 // ending index to either increment or decrement.
5389 int sidx = subStr.lastIndexOf(prefix);
5390 if (sidx != -1) {
5391 subStr = subStr.substring(sidx + prefix.length());
5392 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005393 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5394 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005395 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005396 try {
5397 idx = Integer.parseInt(subStr);
5398 if (idx <= 1) {
5399 idx++;
5400 } else {
5401 idx--;
5402 }
5403 } catch(NumberFormatException e) {
5404 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005405 }
5406 }
5407 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005408 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005409 return prefix + idxStr;
5410 }
5411
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005412 // Utility method used to ignore ADD/REMOVE events
5413 // by directory observer.
5414 private static boolean ignoreCodePath(String fullPathStr) {
5415 String apkName = getApkName(fullPathStr);
5416 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5417 if (idx != -1 && ((idx+1) < apkName.length())) {
5418 // Make sure the package ends with a numeral
5419 String version = apkName.substring(idx+1);
5420 try {
5421 Integer.parseInt(version);
5422 return true;
5423 } catch (NumberFormatException e) {}
5424 }
5425 return false;
5426 }
5427
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005428 // Utility method that returns the relative package path with respect
5429 // to the installation directory. Like say for /data/data/com.test-1.apk
5430 // string com.test-1 is returned.
5431 static String getApkName(String codePath) {
5432 if (codePath == null) {
5433 return null;
5434 }
5435 int sidx = codePath.lastIndexOf("/");
5436 int eidx = codePath.lastIndexOf(".");
5437 if (eidx == -1) {
5438 eidx = codePath.length();
5439 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005440 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005441 return null;
5442 }
5443 return codePath.substring(sidx+1, eidx);
5444 }
5445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 class PackageInstalledInfo {
5447 String name;
5448 int uid;
5449 PackageParser.Package pkg;
5450 int returnCode;
5451 PackageRemovedInfo removedInfo;
5452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 /*
5455 * Install a non-existing package.
5456 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005457 private void installNewPackageLI(PackageParser.Package pkg,
5458 int parseFlags,
5459 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005460 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005461 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005462 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005463
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005464 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465 res.name = pkgName;
5466 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005467 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5468 // A package with the same name is already installed, though
5469 // it has been renamed to an older name. The package we
5470 // are trying to install should be installed as an update to
5471 // the existing one, but that has not been requested, so bail.
5472 Slog.w(TAG, "Attempt to re-install " + pkgName
5473 + " without first uninstalling package running as "
5474 + mSettings.mRenamedPackages.get(pkgName));
5475 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5476 return;
5477 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005478 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005480 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005481 + " without first uninstalling.");
5482 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5483 return;
5484 }
5485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005486 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005487 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005489 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005490 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5491 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5492 }
5493 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005494 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005495 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496 res);
5497 // delete the partially installed application. the data directory will have to be
5498 // restored if it was already existing
5499 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5500 // remove package from internal structures. Note that we want deletePackageX to
5501 // delete the package data and cache directories that it created in
5502 // scanPackageLocked, unless those directories existed before we even tried to
5503 // install.
5504 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005505 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005506 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5507 res.removedInfo);
5508 }
5509 }
5510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005511
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005512 private void replacePackageLI(PackageParser.Package pkg,
5513 int parseFlags,
5514 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005515 String installerPackageName, PackageInstalledInfo res) {
5516
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005517 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005518 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 // First find the old package info and check signatures
5520 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005521 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005522 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005523 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5525 return;
5526 }
5527 }
Kenny Root85387d72010-08-26 10:13:11 -07005528 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005529 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005530 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005531 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005532 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005533 }
5534 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005537 PackageParser.Package pkg,
5538 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005539 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 PackageParser.Package newPackage = null;
5541 String pkgName = deletedPackage.packageName;
5542 boolean deletedPkg = true;
5543 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005544
Jacek Surazski65e13172009-04-28 15:26:38 +02005545 String oldInstallerPackageName = null;
5546 synchronized (mPackages) {
5547 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5548 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005551 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005552 res.removedInfo)) {
5553 // If the existing package was'nt successfully deleted
5554 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5555 deletedPkg = false;
5556 } else {
5557 // Successfully deleted the old package. Now proceed with re-installation
5558 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005559 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005560 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005561 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005562 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5563 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005564 }
5565 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005566 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005567 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005568 res);
5569 updatedSettings = true;
5570 }
5571 }
5572
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005573 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 // remove package from internal structures. Note that we want deletePackageX to
5575 // delete the package data and cache directories that it created in
5576 // scanPackageLocked, unless those directories existed before we even tried to
5577 // install.
5578 if(updatedSettings) {
5579 deletePackageLI(
5580 pkgName, true,
5581 PackageManager.DONT_DELETE_DATA,
5582 res.removedInfo);
5583 }
5584 // Since we failed to install the new package we need to restore the old
5585 // package that we deleted.
5586 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005587 File restoreFile = new File(deletedPackage.mPath);
5588 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005589 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005590 return;
5591 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005592 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005593 boolean oldOnSd = isExternal(deletedPackage);
5594 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5595 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5596 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5597 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5598 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5599 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5600 return;
5601 }
5602 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005603 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005604 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005605 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005606 mSettings.writeLP();
5607 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005608 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 }
5610 }
5611 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005614 PackageParser.Package pkg,
5615 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005616 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005617 PackageParser.Package newPackage = null;
5618 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005619 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005620 PackageParser.PARSE_IS_SYSTEM;
5621 String packageName = deletedPackage.packageName;
5622 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5623 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005624 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005625 return;
5626 }
5627 PackageParser.Package oldPkg;
5628 PackageSetting oldPkgSetting;
5629 synchronized (mPackages) {
5630 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005631 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5633 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005634 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 return;
5636 }
5637 }
5638 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5639 res.removedInfo.removedPackage = packageName;
5640 // Remove existing system package
5641 removePackageLI(oldPkg, true);
5642 synchronized (mPackages) {
5643 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5644 }
5645
5646 // Successfully disabled the old package. Now proceed with re-installation
5647 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5648 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005649 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005651 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005652 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5653 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5654 }
5655 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005656 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 updatedSettings = true;
5658 }
5659
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005660 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 // Re installation failed. Restore old information
5662 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005663 if (newPackage != null) {
5664 removePackageLI(newPackage, true);
5665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005667 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005669 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 // Restore the old system information in Settings
5671 synchronized(mPackages) {
5672 if(updatedSettings) {
5673 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005674 mSettings.setInstallerPackageName(packageName,
5675 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005676 }
5677 mSettings.writeLP();
5678 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005679 } else {
5680 // If this is an update to an existing update, setup
5681 // to remove the existing update.
5682 synchronized (mPackages) {
5683 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5684 if (ps != null && ps.codePathString != null &&
5685 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5686 int installFlags = 0;
5687 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005688 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005689 }
5690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005691 }
5692 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005693
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005694 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005695 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005696 int retCode;
5697 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5698 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5699 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005700 if (mNoDexOpt) {
5701 /*
5702 * If we're in an engineering build, programs are lazily run
5703 * through dexopt. If the .dex file doesn't exist yet, it
5704 * will be created when the program is run next.
5705 */
5706 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5707 } else {
5708 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5709 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5710 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005711 }
5712 }
5713 return PackageManager.INSTALL_SUCCEEDED;
5714 }
5715
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005716 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005717 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005718 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 synchronized (mPackages) {
5720 //write settings. the installStatus will be incomplete at this stage.
5721 //note that the new package setting would have already been
5722 //added to mPackages. It hasn't been persisted yet.
5723 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5724 mSettings.writeLP();
5725 }
5726
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005727 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005728 != PackageManager.INSTALL_SUCCEEDED) {
5729 // Discontinue if moving dex files failed.
5730 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005732 if((res.returnCode = setPermissionsLI(newPackage))
5733 != PackageManager.INSTALL_SUCCEEDED) {
5734 if (mInstaller != null) {
5735 mInstaller.rmdex(newPackage.mScanPath);
5736 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005737 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005739 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005741 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005742 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005743 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 res.name = pkgName;
5745 res.uid = newPackage.applicationInfo.uid;
5746 res.pkg = newPackage;
5747 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005748 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5750 //to update install status
5751 mSettings.writeLP();
5752 }
5753 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005754
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005755 private void installPackageLI(InstallArgs args,
5756 boolean newInstall, PackageInstalledInfo res) {
5757 int pFlags = args.flags;
5758 String installerPackageName = args.installerPackageName;
5759 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005760 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005761 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005762 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005763 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005764 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005765 // Result object to be returned
5766 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5767
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005768 // Retrieve PackageSettings and parse package
5769 int parseFlags = PackageParser.PARSE_CHATTY |
5770 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5771 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5772 parseFlags |= mDefParseFlags;
5773 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5774 pp.setSeparateProcesses(mSeparateProcesses);
5775 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5776 null, mMetrics, parseFlags);
5777 if (pkg == null) {
5778 res.returnCode = pp.getParseError();
5779 return;
5780 }
5781 String pkgName = res.name = pkg.packageName;
5782 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5783 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5784 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5785 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005787 }
5788 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5789 res.returnCode = pp.getParseError();
5790 return;
5791 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005792 // Get rid of all references to package scan path via parser.
5793 pp = null;
5794 String oldCodePath = null;
5795 boolean systemApp = false;
5796 synchronized (mPackages) {
5797 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005798 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5799 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005800 if (pkg.mOriginalPackages != null
5801 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005802 && mPackages.containsKey(oldName)) {
5803 // This package is derived from an original package,
5804 // and this device has been updating from that original
5805 // name. We must continue using the original name, so
5806 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005807 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005808 pkgName = pkg.packageName;
5809 replace = true;
5810 } else if (mPackages.containsKey(pkgName)) {
5811 // This package, under its official name, already exists
5812 // on the device; we should replace it.
5813 replace = true;
5814 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005815 }
5816 PackageSetting ps = mSettings.mPackages.get(pkgName);
5817 if (ps != null) {
5818 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5819 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5820 systemApp = (ps.pkg.applicationInfo.flags &
5821 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005822 }
5823 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005825
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005826 if (systemApp && onSd) {
5827 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005828 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005829 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5830 return;
5831 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005832
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005833 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5834 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5835 return;
5836 }
5837 // Set application objects path explicitly after the rename
5838 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005839 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005840 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005841 replacePackageLI(pkg, parseFlags, scanMode,
5842 installerPackageName, res);
5843 } else {
5844 installNewPackageLI(pkg, parseFlags, scanMode,
5845 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005846 }
5847 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005848
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005849 private int setPermissionsLI(PackageParser.Package newPackage) {
5850 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005851 int retCode = 0;
5852 // TODO Gross hack but fix later. Ideally move this to be a post installation
5853 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005854 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005855 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 try {
5857 extractPublicFiles(newPackage, destResourceFile);
5858 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005859 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 " forward-locked app.");
5861 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5862 } finally {
5863 //TODO clean up the extracted public files
5864 }
5865 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005866 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 newPackage.applicationInfo.uid);
5868 } else {
5869 final int filePermissions =
5870 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005871 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005872 newPackage.applicationInfo.uid);
5873 }
5874 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005875 // The permissions on the resource file was set when it was copied for
5876 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005879 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005880 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005881 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005882 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005883 // TODO Define new internal error
5884 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 }
5886 return PackageManager.INSTALL_SUCCEEDED;
5887 }
5888
Kenny Root85387d72010-08-26 10:13:11 -07005889 private static boolean isForwardLocked(PackageParser.Package pkg) {
5890 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005891 }
5892
Kenny Root85387d72010-08-26 10:13:11 -07005893 private static boolean isExternal(PackageParser.Package pkg) {
5894 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5895 }
5896
5897 private static boolean isSystemApp(PackageParser.Package pkg) {
5898 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5899 }
5900
5901 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5902 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005903 }
5904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005905 private void extractPublicFiles(PackageParser.Package newPackage,
5906 File publicZipFile) throws IOException {
5907 final ZipOutputStream publicZipOutStream =
5908 new ZipOutputStream(new FileOutputStream(publicZipFile));
5909 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5910
5911 // Copy manifest, resources.arsc and res directory to public zip
5912
5913 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5914 while (privateZipEntries.hasMoreElements()) {
5915 final ZipEntry zipEntry = privateZipEntries.nextElement();
5916 final String zipEntryName = zipEntry.getName();
5917 if ("AndroidManifest.xml".equals(zipEntryName)
5918 || "resources.arsc".equals(zipEntryName)
5919 || zipEntryName.startsWith("res/")) {
5920 try {
5921 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5922 } catch (IOException e) {
5923 try {
5924 publicZipOutStream.close();
5925 throw e;
5926 } finally {
5927 publicZipFile.delete();
5928 }
5929 }
5930 }
5931 }
5932
5933 publicZipOutStream.close();
5934 FileUtils.setPermissions(
5935 publicZipFile.getAbsolutePath(),
5936 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5937 -1, -1);
5938 }
5939
5940 private static void copyZipEntry(ZipEntry zipEntry,
5941 ZipFile inZipFile,
5942 ZipOutputStream outZipStream) throws IOException {
5943 byte[] buffer = new byte[4096];
5944 int num;
5945
5946 ZipEntry newEntry;
5947 if (zipEntry.getMethod() == ZipEntry.STORED) {
5948 // Preserve the STORED method of the input entry.
5949 newEntry = new ZipEntry(zipEntry);
5950 } else {
5951 // Create a new entry so that the compressed len is recomputed.
5952 newEntry = new ZipEntry(zipEntry.getName());
5953 }
5954 outZipStream.putNextEntry(newEntry);
5955
5956 InputStream data = inZipFile.getInputStream(zipEntry);
5957 while ((num = data.read(buffer)) > 0) {
5958 outZipStream.write(buffer, 0, num);
5959 }
5960 outZipStream.flush();
5961 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 private void deleteTempPackageFiles() {
5964 FilenameFilter filter = new FilenameFilter() {
5965 public boolean accept(File dir, String name) {
5966 return name.startsWith("vmdl") && name.endsWith(".tmp");
5967 }
5968 };
5969 String tmpFilesList[] = mAppInstallDir.list(filter);
5970 if(tmpFilesList == null) {
5971 return;
5972 }
5973 for(int i = 0; i < tmpFilesList.length; i++) {
5974 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5975 tmpFile.delete();
5976 }
5977 }
5978
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005979 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005980 File tmpPackageFile;
5981 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005982 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005984 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 return null;
5986 }
5987 try {
5988 FileUtils.setPermissions(
5989 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5990 -1, -1);
5991 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005992 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 return null;
5994 }
5995 return tmpPackageFile;
5996 }
5997
5998 public void deletePackage(final String packageName,
5999 final IPackageDeleteObserver observer,
6000 final int flags) {
6001 mContext.enforceCallingOrSelfPermission(
6002 android.Manifest.permission.DELETE_PACKAGES, null);
6003 // Queue up an async operation since the package deletion may take a little while.
6004 mHandler.post(new Runnable() {
6005 public void run() {
6006 mHandler.removeCallbacks(this);
6007 final boolean succeded = deletePackageX(packageName, true, true, flags);
6008 if (observer != null) {
6009 try {
6010 observer.packageDeleted(succeded);
6011 } catch (RemoteException e) {
6012 Log.i(TAG, "Observer no longer exists.");
6013 } //end catch
6014 } //end if
6015 } //end run
6016 });
6017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 /**
6020 * This method is an internal method that could be get invoked either
6021 * to delete an installed package or to clean up a failed installation.
6022 * After deleting an installed package, a broadcast is sent to notify any
6023 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006024 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 * installation wouldn't have sent the initial broadcast either
6026 * The key steps in deleting a package are
6027 * deleting the package information in internal structures like mPackages,
6028 * deleting the packages base directories through installd
6029 * updating mSettings to reflect current status
6030 * persisting settings for later use
6031 * sending a broadcast if necessary
6032 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6034 boolean deleteCodeAndResources, int flags) {
6035 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006036 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006038 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6039 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6040 try {
6041 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006042 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006043 return false;
6044 }
6045 } catch (RemoteException e) {
6046 }
6047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006049 res = deletePackageLI(packageName, deleteCodeAndResources,
6050 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006053 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006054 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006055 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006056
6057 // If the removed package was a system update, the old system packaged
6058 // was re-enabled; we need to broadcast this information
6059 if (systemUpdate) {
6060 Bundle extras = new Bundle(1);
6061 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6062 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6063
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006064 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6065 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006067 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006068 // Force a gc here.
6069 Runtime.getRuntime().gc();
6070 // Delete the resources here after sending the broadcast to let
6071 // other processes clean up before deleting resources.
6072 if (info.args != null) {
6073 synchronized (mInstallLock) {
6074 info.args.doPostDeleteLI(deleteCodeAndResources);
6075 }
6076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 return res;
6078 }
6079
6080 static class PackageRemovedInfo {
6081 String removedPackage;
6082 int uid = -1;
6083 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006084 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006085 // Clean up resources deleted packages.
6086 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006087
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006088 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 Bundle extras = new Bundle(1);
6090 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6091 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6092 if (replacing) {
6093 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6094 }
6095 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006096 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 }
6098 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006099 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 }
6101 }
6102 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 /*
6105 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6106 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006107 * make sure this flag is set for partially installed apps. If not its meaningless to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006108 * delete a partially installed application.
6109 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006110 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 int flags) {
6112 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006113 if (outInfo != null) {
6114 outInfo.removedPackage = packageName;
6115 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006116 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 // Retrieve object to delete permissions for shared user later on
6118 PackageSetting deletedPs;
6119 synchronized (mPackages) {
6120 deletedPs = mSettings.mPackages.get(packageName);
6121 }
6122 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006123 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006125 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006127 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 + packageName + ", retcode=" + retCode);
6129 // we don't consider this to be a failure of the core package deletion
6130 }
6131 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006132 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 PackageParser.Package pkg = mPackages.get(packageName);
6134 File dataDir = new File(pkg.applicationInfo.dataDir);
6135 dataDir.delete();
6136 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006137 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 }
6139 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006140 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006141 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6142 if (outInfo != null) {
6143 outInfo.removedUid = mSettings.removePackageLP(packageName);
6144 }
6145 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006146 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006147 if (deletedPs.sharedUser != null) {
6148 // remove permissions associated with package
6149 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6150 }
6151 }
6152 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006153 // remove from preferred activities.
6154 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6155 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6156 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6157 removed.add(pa);
6158 }
6159 }
6160 for (PreferredActivity pa : removed) {
6161 mSettings.mPreferredActivities.removeFilter(pa);
6162 }
6163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006165 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 }
6167 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 /*
6170 * Tries to delete system package.
6171 */
6172 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006173 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006174 ApplicationInfo applicationInfo = p.applicationInfo;
6175 //applicable for non-partially installed applications only
6176 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006177 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 return false;
6179 }
6180 PackageSetting ps = null;
6181 // Confirm if the system package has been updated
6182 // An updated system app can be deleted. This will also have to restore
6183 // the system pkg from system partition
6184 synchronized (mPackages) {
6185 ps = mSettings.getDisabledSystemPkg(p.packageName);
6186 }
6187 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006188 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 return false;
6190 } else {
6191 Log.i(TAG, "Deleting system pkg from data partition");
6192 }
6193 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006194 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006195 final boolean deleteCodeAndResources;
6196 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006197 // Delete code and resources for downgrades
6198 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006199 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006200 } else {
6201 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006202 deleteCodeAndResources = false;
6203 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006205 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6206 if (!ret) {
6207 return false;
6208 }
6209 synchronized (mPackages) {
6210 // Reinstate the old system package
6211 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07006212 // Remove any native libraries. XXX needed?
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07006213 removeNativeBinariesLI(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 }
6215 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006216 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006218 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006221 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 return false;
6223 }
6224 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006225 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 mSettings.writeLP();
6227 }
6228 return true;
6229 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6232 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6233 ApplicationInfo applicationInfo = p.applicationInfo;
6234 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006235 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236 return false;
6237 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006238 if (outInfo != null) {
6239 outInfo.uid = applicationInfo.uid;
6240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241
6242 // Delete package data from internal structures and also remove data if flag is set
6243 removePackageDataLI(p, outInfo, flags);
6244
6245 // Delete application code and resources
6246 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006247 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006248 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6249 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6250 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6251 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 }
6253 return true;
6254 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 /*
6257 * This method handles package deletion in general
6258 */
6259 private boolean deletePackageLI(String packageName,
6260 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6261 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006262 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 return false;
6264 }
6265 PackageParser.Package p;
6266 boolean dataOnly = false;
6267 synchronized (mPackages) {
6268 p = mPackages.get(packageName);
6269 if (p == null) {
6270 //this retrieves partially installed apps
6271 dataOnly = true;
6272 PackageSetting ps = mSettings.mPackages.get(packageName);
6273 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006274 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006275 return false;
6276 }
6277 p = ps.pkg;
6278 }
6279 }
6280 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006281 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 return false;
6283 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 if (dataOnly) {
6286 // Delete application data first
6287 removePackageDataLI(p, outInfo, flags);
6288 return true;
6289 }
6290 // At this point the package should have ApplicationInfo associated with it
6291 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006292 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006293 return false;
6294 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006295 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006296 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 Log.i(TAG, "Removing system package:"+p.packageName);
6298 // When an updated system application is deleted we delete the existing resources as well and
6299 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006300 ret = deleteSystemPackageLI(p, flags, outInfo);
6301 } else {
6302 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006303 // Kill application pre-emptively especially for apps on sd.
6304 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006305 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006307 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006310 public void clearApplicationUserData(final String packageName,
6311 final IPackageDataObserver observer) {
6312 mContext.enforceCallingOrSelfPermission(
6313 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6314 // Queue up an async operation since the package deletion may take a little while.
6315 mHandler.post(new Runnable() {
6316 public void run() {
6317 mHandler.removeCallbacks(this);
6318 final boolean succeeded;
6319 synchronized (mInstallLock) {
6320 succeeded = clearApplicationUserDataLI(packageName);
6321 }
6322 if (succeeded) {
6323 // invoke DeviceStorageMonitor's update method to clear any notifications
6324 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6325 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6326 if (dsm != null) {
6327 dsm.updateMemory();
6328 }
6329 }
6330 if(observer != null) {
6331 try {
6332 observer.onRemoveCompleted(packageName, succeeded);
6333 } catch (RemoteException e) {
6334 Log.i(TAG, "Observer no longer exists.");
6335 }
6336 } //end if observer
6337 } //end run
6338 });
6339 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 private boolean clearApplicationUserDataLI(String packageName) {
6342 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006343 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 return false;
6345 }
6346 PackageParser.Package p;
6347 boolean dataOnly = false;
6348 synchronized (mPackages) {
6349 p = mPackages.get(packageName);
6350 if(p == null) {
6351 dataOnly = true;
6352 PackageSetting ps = mSettings.mPackages.get(packageName);
6353 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006354 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 return false;
6356 }
6357 p = ps.pkg;
6358 }
6359 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006360 boolean useEncryptedFSDir = false;
6361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 if(!dataOnly) {
6363 //need to check this only for fully installed applications
6364 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006365 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 return false;
6367 }
6368 final ApplicationInfo applicationInfo = p.applicationInfo;
6369 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006370 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 return false;
6372 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006373 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 }
6375 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006376 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006378 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006379 + packageName);
6380 return false;
6381 }
6382 }
6383 return true;
6384 }
6385
6386 public void deleteApplicationCacheFiles(final String packageName,
6387 final IPackageDataObserver observer) {
6388 mContext.enforceCallingOrSelfPermission(
6389 android.Manifest.permission.DELETE_CACHE_FILES, null);
6390 // Queue up an async operation since the package deletion may take a little while.
6391 mHandler.post(new Runnable() {
6392 public void run() {
6393 mHandler.removeCallbacks(this);
6394 final boolean succeded;
6395 synchronized (mInstallLock) {
6396 succeded = deleteApplicationCacheFilesLI(packageName);
6397 }
6398 if(observer != null) {
6399 try {
6400 observer.onRemoveCompleted(packageName, succeded);
6401 } catch (RemoteException e) {
6402 Log.i(TAG, "Observer no longer exists.");
6403 }
6404 } //end if observer
6405 } //end run
6406 });
6407 }
6408
6409 private boolean deleteApplicationCacheFilesLI(String packageName) {
6410 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006411 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 return false;
6413 }
6414 PackageParser.Package p;
6415 synchronized (mPackages) {
6416 p = mPackages.get(packageName);
6417 }
6418 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006419 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 return false;
6421 }
6422 final ApplicationInfo applicationInfo = p.applicationInfo;
6423 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006424 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 return false;
6426 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006427 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006429 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006431 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006432 + packageName);
6433 return false;
6434 }
6435 }
6436 return true;
6437 }
6438
6439 public void getPackageSizeInfo(final String packageName,
6440 final IPackageStatsObserver observer) {
6441 mContext.enforceCallingOrSelfPermission(
6442 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6443 // Queue up an async operation since the package deletion may take a little while.
6444 mHandler.post(new Runnable() {
6445 public void run() {
6446 mHandler.removeCallbacks(this);
6447 PackageStats lStats = new PackageStats(packageName);
6448 final boolean succeded;
6449 synchronized (mInstallLock) {
6450 succeded = getPackageSizeInfoLI(packageName, lStats);
6451 }
6452 if(observer != null) {
6453 try {
6454 observer.onGetStatsCompleted(lStats, succeded);
6455 } catch (RemoteException e) {
6456 Log.i(TAG, "Observer no longer exists.");
6457 }
6458 } //end if observer
6459 } //end run
6460 });
6461 }
6462
6463 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6464 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006465 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006466 return false;
6467 }
6468 PackageParser.Package p;
6469 boolean dataOnly = false;
6470 synchronized (mPackages) {
6471 p = mPackages.get(packageName);
6472 if(p == null) {
6473 dataOnly = true;
6474 PackageSetting ps = mSettings.mPackages.get(packageName);
6475 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006476 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 return false;
6478 }
6479 p = ps.pkg;
6480 }
6481 }
6482 String publicSrcDir = null;
6483 if(!dataOnly) {
6484 final ApplicationInfo applicationInfo = p.applicationInfo;
6485 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006486 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 return false;
6488 }
6489 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6490 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006491 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 if (mInstaller != null) {
6493 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006494 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 if (res < 0) {
6496 return false;
6497 } else {
6498 return true;
6499 }
6500 }
6501 return true;
6502 }
6503
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006505 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006506 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006507 }
6508
6509 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006510 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 }
6512
6513 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006514 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 }
6516
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006517 int getUidTargetSdkVersionLockedLP(int uid) {
6518 Object obj = mSettings.getUserIdLP(uid);
6519 if (obj instanceof SharedUserSetting) {
6520 SharedUserSetting sus = (SharedUserSetting)obj;
6521 final int N = sus.packages.size();
6522 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6523 Iterator<PackageSetting> it = sus.packages.iterator();
6524 int i=0;
6525 while (it.hasNext()) {
6526 PackageSetting ps = it.next();
6527 if (ps.pkg != null) {
6528 int v = ps.pkg.applicationInfo.targetSdkVersion;
6529 if (v < vers) vers = v;
6530 }
6531 }
6532 return vers;
6533 } else if (obj instanceof PackageSetting) {
6534 PackageSetting ps = (PackageSetting)obj;
6535 if (ps.pkg != null) {
6536 return ps.pkg.applicationInfo.targetSdkVersion;
6537 }
6538 }
6539 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6540 }
6541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006542 public void addPreferredActivity(IntentFilter filter, int match,
6543 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006545 if (mContext.checkCallingOrSelfPermission(
6546 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6547 != PackageManager.PERMISSION_GRANTED) {
6548 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6549 < Build.VERSION_CODES.FROYO) {
6550 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6551 + Binder.getCallingUid());
6552 return;
6553 }
6554 mContext.enforceCallingOrSelfPermission(
6555 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6556 }
6557
6558 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6560 mSettings.mPreferredActivities.addFilter(
6561 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006562 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006563 }
6564 }
6565
Satish Sampath8dbe6122009-06-02 23:35:54 +01006566 public void replacePreferredActivity(IntentFilter filter, int match,
6567 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006568 if (filter.countActions() != 1) {
6569 throw new IllegalArgumentException(
6570 "replacePreferredActivity expects filter to have only 1 action.");
6571 }
6572 if (filter.countCategories() != 1) {
6573 throw new IllegalArgumentException(
6574 "replacePreferredActivity expects filter to have only 1 category.");
6575 }
6576 if (filter.countDataAuthorities() != 0
6577 || filter.countDataPaths() != 0
6578 || filter.countDataSchemes() != 0
6579 || filter.countDataTypes() != 0) {
6580 throw new IllegalArgumentException(
6581 "replacePreferredActivity expects filter to have no data authorities, " +
6582 "paths, schemes or types.");
6583 }
6584 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006585 if (mContext.checkCallingOrSelfPermission(
6586 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6587 != PackageManager.PERMISSION_GRANTED) {
6588 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6589 < Build.VERSION_CODES.FROYO) {
6590 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6591 + Binder.getCallingUid());
6592 return;
6593 }
6594 mContext.enforceCallingOrSelfPermission(
6595 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6596 }
6597
Satish Sampath8dbe6122009-06-02 23:35:54 +01006598 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6599 String action = filter.getAction(0);
6600 String category = filter.getCategory(0);
6601 while (it.hasNext()) {
6602 PreferredActivity pa = it.next();
6603 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6604 it.remove();
6605 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6606 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6607 }
6608 }
6609 addPreferredActivity(filter, match, set, activity);
6610 }
6611 }
6612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006615 int uid = Binder.getCallingUid();
6616 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006617 if (pkg == null || pkg.applicationInfo.uid != uid) {
6618 if (mContext.checkCallingOrSelfPermission(
6619 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6620 != PackageManager.PERMISSION_GRANTED) {
6621 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6622 < Build.VERSION_CODES.FROYO) {
6623 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6624 + Binder.getCallingUid());
6625 return;
6626 }
6627 mContext.enforceCallingOrSelfPermission(
6628 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6629 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006630 }
6631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006633 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006634 }
6635 }
6636 }
6637
6638 boolean clearPackagePreferredActivitiesLP(String packageName) {
6639 boolean changed = false;
6640 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6641 while (it.hasNext()) {
6642 PreferredActivity pa = it.next();
6643 if (pa.mActivity.getPackageName().equals(packageName)) {
6644 it.remove();
6645 changed = true;
6646 }
6647 }
6648 return changed;
6649 }
6650
6651 public int getPreferredActivities(List<IntentFilter> outFilters,
6652 List<ComponentName> outActivities, String packageName) {
6653
6654 int num = 0;
6655 synchronized (mPackages) {
6656 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6657 while (it.hasNext()) {
6658 PreferredActivity pa = it.next();
6659 if (packageName == null
6660 || pa.mActivity.getPackageName().equals(packageName)) {
6661 if (outFilters != null) {
6662 outFilters.add(new IntentFilter(pa));
6663 }
6664 if (outActivities != null) {
6665 outActivities.add(pa.mActivity);
6666 }
6667 }
6668 }
6669 }
6670
6671 return num;
6672 }
6673
6674 public void setApplicationEnabledSetting(String appPackageName,
6675 int newState, int flags) {
6676 setEnabledSetting(appPackageName, null, newState, flags);
6677 }
6678
6679 public void setComponentEnabledSetting(ComponentName componentName,
6680 int newState, int flags) {
6681 setEnabledSetting(componentName.getPackageName(),
6682 componentName.getClassName(), newState, flags);
6683 }
6684
6685 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006686 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6688 || newState == COMPONENT_ENABLED_STATE_ENABLED
6689 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6690 throw new IllegalArgumentException("Invalid new component state: "
6691 + newState);
6692 }
6693 PackageSetting pkgSetting;
6694 final int uid = Binder.getCallingUid();
6695 final int permission = mContext.checkCallingPermission(
6696 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6697 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006698 boolean sendNow = false;
6699 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006700 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006702 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006703 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006704 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006705 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006706 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006708 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006709 }
6710 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006711 "Unknown component: " + packageName
6712 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006713 }
6714 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6715 throw new SecurityException(
6716 "Permission Denial: attempt to change component state from pid="
6717 + Binder.getCallingPid()
6718 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6719 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006720 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006721 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006722 if (pkgSetting.enabled == newState) {
6723 // Nothing to do
6724 return;
6725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006726 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006727 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 } else {
6729 // We're dealing with a component level state change
6730 switch (newState) {
6731 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006732 if (!pkgSetting.enableComponentLP(className)) {
6733 return;
6734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 break;
6736 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006737 if (!pkgSetting.disableComponentLP(className)) {
6738 return;
6739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 break;
6741 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006742 if (!pkgSetting.restoreComponentLP(className)) {
6743 return;
6744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 break;
6746 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006747 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006748 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006749 }
6750 }
6751 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006752 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006753 components = mPendingBroadcasts.get(packageName);
6754 boolean newPackage = components == null;
6755 if (newPackage) {
6756 components = new ArrayList<String>();
6757 }
6758 if (!components.contains(componentName)) {
6759 components.add(componentName);
6760 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006761 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6762 sendNow = true;
6763 // Purge entry from pending broadcast list if another one exists already
6764 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006765 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006766 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006767 if (newPackage) {
6768 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006769 }
6770 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6771 // Schedule a message
6772 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6773 }
6774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006777 long callingId = Binder.clearCallingIdentity();
6778 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006779 if (sendNow) {
6780 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006781 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 } finally {
6784 Binder.restoreCallingIdentity(callingId);
6785 }
6786 }
6787
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006788 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006789 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6790 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6791 + " components=" + componentNames);
6792 Bundle extras = new Bundle(4);
6793 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6794 String nameList[] = new String[componentNames.size()];
6795 componentNames.toArray(nameList);
6796 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006797 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6798 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006799 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006800 }
6801
Jacek Surazski65e13172009-04-28 15:26:38 +02006802 public String getInstallerPackageName(String packageName) {
6803 synchronized (mPackages) {
6804 PackageSetting pkg = mSettings.mPackages.get(packageName);
6805 if (pkg == null) {
6806 throw new IllegalArgumentException("Unknown package: " + packageName);
6807 }
6808 return pkg.installerPackageName;
6809 }
6810 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006812 public int getApplicationEnabledSetting(String appPackageName) {
6813 synchronized (mPackages) {
6814 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6815 if (pkg == null) {
6816 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6817 }
6818 return pkg.enabled;
6819 }
6820 }
6821
6822 public int getComponentEnabledSetting(ComponentName componentName) {
6823 synchronized (mPackages) {
6824 final String packageNameStr = componentName.getPackageName();
6825 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6826 if (pkg == null) {
6827 throw new IllegalArgumentException("Unknown component: " + componentName);
6828 }
6829 final String classNameStr = componentName.getClassName();
6830 return pkg.currentEnabledStateLP(classNameStr);
6831 }
6832 }
6833
6834 public void enterSafeMode() {
6835 if (!mSystemReady) {
6836 mSafeMode = true;
6837 }
6838 }
6839
6840 public void systemReady() {
6841 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006842
6843 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006844 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006845 mContext.getContentResolver(),
6846 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006847 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006848 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006849 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006851 }
6852
6853 public boolean isSafeMode() {
6854 return mSafeMode;
6855 }
6856
6857 public boolean hasSystemUidErrors() {
6858 return mHasSystemUidErrors;
6859 }
6860
6861 static String arrayToString(int[] array) {
6862 StringBuffer buf = new StringBuffer(128);
6863 buf.append('[');
6864 if (array != null) {
6865 for (int i=0; i<array.length; i++) {
6866 if (i > 0) buf.append(", ");
6867 buf.append(array[i]);
6868 }
6869 }
6870 buf.append(']');
6871 return buf.toString();
6872 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 @Override
6875 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6876 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6877 != PackageManager.PERMISSION_GRANTED) {
6878 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6879 + Binder.getCallingPid()
6880 + ", uid=" + Binder.getCallingUid()
6881 + " without permission "
6882 + android.Manifest.permission.DUMP);
6883 return;
6884 }
6885
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006886 String packageName = null;
6887
6888 int opti = 0;
6889 while (opti < args.length) {
6890 String opt = args[opti];
6891 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6892 break;
6893 }
6894 opti++;
6895 if ("-a".equals(opt)) {
6896 // Right now we only know how to print all.
6897 } else if ("-h".equals(opt)) {
6898 pw.println("Package manager dump options:");
6899 pw.println(" [-h] [cmd] ...");
6900 pw.println(" cmd may be one of:");
6901 pw.println(" [package.name]: info about given package");
6902 return;
6903 } else {
6904 pw.println("Unknown argument: " + opt + "; use -h for help");
6905 }
6906 }
6907
6908 // Is the caller requesting to dump a particular piece of data?
6909 if (opti < args.length) {
6910 String cmd = args[opti];
6911 opti++;
6912 // Is this a package name?
6913 if ("android".equals(cmd) || cmd.contains(".")) {
6914 packageName = cmd;
6915 }
6916 }
6917
6918 boolean printedTitle = false;
6919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006920 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006921 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6922 printedTitle = true;
6923 }
6924 if (mReceivers.dump(pw, printedTitle
6925 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6926 " ", packageName)) {
6927 printedTitle = true;
6928 }
6929 if (mServices.dump(pw, printedTitle
6930 ? "\nService Resolver Table:" : "Service Resolver Table:",
6931 " ", packageName)) {
6932 printedTitle = true;
6933 }
6934 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6935 ? "\nPreferred Activities:" : "Preferred Activities:",
6936 " ", packageName)) {
6937 printedTitle = true;
6938 }
6939 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006940 {
6941 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006942 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6943 continue;
6944 }
6945 if (!printedSomething) {
6946 if (printedTitle) pw.println(" ");
6947 pw.println("Permissions:");
6948 printedSomething = true;
6949 printedTitle = true;
6950 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006951 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6952 pw.print(Integer.toHexString(System.identityHashCode(p)));
6953 pw.println("):");
6954 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6955 pw.print(" uid="); pw.print(p.uid);
6956 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006957 pw.print(" type="); pw.print(p.type);
6958 pw.print(" prot="); pw.println(p.protectionLevel);
6959 if (p.packageSetting != null) {
6960 pw.print(" packageSetting="); pw.println(p.packageSetting);
6961 }
6962 if (p.perm != null) {
6963 pw.print(" perm="); pw.println(p.perm);
6964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006965 }
6966 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006967 printedSomething = false;
6968 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 {
6970 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006971 if (packageName != null && !packageName.equals(ps.realName)
6972 && !packageName.equals(ps.name)) {
6973 continue;
6974 }
6975 if (!printedSomething) {
6976 if (printedTitle) pw.println(" ");
6977 pw.println("Packages:");
6978 printedSomething = true;
6979 printedTitle = true;
6980 }
6981 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006982 pw.print(" Package [");
6983 pw.print(ps.realName != null ? ps.realName : ps.name);
6984 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006985 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6986 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006987 if (ps.realName != null) {
6988 pw.print(" compat name="); pw.println(ps.name);
6989 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006990 pw.print(" userId="); pw.print(ps.userId);
6991 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6992 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6993 pw.print(" pkg="); pw.println(ps.pkg);
6994 pw.print(" codePath="); pw.println(ps.codePathString);
6995 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07006996 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07006997 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006999 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007000 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007001 if (ps.pkg.mOperationPending) {
7002 pw.println(" mOperationPending=true");
7003 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007004 pw.print(" supportsScreens=[");
7005 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007006 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007007 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7008 if (!first) pw.print(", ");
7009 first = false;
7010 pw.print("small");
7011 }
7012 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007013 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007014 if (!first) pw.print(", ");
7015 first = false;
7016 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007018 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007019 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007020 if (!first) pw.print(", ");
7021 first = false;
7022 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007023 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007024 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007025 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007026 if (!first) pw.print(", ");
7027 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007028 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007029 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007030 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007031 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007032 if (!first) pw.print(", ");
7033 first = false;
7034 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007035 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007036 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007037 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7038 if (!first) pw.print(", ");
7039 first = false;
7040 pw.print("anyDensity");
7041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007042 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007043 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007044 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7045 pw.print(" signatures="); pw.println(ps.signatures);
7046 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007047 pw.print(" haveGids="); pw.println(ps.haveGids);
7048 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007049 pw.print(" installStatus="); pw.print(ps.installStatus);
7050 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007051 if (ps.disabledComponents.size() > 0) {
7052 pw.println(" disabledComponents:");
7053 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007054 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055 }
7056 }
7057 if (ps.enabledComponents.size() > 0) {
7058 pw.println(" enabledComponents:");
7059 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007060 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061 }
7062 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007063 if (ps.grantedPermissions.size() > 0) {
7064 pw.println(" grantedPermissions:");
7065 for (String s : ps.grantedPermissions) {
7066 pw.print(" "); pw.println(s);
7067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007069 }
7070 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007071 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007072 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007073 for (HashMap.Entry<String, String> e
7074 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007075 if (packageName != null && !packageName.equals(e.getKey())
7076 && !packageName.equals(e.getValue())) {
7077 continue;
7078 }
7079 if (!printedSomething) {
7080 if (printedTitle) pw.println(" ");
7081 pw.println("Renamed packages:");
7082 printedSomething = true;
7083 printedTitle = true;
7084 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007085 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7086 pw.println(e.getValue());
7087 }
7088 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007089 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007090 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007091 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007092 if (packageName != null && !packageName.equals(ps.realName)
7093 && !packageName.equals(ps.name)) {
7094 continue;
7095 }
7096 if (!printedSomething) {
7097 if (printedTitle) pw.println(" ");
7098 pw.println("Hidden system packages:");
7099 printedSomething = true;
7100 printedTitle = true;
7101 }
7102 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007103 pw.print(ps.realName != null ? ps.realName : ps.name);
7104 pw.print("] (");
7105 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7106 pw.println("):");
7107 if (ps.realName != null) {
7108 pw.print(" compat name="); pw.println(ps.name);
7109 }
7110 pw.print(" userId="); pw.println(ps.userId);
7111 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7112 pw.print(" codePath="); pw.println(ps.codePathString);
7113 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7114 }
7115 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007116 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 {
7118 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007119 if (packageName != null && su != packageSharedUser) {
7120 continue;
7121 }
7122 if (!printedSomething) {
7123 if (printedTitle) pw.println(" ");
7124 pw.println("Shared users:");
7125 printedSomething = true;
7126 printedTitle = true;
7127 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007128 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7129 pw.print(Integer.toHexString(System.identityHashCode(su)));
7130 pw.println("):");
7131 pw.print(" userId="); pw.print(su.userId);
7132 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007133 pw.println(" grantedPermissions:");
7134 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007135 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007137 }
7138 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007139
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007140 if (packageName == null) {
7141 if (printedTitle) pw.println(" ");
7142 printedTitle = true;
7143 pw.println("Settings parse messages:");
7144 pw.println(mSettings.mReadMessages.toString());
7145
7146 pw.println(" ");
7147 pw.println("Package warning messages:");
7148 File fname = getSettingsProblemFile();
7149 FileInputStream in;
7150 try {
7151 in = new FileInputStream(fname);
7152 int avail = in.available();
7153 byte[] data = new byte[avail];
7154 in.read(data);
7155 pw.println(new String(data));
7156 } catch (FileNotFoundException e) {
7157 } catch (IOException e) {
7158 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007160 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007161
7162 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007163 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007164 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007165 if (packageName != null && !packageName.equals(p.info.packageName)) {
7166 continue;
7167 }
7168 if (!printedSomething) {
7169 if (printedTitle) pw.println(" ");
7170 pw.println("Registered ContentProviders:");
7171 printedSomething = true;
7172 printedTitle = true;
7173 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007174 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007175 pw.println(p.toString());
7176 }
7177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 }
7179
7180 static final class BasePermission {
7181 final static int TYPE_NORMAL = 0;
7182 final static int TYPE_BUILTIN = 1;
7183 final static int TYPE_DYNAMIC = 2;
7184
7185 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007186 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007187 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007188 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007189 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 PackageParser.Permission perm;
7191 PermissionInfo pendingInfo;
7192 int uid;
7193 int[] gids;
7194
7195 BasePermission(String _name, String _sourcePackage, int _type) {
7196 name = _name;
7197 sourcePackage = _sourcePackage;
7198 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007199 // Default to most conservative protection level.
7200 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7201 }
7202
7203 public String toString() {
7204 return "BasePermission{"
7205 + Integer.toHexString(System.identityHashCode(this))
7206 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007207 }
7208 }
7209
7210 static class PackageSignatures {
7211 private Signature[] mSignatures;
7212
7213 PackageSignatures(Signature[] sigs) {
7214 assignSignatures(sigs);
7215 }
7216
7217 PackageSignatures() {
7218 }
7219
7220 void writeXml(XmlSerializer serializer, String tagName,
7221 ArrayList<Signature> pastSignatures) throws IOException {
7222 if (mSignatures == null) {
7223 return;
7224 }
7225 serializer.startTag(null, tagName);
7226 serializer.attribute(null, "count",
7227 Integer.toString(mSignatures.length));
7228 for (int i=0; i<mSignatures.length; i++) {
7229 serializer.startTag(null, "cert");
7230 final Signature sig = mSignatures[i];
7231 final int sigHash = sig.hashCode();
7232 final int numPast = pastSignatures.size();
7233 int j;
7234 for (j=0; j<numPast; j++) {
7235 Signature pastSig = pastSignatures.get(j);
7236 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7237 serializer.attribute(null, "index", Integer.toString(j));
7238 break;
7239 }
7240 }
7241 if (j >= numPast) {
7242 pastSignatures.add(sig);
7243 serializer.attribute(null, "index", Integer.toString(numPast));
7244 serializer.attribute(null, "key", sig.toCharsString());
7245 }
7246 serializer.endTag(null, "cert");
7247 }
7248 serializer.endTag(null, tagName);
7249 }
7250
7251 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7252 throws IOException, XmlPullParserException {
7253 String countStr = parser.getAttributeValue(null, "count");
7254 if (countStr == null) {
7255 reportSettingsProblem(Log.WARN,
7256 "Error in package manager settings: <signatures> has"
7257 + " no count at " + parser.getPositionDescription());
7258 XmlUtils.skipCurrentTag(parser);
7259 }
7260 final int count = Integer.parseInt(countStr);
7261 mSignatures = new Signature[count];
7262 int pos = 0;
7263
7264 int outerDepth = parser.getDepth();
7265 int type;
7266 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7267 && (type != XmlPullParser.END_TAG
7268 || parser.getDepth() > outerDepth)) {
7269 if (type == XmlPullParser.END_TAG
7270 || type == XmlPullParser.TEXT) {
7271 continue;
7272 }
7273
7274 String tagName = parser.getName();
7275 if (tagName.equals("cert")) {
7276 if (pos < count) {
7277 String index = parser.getAttributeValue(null, "index");
7278 if (index != null) {
7279 try {
7280 int idx = Integer.parseInt(index);
7281 String key = parser.getAttributeValue(null, "key");
7282 if (key == null) {
7283 if (idx >= 0 && idx < pastSignatures.size()) {
7284 Signature sig = pastSignatures.get(idx);
7285 if (sig != null) {
7286 mSignatures[pos] = pastSignatures.get(idx);
7287 pos++;
7288 } else {
7289 reportSettingsProblem(Log.WARN,
7290 "Error in package manager settings: <cert> "
7291 + "index " + index + " is not defined at "
7292 + parser.getPositionDescription());
7293 }
7294 } else {
7295 reportSettingsProblem(Log.WARN,
7296 "Error in package manager settings: <cert> "
7297 + "index " + index + " is out of bounds at "
7298 + parser.getPositionDescription());
7299 }
7300 } else {
7301 while (pastSignatures.size() <= idx) {
7302 pastSignatures.add(null);
7303 }
7304 Signature sig = new Signature(key);
7305 pastSignatures.set(idx, sig);
7306 mSignatures[pos] = sig;
7307 pos++;
7308 }
7309 } catch (NumberFormatException e) {
7310 reportSettingsProblem(Log.WARN,
7311 "Error in package manager settings: <cert> "
7312 + "index " + index + " is not a number at "
7313 + parser.getPositionDescription());
7314 }
7315 } else {
7316 reportSettingsProblem(Log.WARN,
7317 "Error in package manager settings: <cert> has"
7318 + " no index at " + parser.getPositionDescription());
7319 }
7320 } else {
7321 reportSettingsProblem(Log.WARN,
7322 "Error in package manager settings: too "
7323 + "many <cert> tags, expected " + count
7324 + " at " + parser.getPositionDescription());
7325 }
7326 } else {
7327 reportSettingsProblem(Log.WARN,
7328 "Unknown element under <cert>: "
7329 + parser.getName());
7330 }
7331 XmlUtils.skipCurrentTag(parser);
7332 }
7333
7334 if (pos < count) {
7335 // Should never happen -- there is an error in the written
7336 // settings -- but if it does we don't want to generate
7337 // a bad array.
7338 Signature[] newSigs = new Signature[pos];
7339 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7340 mSignatures = newSigs;
7341 }
7342 }
7343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 private void assignSignatures(Signature[] sigs) {
7345 if (sigs == null) {
7346 mSignatures = null;
7347 return;
7348 }
7349 mSignatures = new Signature[sigs.length];
7350 for (int i=0; i<sigs.length; i++) {
7351 mSignatures[i] = sigs[i];
7352 }
7353 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007355 @Override
7356 public String toString() {
7357 StringBuffer buf = new StringBuffer(128);
7358 buf.append("PackageSignatures{");
7359 buf.append(Integer.toHexString(System.identityHashCode(this)));
7360 buf.append(" [");
7361 if (mSignatures != null) {
7362 for (int i=0; i<mSignatures.length; i++) {
7363 if (i > 0) buf.append(", ");
7364 buf.append(Integer.toHexString(
7365 System.identityHashCode(mSignatures[i])));
7366 }
7367 }
7368 buf.append("]}");
7369 return buf.toString();
7370 }
7371 }
7372
7373 static class PreferredActivity extends IntentFilter {
7374 final int mMatch;
7375 final String[] mSetPackages;
7376 final String[] mSetClasses;
7377 final String[] mSetComponents;
7378 final ComponentName mActivity;
7379 final String mShortActivity;
7380 String mParseError;
7381
7382 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7383 ComponentName activity) {
7384 super(filter);
7385 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7386 mActivity = activity;
7387 mShortActivity = activity.flattenToShortString();
7388 mParseError = null;
7389 if (set != null) {
7390 final int N = set.length;
7391 String[] myPackages = new String[N];
7392 String[] myClasses = new String[N];
7393 String[] myComponents = new String[N];
7394 for (int i=0; i<N; i++) {
7395 ComponentName cn = set[i];
7396 if (cn == null) {
7397 mSetPackages = null;
7398 mSetClasses = null;
7399 mSetComponents = null;
7400 return;
7401 }
7402 myPackages[i] = cn.getPackageName().intern();
7403 myClasses[i] = cn.getClassName().intern();
7404 myComponents[i] = cn.flattenToShortString().intern();
7405 }
7406 mSetPackages = myPackages;
7407 mSetClasses = myClasses;
7408 mSetComponents = myComponents;
7409 } else {
7410 mSetPackages = null;
7411 mSetClasses = null;
7412 mSetComponents = null;
7413 }
7414 }
7415
7416 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7417 IOException {
7418 mShortActivity = parser.getAttributeValue(null, "name");
7419 mActivity = ComponentName.unflattenFromString(mShortActivity);
7420 if (mActivity == null) {
7421 mParseError = "Bad activity name " + mShortActivity;
7422 }
7423 String matchStr = parser.getAttributeValue(null, "match");
7424 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7425 String setCountStr = parser.getAttributeValue(null, "set");
7426 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7427
7428 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7429 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7430 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7431
7432 int setPos = 0;
7433
7434 int outerDepth = parser.getDepth();
7435 int type;
7436 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7437 && (type != XmlPullParser.END_TAG
7438 || parser.getDepth() > outerDepth)) {
7439 if (type == XmlPullParser.END_TAG
7440 || type == XmlPullParser.TEXT) {
7441 continue;
7442 }
7443
7444 String tagName = parser.getName();
7445 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7446 // + parser.getDepth() + " tag=" + tagName);
7447 if (tagName.equals("set")) {
7448 String name = parser.getAttributeValue(null, "name");
7449 if (name == null) {
7450 if (mParseError == null) {
7451 mParseError = "No name in set tag in preferred activity "
7452 + mShortActivity;
7453 }
7454 } else if (setPos >= setCount) {
7455 if (mParseError == null) {
7456 mParseError = "Too many set tags in preferred activity "
7457 + mShortActivity;
7458 }
7459 } else {
7460 ComponentName cn = ComponentName.unflattenFromString(name);
7461 if (cn == null) {
7462 if (mParseError == null) {
7463 mParseError = "Bad set name " + name + " in preferred activity "
7464 + mShortActivity;
7465 }
7466 } else {
7467 myPackages[setPos] = cn.getPackageName();
7468 myClasses[setPos] = cn.getClassName();
7469 myComponents[setPos] = name;
7470 setPos++;
7471 }
7472 }
7473 XmlUtils.skipCurrentTag(parser);
7474 } else if (tagName.equals("filter")) {
7475 //Log.i(TAG, "Starting to parse filter...");
7476 readFromXml(parser);
7477 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7478 // + parser.getDepth() + " tag=" + parser.getName());
7479 } else {
7480 reportSettingsProblem(Log.WARN,
7481 "Unknown element under <preferred-activities>: "
7482 + parser.getName());
7483 XmlUtils.skipCurrentTag(parser);
7484 }
7485 }
7486
7487 if (setPos != setCount) {
7488 if (mParseError == null) {
7489 mParseError = "Not enough set tags (expected " + setCount
7490 + " but found " + setPos + ") in " + mShortActivity;
7491 }
7492 }
7493
7494 mSetPackages = myPackages;
7495 mSetClasses = myClasses;
7496 mSetComponents = myComponents;
7497 }
7498
7499 public void writeToXml(XmlSerializer serializer) throws IOException {
7500 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7501 serializer.attribute(null, "name", mShortActivity);
7502 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7503 serializer.attribute(null, "set", Integer.toString(NS));
7504 for (int s=0; s<NS; s++) {
7505 serializer.startTag(null, "set");
7506 serializer.attribute(null, "name", mSetComponents[s]);
7507 serializer.endTag(null, "set");
7508 }
7509 serializer.startTag(null, "filter");
7510 super.writeToXml(serializer);
7511 serializer.endTag(null, "filter");
7512 }
7513
7514 boolean sameSet(List<ResolveInfo> query, int priority) {
7515 if (mSetPackages == null) return false;
7516 final int NQ = query.size();
7517 final int NS = mSetPackages.length;
7518 int numMatch = 0;
7519 for (int i=0; i<NQ; i++) {
7520 ResolveInfo ri = query.get(i);
7521 if (ri.priority != priority) continue;
7522 ActivityInfo ai = ri.activityInfo;
7523 boolean good = false;
7524 for (int j=0; j<NS; j++) {
7525 if (mSetPackages[j].equals(ai.packageName)
7526 && mSetClasses[j].equals(ai.name)) {
7527 numMatch++;
7528 good = true;
7529 break;
7530 }
7531 }
7532 if (!good) return false;
7533 }
7534 return numMatch == NS;
7535 }
7536 }
7537
7538 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007539 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007541 HashSet<String> grantedPermissions = new HashSet<String>();
7542 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007544 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007545 setFlags(pkgFlags);
7546 }
7547
7548 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007549 this.pkgFlags = pkgFlags & (
7550 ApplicationInfo.FLAG_SYSTEM |
7551 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007552 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007553 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554 }
7555 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007557 /**
7558 * Settings base class for pending and resolved classes.
7559 */
7560 static class PackageSettingBase extends GrantedPermissions {
7561 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007562 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007563 File codePath;
7564 String codePathString;
7565 File resourcePath;
7566 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007567 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007568 String obbPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007569 private long timeStamp;
7570 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007571 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007572
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007573 boolean uidError;
7574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007575 PackageSignatures signatures = new PackageSignatures();
7576
7577 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007578 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007580 /* Explicitly disabled components */
7581 HashSet<String> disabledComponents = new HashSet<String>(0);
7582 /* Explicitly enabled components */
7583 HashSet<String> enabledComponents = new HashSet<String>(0);
7584 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7585 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007586
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007587 PackageSettingBase origPackage;
7588
Jacek Surazski65e13172009-04-28 15:26:38 +02007589 /* package name of the app that installed this package */
7590 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007591
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007592 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007593 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 super(pkgFlags);
7595 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007596 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007597 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007598 }
7599
Kenny Root806cc132010-09-12 08:34:19 -07007600 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7601 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007602 this.codePath = codePath;
7603 this.codePathString = codePath.toString();
7604 this.resourcePath = resourcePath;
7605 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007606 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007607 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 }
Kenny Root85387d72010-08-26 10:13:11 -07007609
Jacek Surazski65e13172009-04-28 15:26:38 +02007610 public void setInstallerPackageName(String packageName) {
7611 installerPackageName = packageName;
7612 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007613
Jacek Surazski65e13172009-04-28 15:26:38 +02007614 String getInstallerPackageName() {
7615 return installerPackageName;
7616 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007618 public void setInstallStatus(int newStatus) {
7619 installStatus = newStatus;
7620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007622 public int getInstallStatus() {
7623 return installStatus;
7624 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007626 public void setTimeStamp(long newStamp) {
7627 if (newStamp != timeStamp) {
7628 timeStamp = newStamp;
7629 timeStampString = Long.toString(newStamp);
7630 }
7631 }
7632
7633 public void setTimeStamp(long newStamp, String newStampStr) {
7634 timeStamp = newStamp;
7635 timeStampString = newStampStr;
7636 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007638 public long getTimeStamp() {
7639 return timeStamp;
7640 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007642 public String getTimeStampStr() {
7643 return timeStampString;
7644 }
7645
7646 public void copyFrom(PackageSettingBase base) {
7647 grantedPermissions = base.grantedPermissions;
7648 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007650 timeStamp = base.timeStamp;
7651 timeStampString = base.timeStampString;
7652 signatures = base.signatures;
7653 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007654 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007655 disabledComponents = base.disabledComponents;
7656 enabledComponents = base.enabledComponents;
7657 enabled = base.enabled;
7658 installStatus = base.installStatus;
7659 }
7660
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007661 boolean enableComponentLP(String componentClassName) {
7662 boolean changed = disabledComponents.remove(componentClassName);
7663 changed |= enabledComponents.add(componentClassName);
7664 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007665 }
7666
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007667 boolean disableComponentLP(String componentClassName) {
7668 boolean changed = enabledComponents.remove(componentClassName);
7669 changed |= disabledComponents.add(componentClassName);
7670 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007671 }
7672
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007673 boolean restoreComponentLP(String componentClassName) {
7674 boolean changed = enabledComponents.remove(componentClassName);
7675 changed |= disabledComponents.remove(componentClassName);
7676 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007677 }
7678
7679 int currentEnabledStateLP(String componentName) {
7680 if (enabledComponents.contains(componentName)) {
7681 return COMPONENT_ENABLED_STATE_ENABLED;
7682 } else if (disabledComponents.contains(componentName)) {
7683 return COMPONENT_ENABLED_STATE_DISABLED;
7684 } else {
7685 return COMPONENT_ENABLED_STATE_DEFAULT;
7686 }
7687 }
7688 }
7689
7690 /**
7691 * Settings data for a particular package we know about.
7692 */
7693 static final class PackageSetting extends PackageSettingBase {
7694 int userId;
7695 PackageParser.Package pkg;
7696 SharedUserSetting sharedUser;
7697
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007698 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007699 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7700 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7701 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007704 @Override
7705 public String toString() {
7706 return "PackageSetting{"
7707 + Integer.toHexString(System.identityHashCode(this))
7708 + " " + name + "/" + userId + "}";
7709 }
7710 }
7711
7712 /**
7713 * Settings data for a particular shared user ID we know about.
7714 */
7715 static final class SharedUserSetting extends GrantedPermissions {
7716 final String name;
7717 int userId;
7718 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7719 final PackageSignatures signatures = new PackageSignatures();
7720
7721 SharedUserSetting(String _name, int _pkgFlags) {
7722 super(_pkgFlags);
7723 name = _name;
7724 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726 @Override
7727 public String toString() {
7728 return "SharedUserSetting{"
7729 + Integer.toHexString(System.identityHashCode(this))
7730 + " " + name + "/" + userId + "}";
7731 }
7732 }
7733
7734 /**
7735 * Holds information about dynamic settings.
7736 */
7737 private static final class Settings {
7738 private final File mSettingsFilename;
7739 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007740 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007741 private final HashMap<String, PackageSetting> mPackages =
7742 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007743 // List of replaced system applications
7744 final HashMap<String, PackageSetting> mDisabledSysPackages =
7745 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007746
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007747 // These are the last platform API version we were using for
7748 // the apps installed on internal and external storage. It is
7749 // used to grant newer permissions one time during a system upgrade.
7750 int mInternalSdkPlatform;
7751 int mExternalSdkPlatform;
7752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753 // The user's preferred activities associated with particular intent
7754 // filters.
7755 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7756 new IntentResolver<PreferredActivity, PreferredActivity>() {
7757 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007758 protected String packageForFilter(PreferredActivity filter) {
7759 return filter.mActivity.getPackageName();
7760 }
7761 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007762 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007764 out.print(prefix); out.print(
7765 Integer.toHexString(System.identityHashCode(filter)));
7766 out.print(' ');
7767 out.print(filter.mActivity.flattenToShortString());
7768 out.print(" match=0x");
7769 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007770 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007771 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007772 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007773 out.print(prefix); out.print(" ");
7774 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007775 }
7776 }
7777 }
7778 };
7779 private final HashMap<String, SharedUserSetting> mSharedUsers =
7780 new HashMap<String, SharedUserSetting>();
7781 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7782 private final SparseArray<Object> mOtherUserIds =
7783 new SparseArray<Object>();
7784
7785 // For reading/writing settings file.
7786 private final ArrayList<Signature> mPastSignatures =
7787 new ArrayList<Signature>();
7788
7789 // Mapping from permission names to info about them.
7790 final HashMap<String, BasePermission> mPermissions =
7791 new HashMap<String, BasePermission>();
7792
7793 // Mapping from permission tree names to info about them.
7794 final HashMap<String, BasePermission> mPermissionTrees =
7795 new HashMap<String, BasePermission>();
7796
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007797 // Packages that have been uninstalled and still need their external
7798 // storage data deleted.
7799 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7800
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007801 // Packages that have been renamed since they were first installed.
7802 // Keys are the new names of the packages, values are the original
7803 // names. The packages appear everwhere else under their original
7804 // names.
7805 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 private final StringBuilder mReadMessages = new StringBuilder();
7808
7809 private static final class PendingPackage extends PackageSettingBase {
7810 final int sharedId;
7811
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007812 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007813 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7814 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7815 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816 this.sharedId = sharedId;
7817 }
7818 }
7819 private final ArrayList<PendingPackage> mPendingPackages
7820 = new ArrayList<PendingPackage>();
7821
7822 Settings() {
7823 File dataDir = Environment.getDataDirectory();
7824 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007825 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7826 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007827 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007828 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007829 FileUtils.setPermissions(systemDir.toString(),
7830 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7831 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7832 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007833 FileUtils.setPermissions(systemSecureDir.toString(),
7834 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7835 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7836 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007837 mSettingsFilename = new File(systemDir, "packages.xml");
7838 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007839 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007840 }
7841
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007842 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007843 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007844 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007845 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007846 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007847 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 return p;
7849 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007850
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007851 PackageSetting peekPackageLP(String name) {
7852 return mPackages.get(name);
7853 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007854 PackageSetting p = mPackages.get(name);
7855 if (p != null && p.codePath.getPath().equals(codePath)) {
7856 return p;
7857 }
7858 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007859 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 void setInstallStatus(String pkgName, int status) {
7863 PackageSetting p = mPackages.get(pkgName);
7864 if(p != null) {
7865 if(p.getInstallStatus() != status) {
7866 p.setInstallStatus(status);
7867 }
7868 }
7869 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007870
Jacek Surazski65e13172009-04-28 15:26:38 +02007871 void setInstallerPackageName(String pkgName,
7872 String installerPkgName) {
7873 PackageSetting p = mPackages.get(pkgName);
7874 if(p != null) {
7875 p.setInstallerPackageName(installerPkgName);
7876 }
7877 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007878
Jacek Surazski65e13172009-04-28 15:26:38 +02007879 String getInstallerPackageName(String pkgName) {
7880 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007881 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007882 }
7883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 int getInstallStatus(String pkgName) {
7885 PackageSetting p = mPackages.get(pkgName);
7886 if(p != null) {
7887 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 return -1;
7890 }
7891
7892 SharedUserSetting getSharedUserLP(String name,
7893 int pkgFlags, boolean create) {
7894 SharedUserSetting s = mSharedUsers.get(name);
7895 if (s == null) {
7896 if (!create) {
7897 return null;
7898 }
7899 s = new SharedUserSetting(name, pkgFlags);
7900 if (MULTIPLE_APPLICATION_UIDS) {
7901 s.userId = newUserIdLP(s);
7902 } else {
7903 s.userId = FIRST_APPLICATION_UID;
7904 }
7905 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7906 // < 0 means we couldn't assign a userid; fall out and return
7907 // s, which is currently null
7908 if (s.userId >= 0) {
7909 mSharedUsers.put(name, s);
7910 }
7911 }
7912
7913 return s;
7914 }
7915
7916 int disableSystemPackageLP(String name) {
7917 PackageSetting p = mPackages.get(name);
7918 if(p == null) {
7919 Log.w(TAG, "Package:"+name+" is not an installed package");
7920 return -1;
7921 }
7922 PackageSetting dp = mDisabledSysPackages.get(name);
7923 // always make sure the system package code and resource paths dont change
7924 if(dp == null) {
7925 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7926 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7927 }
7928 mDisabledSysPackages.put(name, p);
7929 }
7930 return removePackageLP(name);
7931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007933 PackageSetting enableSystemPackageLP(String name) {
7934 PackageSetting p = mDisabledSysPackages.get(name);
7935 if(p == null) {
7936 Log.w(TAG, "Package:"+name+" is not disabled");
7937 return null;
7938 }
7939 // Reset flag in ApplicationInfo object
7940 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7941 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7942 }
Kenny Root806cc132010-09-12 08:34:19 -07007943 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
7944 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007945 mDisabledSysPackages.remove(name);
7946 return ret;
7947 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007948
Kenny Root806cc132010-09-12 08:34:19 -07007949 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
7950 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007951 PackageSetting p = mPackages.get(name);
7952 if (p != null) {
7953 if (p.userId == uid) {
7954 return p;
7955 }
7956 reportSettingsProblem(Log.ERROR,
7957 "Adding duplicate package, keeping first: " + name);
7958 return null;
7959 }
Kenny Root806cc132010-09-12 08:34:19 -07007960 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
7961 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007962 p.userId = uid;
7963 if (addUserIdLP(uid, p, name)) {
7964 mPackages.put(name, p);
7965 return p;
7966 }
7967 return null;
7968 }
7969
7970 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7971 SharedUserSetting s = mSharedUsers.get(name);
7972 if (s != null) {
7973 if (s.userId == uid) {
7974 return s;
7975 }
7976 reportSettingsProblem(Log.ERROR,
7977 "Adding duplicate shared user, keeping first: " + name);
7978 return null;
7979 }
7980 s = new SharedUserSetting(name, pkgFlags);
7981 s.userId = uid;
7982 if (addUserIdLP(uid, s, name)) {
7983 mSharedUsers.put(name, s);
7984 return s;
7985 }
7986 return null;
7987 }
7988
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007989 // Transfer ownership of permissions from one package to another.
7990 private void transferPermissions(String origPkg, String newPkg) {
7991 // Transfer ownership of permissions to the new package.
7992 for (int i=0; i<2; i++) {
7993 HashMap<String, BasePermission> permissions =
7994 i == 0 ? mPermissionTrees : mPermissions;
7995 for (BasePermission bp : permissions.values()) {
7996 if (origPkg.equals(bp.sourcePackage)) {
7997 if (DEBUG_UPGRADE) Log.v(TAG,
7998 "Moving permission " + bp.name
7999 + " from pkg " + bp.sourcePackage
8000 + " to " + newPkg);
8001 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008002 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008003 bp.perm = null;
8004 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008005 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008006 }
8007 bp.uid = 0;
8008 bp.gids = null;
8009 }
8010 }
8011 }
8012 }
8013
8014 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008015 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008016 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 PackageSetting p = mPackages.get(name);
8018 if (p != null) {
8019 if (!p.codePath.equals(codePath)) {
8020 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008021 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008022 // This is an updated system app with versions in both system
8023 // and data partition. Just let the most recent version
8024 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008025 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008026 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008027 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008028 // Just a change in the code path is not an issue, but
8029 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008030 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008031 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008032 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008033 }
8034 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 reportSettingsProblem(Log.WARN,
8036 "Package " + name + " shared user changed from "
8037 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8038 + " to "
8039 + (sharedUser != null ? sharedUser.name : "<nothing>")
8040 + "; replacing with new");
8041 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008042 } else {
8043 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8044 // If what we are scanning is a system package, then
8045 // make it so, regardless of whether it was previously
8046 // installed only in the data partition.
8047 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008049 }
8050 }
8051 if (p == null) {
8052 // Create a new PackageSettings entry. this can end up here because
8053 // of code path mismatch or user id mismatch of an updated system partition
8054 if (!create) {
8055 return null;
8056 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008057 if (origPackage != null) {
8058 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008059 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8060 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008061 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8062 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008063 // Note that we will retain the new package's signature so
8064 // that we can keep its data.
8065 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008066 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008067 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008068 p.sharedUser = origPackage.sharedUser;
8069 p.userId = origPackage.userId;
8070 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008071 mRenamedPackages.put(name, origPackage.name);
8072 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008073 // Update new package state.
8074 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008075 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008076 p = new PackageSetting(name, realName, codePath, resourcePath,
8077 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008078 p.setTimeStamp(codePath.lastModified());
8079 p.sharedUser = sharedUser;
8080 if (sharedUser != null) {
8081 p.userId = sharedUser.userId;
8082 } else if (MULTIPLE_APPLICATION_UIDS) {
8083 // Clone the setting here for disabled system packages
8084 PackageSetting dis = mDisabledSysPackages.get(name);
8085 if (dis != null) {
8086 // For disabled packages a new setting is created
8087 // from the existing user id. This still has to be
8088 // added to list of user id's
8089 // Copy signatures from previous setting
8090 if (dis.signatures.mSignatures != null) {
8091 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8092 }
8093 p.userId = dis.userId;
8094 // Clone permissions
8095 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008096 // Clone component info
8097 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8098 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8099 // Add new setting to list of user ids
8100 addUserIdLP(p.userId, p, name);
8101 } else {
8102 // Assign new user id
8103 p.userId = newUserIdLP(p);
8104 }
8105 } else {
8106 p.userId = FIRST_APPLICATION_UID;
8107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 }
8109 if (p.userId < 0) {
8110 reportSettingsProblem(Log.WARN,
8111 "Package " + name + " could not be assigned a valid uid");
8112 return null;
8113 }
8114 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008115 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008116 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008117 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008118 }
8119 }
8120 return p;
8121 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008122
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008123 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008124 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008125 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008126 final String codePath = pkg.applicationInfo.sourceDir;
8127 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008128 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008129 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008130 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008131 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008132 p.codePath = new File(codePath);
8133 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008134 }
8135 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008136 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008137 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008138 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008139 p.resourcePath = new File(resourcePath);
8140 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008141 }
Kenny Root85387d72010-08-26 10:13:11 -07008142 // Update the native library path if needed
8143 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8144 if (nativeLibraryPath != null
8145 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8146 p.nativeLibraryPathString = nativeLibraryPath;
8147 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008148 // Update version code if needed
8149 if (pkg.mVersionCode != p.versionCode) {
8150 p.versionCode = pkg.mVersionCode;
8151 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008152 // Update signatures if needed.
8153 if (p.signatures.mSignatures == null) {
8154 p.signatures.assignSignatures(pkg.mSignatures);
8155 }
8156 // If this app defines a shared user id initialize
8157 // the shared user signatures as well.
8158 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8159 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8160 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008161 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8162 }
8163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008164 // Utility method that adds a PackageSetting to mPackages and
8165 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008166 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008167 SharedUserSetting sharedUser) {
8168 mPackages.put(name, p);
8169 if (sharedUser != null) {
8170 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8171 reportSettingsProblem(Log.ERROR,
8172 "Package " + p.name + " was user "
8173 + p.sharedUser + " but is now " + sharedUser
8174 + "; I am not changing its files so it will probably fail!");
8175 p.sharedUser.packages.remove(p);
8176 } else if (p.userId != sharedUser.userId) {
8177 reportSettingsProblem(Log.ERROR,
8178 "Package " + p.name + " was user id " + p.userId
8179 + " but is now user " + sharedUser
8180 + " with id " + sharedUser.userId
8181 + "; I am not changing its files so it will probably fail!");
8182 }
8183
8184 sharedUser.packages.add(p);
8185 p.sharedUser = sharedUser;
8186 p.userId = sharedUser.userId;
8187 }
8188 }
8189
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008190 /*
8191 * Update the shared user setting when a package using
8192 * specifying the shared user id is removed. The gids
8193 * associated with each permission of the deleted package
8194 * are removed from the shared user's gid list only if its
8195 * not in use by other permissions of packages in the
8196 * shared user setting.
8197 */
8198 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008199 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008200 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008201 return;
8202 }
8203 // No sharedUserId
8204 if (deletedPs.sharedUser == null) {
8205 return;
8206 }
8207 SharedUserSetting sus = deletedPs.sharedUser;
8208 // Update permissions
8209 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8210 boolean used = false;
8211 if (!sus.grantedPermissions.contains (eachPerm)) {
8212 continue;
8213 }
8214 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008215 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008216 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008217 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008218 used = true;
8219 break;
8220 }
8221 }
8222 if (!used) {
8223 // can safely delete this permission from list
8224 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 }
8226 }
8227 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008228 int newGids[] = globalGids;
8229 for (String eachPerm : sus.grantedPermissions) {
8230 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008231 if (bp != null) {
8232 newGids = appendInts(newGids, bp.gids);
8233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008234 }
8235 sus.gids = newGids;
8236 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008238 private int removePackageLP(String name) {
8239 PackageSetting p = mPackages.get(name);
8240 if (p != null) {
8241 mPackages.remove(name);
8242 if (p.sharedUser != null) {
8243 p.sharedUser.packages.remove(p);
8244 if (p.sharedUser.packages.size() == 0) {
8245 mSharedUsers.remove(p.sharedUser.name);
8246 removeUserIdLP(p.sharedUser.userId);
8247 return p.sharedUser.userId;
8248 }
8249 } else {
8250 removeUserIdLP(p.userId);
8251 return p.userId;
8252 }
8253 }
8254 return -1;
8255 }
8256
8257 private boolean addUserIdLP(int uid, Object obj, Object name) {
8258 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8259 return false;
8260 }
8261
8262 if (uid >= FIRST_APPLICATION_UID) {
8263 int N = mUserIds.size();
8264 final int index = uid - FIRST_APPLICATION_UID;
8265 while (index >= N) {
8266 mUserIds.add(null);
8267 N++;
8268 }
8269 if (mUserIds.get(index) != null) {
8270 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008271 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008272 + " name=" + name);
8273 return false;
8274 }
8275 mUserIds.set(index, obj);
8276 } else {
8277 if (mOtherUserIds.get(uid) != null) {
8278 reportSettingsProblem(Log.ERROR,
8279 "Adding duplicate shared id: " + uid
8280 + " name=" + name);
8281 return false;
8282 }
8283 mOtherUserIds.put(uid, obj);
8284 }
8285 return true;
8286 }
8287
8288 public Object getUserIdLP(int uid) {
8289 if (uid >= FIRST_APPLICATION_UID) {
8290 int N = mUserIds.size();
8291 final int index = uid - FIRST_APPLICATION_UID;
8292 return index < N ? mUserIds.get(index) : null;
8293 } else {
8294 return mOtherUserIds.get(uid);
8295 }
8296 }
8297
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008298 private Set<String> findPackagesWithFlag(int flag) {
8299 Set<String> ret = new HashSet<String>();
8300 for (PackageSetting ps : mPackages.values()) {
8301 // Has to match atleast all the flag bits set on flag
8302 if ((ps.pkgFlags & flag) == flag) {
8303 ret.add(ps.name);
8304 }
8305 }
8306 return ret;
8307 }
8308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008309 private void removeUserIdLP(int uid) {
8310 if (uid >= FIRST_APPLICATION_UID) {
8311 int N = mUserIds.size();
8312 final int index = uid - FIRST_APPLICATION_UID;
8313 if (index < N) mUserIds.set(index, null);
8314 } else {
8315 mOtherUserIds.remove(uid);
8316 }
8317 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008319 void writeLP() {
8320 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8321
8322 // Keep the old settings around until we know the new ones have
8323 // been successfully written.
8324 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008325 // Presence of backup settings file indicates that we failed
8326 // to persist settings earlier. So preserve the older
8327 // backup for future reference since the current settings
8328 // might have been corrupted.
8329 if (!mBackupSettingsFilename.exists()) {
8330 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008331 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008332 return;
8333 }
8334 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008335 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008336 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338 }
8339
8340 mPastSignatures.clear();
8341
8342 try {
8343 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8344
8345 //XmlSerializer serializer = XmlUtils.serializerInstance();
8346 XmlSerializer serializer = new FastXmlSerializer();
8347 serializer.setOutput(str, "utf-8");
8348 serializer.startDocument(null, true);
8349 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8350
8351 serializer.startTag(null, "packages");
8352
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008353 serializer.startTag(null, "last-platform-version");
8354 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8355 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8356 serializer.endTag(null, "last-platform-version");
8357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008358 serializer.startTag(null, "permission-trees");
8359 for (BasePermission bp : mPermissionTrees.values()) {
8360 writePermission(serializer, bp);
8361 }
8362 serializer.endTag(null, "permission-trees");
8363
8364 serializer.startTag(null, "permissions");
8365 for (BasePermission bp : mPermissions.values()) {
8366 writePermission(serializer, bp);
8367 }
8368 serializer.endTag(null, "permissions");
8369
8370 for (PackageSetting pkg : mPackages.values()) {
8371 writePackage(serializer, pkg);
8372 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008374 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8375 writeDisabledSysPackage(serializer, pkg);
8376 }
8377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008378 serializer.startTag(null, "preferred-activities");
8379 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8380 serializer.startTag(null, "item");
8381 pa.writeToXml(serializer);
8382 serializer.endTag(null, "item");
8383 }
8384 serializer.endTag(null, "preferred-activities");
8385
8386 for (SharedUserSetting usr : mSharedUsers.values()) {
8387 serializer.startTag(null, "shared-user");
8388 serializer.attribute(null, "name", usr.name);
8389 serializer.attribute(null, "userId",
8390 Integer.toString(usr.userId));
8391 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8392 serializer.startTag(null, "perms");
8393 for (String name : usr.grantedPermissions) {
8394 serializer.startTag(null, "item");
8395 serializer.attribute(null, "name", name);
8396 serializer.endTag(null, "item");
8397 }
8398 serializer.endTag(null, "perms");
8399 serializer.endTag(null, "shared-user");
8400 }
8401
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008402 if (mPackagesToBeCleaned.size() > 0) {
8403 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8404 serializer.startTag(null, "cleaning-package");
8405 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8406 serializer.endTag(null, "cleaning-package");
8407 }
8408 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008409
8410 if (mRenamedPackages.size() > 0) {
8411 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8412 serializer.startTag(null, "renamed-package");
8413 serializer.attribute(null, "new", e.getKey());
8414 serializer.attribute(null, "old", e.getValue());
8415 serializer.endTag(null, "renamed-package");
8416 }
8417 }
8418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008419 serializer.endTag(null, "packages");
8420
8421 serializer.endDocument();
8422
8423 str.flush();
8424 str.close();
8425
8426 // New settings successfully written, old ones are no longer
8427 // needed.
8428 mBackupSettingsFilename.delete();
8429 FileUtils.setPermissions(mSettingsFilename.toString(),
8430 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8431 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8432 |FileUtils.S_IROTH,
8433 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008434
8435 // Write package list file now, use a JournaledFile.
8436 //
8437 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8438 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8439
8440 str = new FileOutputStream(journal.chooseForWrite());
8441 try {
8442 StringBuilder sb = new StringBuilder();
8443 for (PackageSetting pkg : mPackages.values()) {
8444 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008445 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008446 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8447
8448 // Avoid any application that has a space in its path
8449 // or that is handled by the system.
8450 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8451 continue;
8452
8453 // we store on each line the following information for now:
8454 //
8455 // pkgName - package name
8456 // userId - application-specific user id
8457 // debugFlag - 0 or 1 if the package is debuggable.
8458 // dataPath - path to package's data path
8459 //
8460 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8461 //
8462 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8463 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8464 // system/core/run-as/run-as.c
8465 //
8466 sb.setLength(0);
8467 sb.append(ai.packageName);
8468 sb.append(" ");
8469 sb.append((int)ai.uid);
8470 sb.append(isDebug ? " 1 " : " 0 ");
8471 sb.append(dataPath);
8472 sb.append("\n");
8473 str.write(sb.toString().getBytes());
8474 }
8475 str.flush();
8476 str.close();
8477 journal.commit();
8478 }
8479 catch (Exception e) {
8480 journal.rollback();
8481 }
8482
8483 FileUtils.setPermissions(mPackageListFilename.toString(),
8484 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8485 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8486 |FileUtils.S_IROTH,
8487 -1, -1);
8488
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008489 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008490
8491 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008492 Slog.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008493 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008494 Slog.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008495 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008496 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008497 if (mSettingsFilename.exists()) {
8498 if (!mSettingsFilename.delete()) {
8499 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8500 }
8501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502 //Debug.stopMethodTracing();
8503 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008504
8505 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008506 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008507 serializer.startTag(null, "updated-package");
8508 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008509 if (pkg.realName != null) {
8510 serializer.attribute(null, "realName", pkg.realName);
8511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008512 serializer.attribute(null, "codePath", pkg.codePathString);
8513 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008514 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008515 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8516 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8517 }
Kenny Root85387d72010-08-26 10:13:11 -07008518 if (pkg.nativeLibraryPathString != null) {
8519 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008521 if (pkg.sharedUser == null) {
8522 serializer.attribute(null, "userId",
8523 Integer.toString(pkg.userId));
8524 } else {
8525 serializer.attribute(null, "sharedUserId",
8526 Integer.toString(pkg.userId));
8527 }
8528 serializer.startTag(null, "perms");
8529 if (pkg.sharedUser == null) {
8530 // If this is a shared user, the permissions will
8531 // be written there. We still need to write an
8532 // empty permissions list so permissionsFixed will
8533 // be set.
8534 for (final String name : pkg.grantedPermissions) {
8535 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008536 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008537 // We only need to write signature or system permissions but this wont
8538 // match the semantics of grantedPermissions. So write all permissions.
8539 serializer.startTag(null, "item");
8540 serializer.attribute(null, "name", name);
8541 serializer.endTag(null, "item");
8542 }
8543 }
8544 }
8545 serializer.endTag(null, "perms");
8546 serializer.endTag(null, "updated-package");
8547 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008548
8549 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008550 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008551 serializer.startTag(null, "package");
8552 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008553 if (pkg.realName != null) {
8554 serializer.attribute(null, "realName", pkg.realName);
8555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556 serializer.attribute(null, "codePath", pkg.codePathString);
8557 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8558 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8559 }
Kenny Root85387d72010-08-26 10:13:11 -07008560 if (pkg.nativeLibraryPathString != null) {
8561 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8562 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008563 serializer.attribute(null, "flags",
8564 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008565 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008566 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008567 if (pkg.sharedUser == null) {
8568 serializer.attribute(null, "userId",
8569 Integer.toString(pkg.userId));
8570 } else {
8571 serializer.attribute(null, "sharedUserId",
8572 Integer.toString(pkg.userId));
8573 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008574 if (pkg.uidError) {
8575 serializer.attribute(null, "uidError", "true");
8576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8578 serializer.attribute(null, "enabled",
8579 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8580 ? "true" : "false");
8581 }
8582 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8583 serializer.attribute(null, "installStatus", "false");
8584 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008585 if (pkg.installerPackageName != null) {
8586 serializer.attribute(null, "installer", pkg.installerPackageName);
8587 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008588 if (pkg.obbPathString != null) {
8589 serializer.attribute(null, "obbPath", pkg.obbPathString);
8590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8592 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8593 serializer.startTag(null, "perms");
8594 if (pkg.sharedUser == null) {
8595 // If this is a shared user, the permissions will
8596 // be written there. We still need to write an
8597 // empty permissions list so permissionsFixed will
8598 // be set.
8599 for (final String name : pkg.grantedPermissions) {
8600 serializer.startTag(null, "item");
8601 serializer.attribute(null, "name", name);
8602 serializer.endTag(null, "item");
8603 }
8604 }
8605 serializer.endTag(null, "perms");
8606 }
8607 if (pkg.disabledComponents.size() > 0) {
8608 serializer.startTag(null, "disabled-components");
8609 for (final String name : pkg.disabledComponents) {
8610 serializer.startTag(null, "item");
8611 serializer.attribute(null, "name", name);
8612 serializer.endTag(null, "item");
8613 }
8614 serializer.endTag(null, "disabled-components");
8615 }
8616 if (pkg.enabledComponents.size() > 0) {
8617 serializer.startTag(null, "enabled-components");
8618 for (final String name : pkg.enabledComponents) {
8619 serializer.startTag(null, "item");
8620 serializer.attribute(null, "name", name);
8621 serializer.endTag(null, "item");
8622 }
8623 serializer.endTag(null, "enabled-components");
8624 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008626 serializer.endTag(null, "package");
8627 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629 void writePermission(XmlSerializer serializer, BasePermission bp)
8630 throws XmlPullParserException, java.io.IOException {
8631 if (bp.type != BasePermission.TYPE_BUILTIN
8632 && bp.sourcePackage != null) {
8633 serializer.startTag(null, "item");
8634 serializer.attribute(null, "name", bp.name);
8635 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008636 if (bp.protectionLevel !=
8637 PermissionInfo.PROTECTION_NORMAL) {
8638 serializer.attribute(null, "protection",
8639 Integer.toString(bp.protectionLevel));
8640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 if (DEBUG_SETTINGS) Log.v(TAG,
8642 "Writing perm: name=" + bp.name + " type=" + bp.type);
8643 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8644 PermissionInfo pi = bp.perm != null ? bp.perm.info
8645 : bp.pendingInfo;
8646 if (pi != null) {
8647 serializer.attribute(null, "type", "dynamic");
8648 if (pi.icon != 0) {
8649 serializer.attribute(null, "icon",
8650 Integer.toString(pi.icon));
8651 }
8652 if (pi.nonLocalizedLabel != null) {
8653 serializer.attribute(null, "label",
8654 pi.nonLocalizedLabel.toString());
8655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 }
8657 }
8658 serializer.endTag(null, "item");
8659 }
8660 }
8661
8662 String getReadMessagesLP() {
8663 return mReadMessages.toString();
8664 }
8665
Oscar Montemayora8529f62009-11-18 10:14:20 -08008666 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008667 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8668 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008669 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008670 while(its.hasNext()) {
8671 String key = its.next();
8672 PackageSetting ps = mPackages.get(key);
8673 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008674 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008675 }
8676 }
8677 return ret;
8678 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 boolean readLP() {
8681 FileInputStream str = null;
8682 if (mBackupSettingsFilename.exists()) {
8683 try {
8684 str = new FileInputStream(mBackupSettingsFilename);
8685 mReadMessages.append("Reading from backup settings file\n");
8686 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008687 if (mSettingsFilename.exists()) {
8688 // If both the backup and settings file exist, we
8689 // ignore the settings since it might have been
8690 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008691 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008692 mSettingsFilename.delete();
8693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008694 } catch (java.io.IOException e) {
8695 // We'll try for the normal settings file.
8696 }
8697 }
8698
8699 mPastSignatures.clear();
8700
8701 try {
8702 if (str == null) {
8703 if (!mSettingsFilename.exists()) {
8704 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008705 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706 return false;
8707 }
8708 str = new FileInputStream(mSettingsFilename);
8709 }
8710 XmlPullParser parser = Xml.newPullParser();
8711 parser.setInput(str, null);
8712
8713 int type;
8714 while ((type=parser.next()) != XmlPullParser.START_TAG
8715 && type != XmlPullParser.END_DOCUMENT) {
8716 ;
8717 }
8718
8719 if (type != XmlPullParser.START_TAG) {
8720 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008721 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008722 return false;
8723 }
8724
8725 int outerDepth = parser.getDepth();
8726 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8727 && (type != XmlPullParser.END_TAG
8728 || parser.getDepth() > outerDepth)) {
8729 if (type == XmlPullParser.END_TAG
8730 || type == XmlPullParser.TEXT) {
8731 continue;
8732 }
8733
8734 String tagName = parser.getName();
8735 if (tagName.equals("package")) {
8736 readPackageLP(parser);
8737 } else if (tagName.equals("permissions")) {
8738 readPermissionsLP(mPermissions, parser);
8739 } else if (tagName.equals("permission-trees")) {
8740 readPermissionsLP(mPermissionTrees, parser);
8741 } else if (tagName.equals("shared-user")) {
8742 readSharedUserLP(parser);
8743 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008744 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008745 } else if (tagName.equals("preferred-activities")) {
8746 readPreferredActivitiesLP(parser);
8747 } else if(tagName.equals("updated-package")) {
8748 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008749 } else if (tagName.equals("cleaning-package")) {
8750 String name = parser.getAttributeValue(null, "name");
8751 if (name != null) {
8752 mPackagesToBeCleaned.add(name);
8753 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008754 } else if (tagName.equals("renamed-package")) {
8755 String nname = parser.getAttributeValue(null, "new");
8756 String oname = parser.getAttributeValue(null, "old");
8757 if (nname != null && oname != null) {
8758 mRenamedPackages.put(nname, oname);
8759 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008760 } else if (tagName.equals("last-platform-version")) {
8761 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8762 try {
8763 String internal = parser.getAttributeValue(null, "internal");
8764 if (internal != null) {
8765 mInternalSdkPlatform = Integer.parseInt(internal);
8766 }
8767 String external = parser.getAttributeValue(null, "external");
8768 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008769 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008770 }
8771 } catch (NumberFormatException e) {
8772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008773 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008774 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008775 + parser.getName());
8776 XmlUtils.skipCurrentTag(parser);
8777 }
8778 }
8779
8780 str.close();
8781
8782 } catch(XmlPullParserException e) {
8783 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008784 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008785
8786 } catch(java.io.IOException e) {
8787 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008788 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008789
8790 }
8791
8792 int N = mPendingPackages.size();
8793 for (int i=0; i<N; i++) {
8794 final PendingPackage pp = mPendingPackages.get(i);
8795 Object idObj = getUserIdLP(pp.sharedId);
8796 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008797 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008798 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8799 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008800 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008801 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008802 + pp.name);
8803 continue;
8804 }
8805 p.copyFrom(pp);
8806 } else if (idObj != null) {
8807 String msg = "Bad package setting: package " + pp.name
8808 + " has shared uid " + pp.sharedId
8809 + " that is not a shared uid\n";
8810 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008811 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008812 } else {
8813 String msg = "Bad package setting: package " + pp.name
8814 + " has shared uid " + pp.sharedId
8815 + " that is not defined\n";
8816 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008817 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008818 }
8819 }
8820 mPendingPackages.clear();
8821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008822 mReadMessages.append("Read completed successfully: "
8823 + mPackages.size() + " packages, "
8824 + mSharedUsers.size() + " shared uids\n");
8825
8826 return true;
8827 }
8828
8829 private int readInt(XmlPullParser parser, String ns, String name,
8830 int defValue) {
8831 String v = parser.getAttributeValue(ns, name);
8832 try {
8833 if (v == null) {
8834 return defValue;
8835 }
8836 return Integer.parseInt(v);
8837 } catch (NumberFormatException e) {
8838 reportSettingsProblem(Log.WARN,
8839 "Error in package manager settings: attribute " +
8840 name + " has bad integer value " + v + " at "
8841 + parser.getPositionDescription());
8842 }
8843 return defValue;
8844 }
8845
8846 private void readPermissionsLP(HashMap<String, BasePermission> out,
8847 XmlPullParser parser)
8848 throws IOException, XmlPullParserException {
8849 int outerDepth = parser.getDepth();
8850 int type;
8851 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8852 && (type != XmlPullParser.END_TAG
8853 || parser.getDepth() > outerDepth)) {
8854 if (type == XmlPullParser.END_TAG
8855 || type == XmlPullParser.TEXT) {
8856 continue;
8857 }
8858
8859 String tagName = parser.getName();
8860 if (tagName.equals("item")) {
8861 String name = parser.getAttributeValue(null, "name");
8862 String sourcePackage = parser.getAttributeValue(null, "package");
8863 String ptype = parser.getAttributeValue(null, "type");
8864 if (name != null && sourcePackage != null) {
8865 boolean dynamic = "dynamic".equals(ptype);
8866 BasePermission bp = new BasePermission(name, sourcePackage,
8867 dynamic
8868 ? BasePermission.TYPE_DYNAMIC
8869 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008870 bp.protectionLevel = readInt(parser, null, "protection",
8871 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008872 if (dynamic) {
8873 PermissionInfo pi = new PermissionInfo();
8874 pi.packageName = sourcePackage.intern();
8875 pi.name = name.intern();
8876 pi.icon = readInt(parser, null, "icon", 0);
8877 pi.nonLocalizedLabel = parser.getAttributeValue(
8878 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008879 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008880 bp.pendingInfo = pi;
8881 }
8882 out.put(bp.name, bp);
8883 } else {
8884 reportSettingsProblem(Log.WARN,
8885 "Error in package manager settings: permissions has"
8886 + " no name at " + parser.getPositionDescription());
8887 }
8888 } else {
8889 reportSettingsProblem(Log.WARN,
8890 "Unknown element reading permissions: "
8891 + parser.getName() + " at "
8892 + parser.getPositionDescription());
8893 }
8894 XmlUtils.skipCurrentTag(parser);
8895 }
8896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008898 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008899 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008900 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008901 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008902 String codePathStr = parser.getAttributeValue(null, "codePath");
8903 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07008904 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008905 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 resourcePathStr = codePathStr;
8907 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008908 String version = parser.getAttributeValue(null, "version");
8909 int versionCode = 0;
8910 if (version != null) {
8911 try {
8912 versionCode = Integer.parseInt(version);
8913 } catch (NumberFormatException e) {
8914 }
8915 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008917 int pkgFlags = 0;
8918 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07008919 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
8920 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008921 String timeStampStr = parser.getAttributeValue(null, "ts");
8922 if (timeStampStr != null) {
8923 try {
8924 long timeStamp = Long.parseLong(timeStampStr);
8925 ps.setTimeStamp(timeStamp, timeStampStr);
8926 } catch (NumberFormatException e) {
8927 }
8928 }
8929 String idStr = parser.getAttributeValue(null, "userId");
8930 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8931 if(ps.userId <= 0) {
8932 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8933 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8934 }
8935 int outerDepth = parser.getDepth();
8936 int type;
8937 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8938 && (type != XmlPullParser.END_TAG
8939 || parser.getDepth() > outerDepth)) {
8940 if (type == XmlPullParser.END_TAG
8941 || type == XmlPullParser.TEXT) {
8942 continue;
8943 }
8944
8945 String tagName = parser.getName();
8946 if (tagName.equals("perms")) {
8947 readGrantedPermissionsLP(parser,
8948 ps.grantedPermissions);
8949 } else {
8950 reportSettingsProblem(Log.WARN,
8951 "Unknown element under <updated-package>: "
8952 + parser.getName());
8953 XmlUtils.skipCurrentTag(parser);
8954 }
8955 }
8956 mDisabledSysPackages.put(name, ps);
8957 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008959 private void readPackageLP(XmlPullParser parser)
8960 throws XmlPullParserException, IOException {
8961 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008962 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008963 String idStr = null;
8964 String sharedIdStr = null;
8965 String codePathStr = null;
8966 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07008967 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07008968 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008969 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008970 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008971 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008972 int pkgFlags = 0;
8973 String timeStampStr;
8974 long timeStamp = 0;
8975 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008976 String version = null;
8977 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008978 try {
8979 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008980 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008981 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008982 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008983 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8984 codePathStr = parser.getAttributeValue(null, "codePath");
8985 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07008986 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07008987 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008988 version = parser.getAttributeValue(null, "version");
8989 if (version != null) {
8990 try {
8991 versionCode = Integer.parseInt(version);
8992 } catch (NumberFormatException e) {
8993 }
8994 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008995 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008996
8997 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008998 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008999 try {
9000 pkgFlags = Integer.parseInt(systemStr);
9001 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009002 }
9003 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009004 // For backward compatibility
9005 systemStr = parser.getAttributeValue(null, "system");
9006 if (systemStr != null) {
9007 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9008 } else {
9009 // Old settings that don't specify system... just treat
9010 // them as system, good enough.
9011 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009013 }
9014 timeStampStr = parser.getAttributeValue(null, "ts");
9015 if (timeStampStr != null) {
9016 try {
9017 timeStamp = Long.parseLong(timeStampStr);
9018 } catch (NumberFormatException e) {
9019 }
9020 }
9021 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9022 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9023 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9024 if (resourcePathStr == null) {
9025 resourcePathStr = codePathStr;
9026 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009027 if (realName != null) {
9028 realName = realName.intern();
9029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009030 if (name == null) {
9031 reportSettingsProblem(Log.WARN,
9032 "Error in package manager settings: <package> has no name at "
9033 + parser.getPositionDescription());
9034 } else if (codePathStr == null) {
9035 reportSettingsProblem(Log.WARN,
9036 "Error in package manager settings: <package> has no codePath at "
9037 + parser.getPositionDescription());
9038 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009039 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9040 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9041 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009042 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9043 + ": userId=" + userId + " pkg=" + packageSetting);
9044 if (packageSetting == null) {
9045 reportSettingsProblem(Log.ERROR,
9046 "Failure adding uid " + userId
9047 + " while parsing settings at "
9048 + parser.getPositionDescription());
9049 } else {
9050 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9051 }
9052 } else if (sharedIdStr != null) {
9053 userId = sharedIdStr != null
9054 ? Integer.parseInt(sharedIdStr) : 0;
9055 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009056 packageSetting = new PendingPackage(name.intern(), realName,
9057 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009058 nativeLibraryPathStr, userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009059 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9060 mPendingPackages.add((PendingPackage) packageSetting);
9061 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9062 + ": sharedUserId=" + userId + " pkg="
9063 + packageSetting);
9064 } else {
9065 reportSettingsProblem(Log.WARN,
9066 "Error in package manager settings: package "
9067 + name + " has bad sharedId " + sharedIdStr
9068 + " at " + parser.getPositionDescription());
9069 }
9070 } else {
9071 reportSettingsProblem(Log.WARN,
9072 "Error in package manager settings: package "
9073 + name + " has bad userId " + idStr + " at "
9074 + parser.getPositionDescription());
9075 }
9076 } catch (NumberFormatException e) {
9077 reportSettingsProblem(Log.WARN,
9078 "Error in package manager settings: package "
9079 + name + " has bad userId " + idStr + " at "
9080 + parser.getPositionDescription());
9081 }
9082 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009083 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009084 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009085 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009086 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009087 final String enabledStr = parser.getAttributeValue(null, "enabled");
9088 if (enabledStr != null) {
9089 if (enabledStr.equalsIgnoreCase("true")) {
9090 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9091 } else if (enabledStr.equalsIgnoreCase("false")) {
9092 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9093 } else if (enabledStr.equalsIgnoreCase("default")) {
9094 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9095 } else {
9096 reportSettingsProblem(Log.WARN,
9097 "Error in package manager settings: package "
9098 + name + " has bad enabled value: " + idStr
9099 + " at " + parser.getPositionDescription());
9100 }
9101 } else {
9102 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9103 }
9104 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9105 if (installStatusStr != null) {
9106 if (installStatusStr.equalsIgnoreCase("false")) {
9107 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9108 } else {
9109 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9110 }
9111 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009113 int outerDepth = parser.getDepth();
9114 int type;
9115 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9116 && (type != XmlPullParser.END_TAG
9117 || parser.getDepth() > outerDepth)) {
9118 if (type == XmlPullParser.END_TAG
9119 || type == XmlPullParser.TEXT) {
9120 continue;
9121 }
9122
9123 String tagName = parser.getName();
9124 if (tagName.equals("disabled-components")) {
9125 readDisabledComponentsLP(packageSetting, parser);
9126 } else if (tagName.equals("enabled-components")) {
9127 readEnabledComponentsLP(packageSetting, parser);
9128 } else if (tagName.equals("sigs")) {
9129 packageSetting.signatures.readXml(parser, mPastSignatures);
9130 } else if (tagName.equals("perms")) {
9131 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009132 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009133 packageSetting.permissionsFixed = true;
9134 } else {
9135 reportSettingsProblem(Log.WARN,
9136 "Unknown element under <package>: "
9137 + parser.getName());
9138 XmlUtils.skipCurrentTag(parser);
9139 }
9140 }
9141 } else {
9142 XmlUtils.skipCurrentTag(parser);
9143 }
9144 }
9145
9146 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9147 XmlPullParser parser)
9148 throws IOException, XmlPullParserException {
9149 int outerDepth = parser.getDepth();
9150 int type;
9151 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9152 && (type != XmlPullParser.END_TAG
9153 || parser.getDepth() > outerDepth)) {
9154 if (type == XmlPullParser.END_TAG
9155 || type == XmlPullParser.TEXT) {
9156 continue;
9157 }
9158
9159 String tagName = parser.getName();
9160 if (tagName.equals("item")) {
9161 String name = parser.getAttributeValue(null, "name");
9162 if (name != null) {
9163 packageSetting.disabledComponents.add(name.intern());
9164 } else {
9165 reportSettingsProblem(Log.WARN,
9166 "Error in package manager settings: <disabled-components> has"
9167 + " no name at " + parser.getPositionDescription());
9168 }
9169 } else {
9170 reportSettingsProblem(Log.WARN,
9171 "Unknown element under <disabled-components>: "
9172 + parser.getName());
9173 }
9174 XmlUtils.skipCurrentTag(parser);
9175 }
9176 }
9177
9178 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9179 XmlPullParser parser)
9180 throws IOException, XmlPullParserException {
9181 int outerDepth = parser.getDepth();
9182 int type;
9183 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9184 && (type != XmlPullParser.END_TAG
9185 || parser.getDepth() > outerDepth)) {
9186 if (type == XmlPullParser.END_TAG
9187 || type == XmlPullParser.TEXT) {
9188 continue;
9189 }
9190
9191 String tagName = parser.getName();
9192 if (tagName.equals("item")) {
9193 String name = parser.getAttributeValue(null, "name");
9194 if (name != null) {
9195 packageSetting.enabledComponents.add(name.intern());
9196 } else {
9197 reportSettingsProblem(Log.WARN,
9198 "Error in package manager settings: <enabled-components> has"
9199 + " no name at " + parser.getPositionDescription());
9200 }
9201 } else {
9202 reportSettingsProblem(Log.WARN,
9203 "Unknown element under <enabled-components>: "
9204 + parser.getName());
9205 }
9206 XmlUtils.skipCurrentTag(parser);
9207 }
9208 }
9209
9210 private void readSharedUserLP(XmlPullParser parser)
9211 throws XmlPullParserException, IOException {
9212 String name = null;
9213 String idStr = null;
9214 int pkgFlags = 0;
9215 SharedUserSetting su = null;
9216 try {
9217 name = parser.getAttributeValue(null, "name");
9218 idStr = parser.getAttributeValue(null, "userId");
9219 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9220 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9221 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9222 }
9223 if (name == null) {
9224 reportSettingsProblem(Log.WARN,
9225 "Error in package manager settings: <shared-user> has no name at "
9226 + parser.getPositionDescription());
9227 } else if (userId == 0) {
9228 reportSettingsProblem(Log.WARN,
9229 "Error in package manager settings: shared-user "
9230 + name + " has bad userId " + idStr + " at "
9231 + parser.getPositionDescription());
9232 } else {
9233 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9234 reportSettingsProblem(Log.ERROR,
9235 "Occurred while parsing settings at "
9236 + parser.getPositionDescription());
9237 }
9238 }
9239 } catch (NumberFormatException e) {
9240 reportSettingsProblem(Log.WARN,
9241 "Error in package manager settings: package "
9242 + name + " has bad userId " + idStr + " at "
9243 + parser.getPositionDescription());
9244 };
9245
9246 if (su != null) {
9247 int outerDepth = parser.getDepth();
9248 int type;
9249 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9250 && (type != XmlPullParser.END_TAG
9251 || parser.getDepth() > outerDepth)) {
9252 if (type == XmlPullParser.END_TAG
9253 || type == XmlPullParser.TEXT) {
9254 continue;
9255 }
9256
9257 String tagName = parser.getName();
9258 if (tagName.equals("sigs")) {
9259 su.signatures.readXml(parser, mPastSignatures);
9260 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009261 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009262 } else {
9263 reportSettingsProblem(Log.WARN,
9264 "Unknown element under <shared-user>: "
9265 + parser.getName());
9266 XmlUtils.skipCurrentTag(parser);
9267 }
9268 }
9269
9270 } else {
9271 XmlUtils.skipCurrentTag(parser);
9272 }
9273 }
9274
9275 private void readGrantedPermissionsLP(XmlPullParser parser,
9276 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9277 int outerDepth = parser.getDepth();
9278 int type;
9279 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9280 && (type != XmlPullParser.END_TAG
9281 || parser.getDepth() > outerDepth)) {
9282 if (type == XmlPullParser.END_TAG
9283 || type == XmlPullParser.TEXT) {
9284 continue;
9285 }
9286
9287 String tagName = parser.getName();
9288 if (tagName.equals("item")) {
9289 String name = parser.getAttributeValue(null, "name");
9290 if (name != null) {
9291 outPerms.add(name.intern());
9292 } else {
9293 reportSettingsProblem(Log.WARN,
9294 "Error in package manager settings: <perms> has"
9295 + " no name at " + parser.getPositionDescription());
9296 }
9297 } else {
9298 reportSettingsProblem(Log.WARN,
9299 "Unknown element under <perms>: "
9300 + parser.getName());
9301 }
9302 XmlUtils.skipCurrentTag(parser);
9303 }
9304 }
9305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009306 private void readPreferredActivitiesLP(XmlPullParser parser)
9307 throws XmlPullParserException, IOException {
9308 int outerDepth = parser.getDepth();
9309 int type;
9310 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9311 && (type != XmlPullParser.END_TAG
9312 || parser.getDepth() > outerDepth)) {
9313 if (type == XmlPullParser.END_TAG
9314 || type == XmlPullParser.TEXT) {
9315 continue;
9316 }
9317
9318 String tagName = parser.getName();
9319 if (tagName.equals("item")) {
9320 PreferredActivity pa = new PreferredActivity(parser);
9321 if (pa.mParseError == null) {
9322 mPreferredActivities.addFilter(pa);
9323 } else {
9324 reportSettingsProblem(Log.WARN,
9325 "Error in package manager settings: <preferred-activity> "
9326 + pa.mParseError + " at "
9327 + parser.getPositionDescription());
9328 }
9329 } else {
9330 reportSettingsProblem(Log.WARN,
9331 "Unknown element under <preferred-activities>: "
9332 + parser.getName());
9333 XmlUtils.skipCurrentTag(parser);
9334 }
9335 }
9336 }
9337
9338 // Returns -1 if we could not find an available UserId to assign
9339 private int newUserIdLP(Object obj) {
9340 // Let's be stupidly inefficient for now...
9341 final int N = mUserIds.size();
9342 for (int i=0; i<N; i++) {
9343 if (mUserIds.get(i) == null) {
9344 mUserIds.set(i, obj);
9345 return FIRST_APPLICATION_UID + i;
9346 }
9347 }
9348
9349 // None left?
9350 if (N >= MAX_APPLICATION_UIDS) {
9351 return -1;
9352 }
9353
9354 mUserIds.add(obj);
9355 return FIRST_APPLICATION_UID + N;
9356 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009358 public PackageSetting getDisabledSystemPkg(String name) {
9359 synchronized(mPackages) {
9360 PackageSetting ps = mDisabledSysPackages.get(name);
9361 return ps;
9362 }
9363 }
9364
9365 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009366 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9367 return true;
9368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009369 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9370 if (Config.LOGV) {
9371 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9372 + " componentName = " + componentInfo.name);
9373 Log.v(TAG, "enabledComponents: "
9374 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9375 Log.v(TAG, "disabledComponents: "
9376 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9377 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009378 if (packageSettings == null) {
9379 if (false) {
9380 Log.w(TAG, "WAITING FOR DEBUGGER");
9381 Debug.waitForDebugger();
9382 Log.i(TAG, "We will crash!");
9383 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009384 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009385 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009386 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9387 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9388 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9389 return false;
9390 }
9391 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9392 return true;
9393 }
9394 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9395 return false;
9396 }
9397 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009398 }
9399 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009400
9401 // ------- apps on sdcard specific code -------
9402 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009403 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9404 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9405 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009406 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009407
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009408 private String getEncryptKey() {
9409 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009410 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9411 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009412 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009413 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9414 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009415 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009416 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009417 return null;
9418 }
9419 }
9420 return sdEncKey;
9421 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009422 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009423 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009424 } catch (IOException ioe) {
9425 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9426 + ioe);
9427 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009428 }
Rich Cannings8d578832010-09-09 15:12:40 -07009429
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009430 }
9431
Kenny Rootc78a8072010-07-27 15:18:38 -07009432 /* package */ static String getTempContainerId() {
9433 int tmpIdx = 1;
9434 String list[] = PackageHelper.getSecureContainerList();
9435 if (list != null) {
9436 for (final String name : list) {
9437 // Ignore null and non-temporary container entries
9438 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9439 continue;
9440 }
9441
9442 String subStr = name.substring(mTempContainerPrefix.length());
9443 try {
9444 int cid = Integer.parseInt(subStr);
9445 if (cid >= tmpIdx) {
9446 tmpIdx = cid + 1;
9447 }
9448 } catch (NumberFormatException e) {
9449 }
9450 }
9451 }
9452 return mTempContainerPrefix + tmpIdx;
9453 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009454
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009455 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009456 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009457 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009458 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9459 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9460 throw new SecurityException("Media status can only be updated by the system");
9461 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009462 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009463 Log.i(TAG, "Updating external media status from " +
9464 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9465 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009466 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9467 mediaStatus+", mMediaMounted=" + mMediaMounted);
9468 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009469 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9470 reportStatus ? 1 : 0, -1);
9471 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009472 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009473 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009474 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009475 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009476 // Queue up an async operation since the package installation may take a little while.
9477 mHandler.post(new Runnable() {
9478 public void run() {
9479 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009480 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009481 }
9482 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009483 }
9484
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009485 /*
9486 * Collect information of applications on external media, map them
9487 * against existing containers and update information based on current
9488 * mount status. Please note that we always have to report status
9489 * if reportStatus has been set to true especially when unloading packages.
9490 */
9491 private void updateExternalMediaStatusInner(boolean mediaStatus,
9492 boolean reportStatus) {
9493 // Collection of uids
9494 int uidArr[] = null;
9495 // Collection of stale containers
9496 HashSet<String> removeCids = new HashSet<String>();
9497 // Collection of packages on external media with valid containers.
9498 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9499 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009500 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009501 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009502 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009503 } else {
9504 // Process list of secure containers and categorize them
9505 // as active or stale based on their package internal state.
9506 int uidList[] = new int[list.length];
9507 int num = 0;
9508 synchronized (mPackages) {
9509 for (String cid : list) {
9510 SdInstallArgs args = new SdInstallArgs(cid);
9511 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009512 String pkgName = args.getPackageName();
9513 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009514 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9515 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009516 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009517 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009518 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9519 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009520 // The package status is changed only if the code path
9521 // matches between settings and the container id.
9522 if (ps != null && ps.codePathString != null &&
9523 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009524 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9525 " corresponds to pkg : " + pkgName +
9526 " at code path: " + ps.codePathString);
9527 // We do have a valid package installed on sdcard
9528 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009529 int uid = ps.userId;
9530 if (uid != -1) {
9531 uidList[num++] = uid;
9532 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009533 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009534 // Stale container on sdcard. Just delete
9535 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9536 removeCids.add(cid);
9537 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009538 }
9539 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009540
9541 if (num > 0) {
9542 // Sort uid list
9543 Arrays.sort(uidList, 0, num);
9544 // Throw away duplicates
9545 uidArr = new int[num];
9546 uidArr[0] = uidList[0];
9547 int di = 0;
9548 for (int i = 1; i < num; i++) {
9549 if (uidList[i-1] != uidList[i]) {
9550 uidArr[di++] = uidList[i];
9551 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009552 }
9553 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009554 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009555 // Process packages with valid entries.
9556 if (mediaStatus) {
9557 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009558 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009559 startCleaningPackages();
9560 } else {
9561 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009562 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009563 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009564 }
9565
9566 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009567 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009568 int size = pkgList.size();
9569 if (size > 0) {
9570 // Send broadcasts here
9571 Bundle extras = new Bundle();
9572 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9573 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009574 if (uidArr != null) {
9575 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9576 }
9577 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9578 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009579 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009580 }
9581 }
9582
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009583 /*
9584 * Look at potentially valid container ids from processCids
9585 * If package information doesn't match the one on record
9586 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009587 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009588 */
9589 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009590 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009591 ArrayList<String> pkgList = new ArrayList<String>();
9592 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009593 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009594 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009595 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009596 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9597 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009598 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009599 try {
9600 // Make sure there are no container errors first.
9601 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9602 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009603 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009604 " when installing from sdcard");
9605 continue;
9606 }
9607 // Check code path here.
9608 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009609 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009610 " does not match one in settings " + codePath);
9611 continue;
9612 }
9613 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009614 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009615 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009616 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009617 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9618 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009619 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009620 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009621 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009622 retCode = PackageManager.INSTALL_SUCCEEDED;
9623 pkgList.add(pkg.packageName);
9624 // Post process args
9625 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9626 }
9627 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009628 Slog.i(TAG, "Failed to install pkg from " +
9629 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009630 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009631 }
9632
9633 } finally {
9634 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9635 // Don't destroy container here. Wait till gc clears things up.
9636 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009637 }
9638 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009639 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009640 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009641 // If the platform SDK has changed since the last time we booted,
9642 // we need to re-grant app permission to catch any new ones that
9643 // appear. This is really a hack, and means that apps can in some
9644 // cases get permissions that the user didn't initially explicitly
9645 // allow... it would be nice to have some better way to handle
9646 // this situation.
9647 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9648 != mSdkVersion;
9649 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9650 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9651 + "; regranting permissions for external storage");
9652 mSettings.mExternalSdkPlatform = mSdkVersion;
9653
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009654 // Make sure group IDs have been assigned, and any permission
9655 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009656 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009657 // Persist settings
9658 mSettings.writeLP();
9659 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009660 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009661 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009662 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009663 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009664 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009665 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009666 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009667 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009668 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009669 if (removeCids != null) {
9670 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009671 if (cid.startsWith(mTempContainerPrefix)) {
9672 Log.i(TAG, "Destroying stale temporary container " + cid);
9673 PackageHelper.destroySdDir(cid);
9674 } else {
9675 Log.w(TAG, "Container " + cid + " is stale");
9676 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009677 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009678 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009679 }
9680
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009681 /*
9682 * Utility method to unload a list of specified containers
9683 */
9684 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9685 // Just unmount all valid containers.
9686 for (SdInstallArgs arg : cidArgs) {
9687 synchronized (mInstallLock) {
9688 arg.doPostDeleteLI(false);
9689 }
9690 }
9691 }
9692
9693 /*
9694 * Unload packages mounted on external media. This involves deleting
9695 * package data from internal structures, sending broadcasts about
9696 * diabled packages, gc'ing to free up references, unmounting all
9697 * secure containers corresponding to packages on external media, and
9698 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9699 * Please note that we always have to post this message if status has
9700 * been requested no matter what.
9701 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009702 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009703 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009704 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009705 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009706 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009707 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009708 for (SdInstallArgs args : keys) {
9709 String cid = args.cid;
9710 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009711 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009712 // Delete package internally
9713 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9714 synchronized (mInstallLock) {
9715 boolean res = deletePackageLI(pkgName, false,
9716 PackageManager.DONT_DELETE_DATA, outInfo);
9717 if (res) {
9718 pkgList.add(pkgName);
9719 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009720 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009721 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009722 }
9723 }
9724 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009725 // We have to absolutely send UPDATED_MEDIA_STATUS only
9726 // after confirming that all the receivers processed the ordered
9727 // broadcast when packages get disabled, force a gc to clean things up.
9728 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009729 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009730 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9731 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9732 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009733 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9734 reportStatus ? 1 : 0, 1, keys);
9735 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009736 }
9737 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009738 } else {
9739 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9740 reportStatus ? 1 : 0, -1, keys);
9741 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009742 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009743 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009744
9745 public void movePackage(final String packageName,
9746 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009747 mContext.enforceCallingOrSelfPermission(
9748 android.Manifest.permission.MOVE_PACKAGE, null);
9749 int returnCode = PackageManager.MOVE_SUCCEEDED;
9750 int currFlags = 0;
9751 int newFlags = 0;
9752 synchronized (mPackages) {
9753 PackageParser.Package pkg = mPackages.get(packageName);
9754 if (pkg == null) {
9755 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009756 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009757 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009758 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009759 Slog.w(TAG, "Cannot move system application");
9760 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009761 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009762 Slog.w(TAG, "Cannot move forward locked app.");
9763 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009764 } else if (pkg.mOperationPending) {
9765 Slog.w(TAG, "Attempt to move package which has pending operations");
9766 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009767 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009768 // Find install location first
9769 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9770 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9771 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009772 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009773 } else {
9774 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9775 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009776 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9777 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009778 if (newFlags == currFlags) {
9779 Slog.w(TAG, "No move required. Trying to move to same location");
9780 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9781 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009782 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009783 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9784 pkg.mOperationPending = true;
9785 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009786 }
9787 }
9788 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009789 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009790 } else {
9791 Message msg = mHandler.obtainMessage(INIT_COPY);
9792 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009793 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9794 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9795 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009796 msg.obj = mp;
9797 mHandler.sendMessage(msg);
9798 }
9799 }
9800 }
9801
9802 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9803 // Queue up an async operation since the package deletion may take a little while.
9804 mHandler.post(new Runnable() {
9805 public void run() {
9806 mHandler.removeCallbacks(this);
9807 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009808 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9809 int uidArr[] = null;
9810 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009811 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009812 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009813 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009814 Slog.w(TAG, " Package " + mp.packageName +
9815 " doesn't exist. Aborting move");
9816 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9817 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9818 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9819 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9820 " Aborting move and returning error");
9821 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9822 } else {
9823 uidArr = new int[] { pkg.applicationInfo.uid };
9824 pkgList = new ArrayList<String>();
9825 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009826 }
9827 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009828 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9829 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009830 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009831 // Update package code and resource paths
9832 synchronized (mInstallLock) {
9833 synchronized (mPackages) {
9834 PackageParser.Package pkg = mPackages.get(mp.packageName);
9835 // Recheck for package again.
9836 if (pkg == null ) {
9837 Slog.w(TAG, " Package " + mp.packageName +
9838 " doesn't exist. Aborting move");
9839 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9840 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9841 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9842 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9843 " Aborting move and returning error");
9844 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9845 } else {
Kenny Root85387d72010-08-26 10:13:11 -07009846 final String oldCodePath = pkg.mPath;
9847 final String newCodePath = mp.targetArgs.getCodePath();
9848 final String newResPath = mp.targetArgs.getResourcePath();
9849 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009850 pkg.mPath = newCodePath;
9851 // Move dex files around
9852 if (moveDexFilesLI(pkg)
9853 != PackageManager.INSTALL_SUCCEEDED) {
9854 // Moving of dex files failed. Set
9855 // error code and abort move.
9856 pkg.mPath = pkg.mScanPath;
9857 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9858 } else {
9859 pkg.mScanPath = newCodePath;
9860 pkg.applicationInfo.sourceDir = newCodePath;
9861 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -07009862 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009863 PackageSetting ps = (PackageSetting) pkg.mExtras;
9864 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9865 ps.codePathString = ps.codePath.getPath();
9866 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9867 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -07009868 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009869 // Set the application info flag correctly.
9870 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9871 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9872 } else {
9873 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9874 }
9875 ps.setFlags(pkg.applicationInfo.flags);
9876 mAppDirs.remove(oldCodePath);
9877 mAppDirs.put(newCodePath, pkg);
9878 // Persist settings
9879 mSettings.writeLP();
9880 }
9881 }
9882 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009883 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009884 // Send resources available broadcast
9885 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009886 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009887 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009888 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009889 // Clean up failed installation
9890 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009891 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009892 }
9893 } else {
9894 // Force a gc to clear things up.
9895 Runtime.getRuntime().gc();
9896 // Delete older code
9897 synchronized (mInstallLock) {
9898 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009899 }
9900 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009901
9902 // Allow more operations on this file if we didn't fail because
9903 // an operation was already pending for this package.
9904 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9905 synchronized (mPackages) {
9906 PackageParser.Package pkg = mPackages.get(mp.packageName);
9907 if (pkg != null) {
9908 pkg.mOperationPending = false;
9909 }
9910 }
9911 }
9912
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009913 IPackageMoveObserver observer = mp.observer;
9914 if (observer != null) {
9915 try {
9916 observer.packageMoved(mp.packageName, returnCode);
9917 } catch (RemoteException e) {
9918 Log.i(TAG, "Observer no longer exists.");
9919 }
9920 }
9921 }
9922 });
9923 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009924
9925 public boolean setInstallLocation(int loc) {
9926 mContext.enforceCallingOrSelfPermission(
9927 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9928 if (getInstallLocation() == loc) {
9929 return true;
9930 }
9931 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9932 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9933 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9934 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9935 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9936 return true;
9937 }
9938 return false;
9939 }
9940
9941 public int getInstallLocation() {
9942 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9943 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009945}