blob: 050e0c81ccc9feec1215d82b7025ecec526efc35 [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
Kenny Root9f306d72010-09-26 11:19:47 -070094import java.io.BufferedOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.io.File;
96import java.io.FileDescriptor;
97import java.io.FileInputStream;
98import java.io.FileNotFoundException;
99import java.io.FileOutputStream;
100import java.io.FileReader;
101import java.io.FilenameFilter;
102import java.io.IOException;
103import java.io.InputStream;
104import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800105import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800106import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
108import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700109import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Collections;
111import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800112import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.Enumeration;
114import java.util.HashMap;
115import java.util.HashSet;
116import java.util.Iterator;
Kenny Root85387d72010-08-26 10:13:11 -0700117import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.List;
119import java.util.Map;
120import java.util.Set;
121import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800122import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import java.util.zip.ZipFile;
124import java.util.zip.ZipOutputStream;
125
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700126/**
127 * Keep track of all those .apks everywhere.
128 *
129 * This is very central to the platform's security; please run the unit
130 * tests whenever making modifications here:
131 *
132mmm frameworks/base/tests/AndroidTests
133adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
134adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
135 *
136 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137class PackageManagerService extends IPackageManager.Stub {
138 private static final String TAG = "PackageManager";
139 private static final boolean DEBUG_SETTINGS = false;
140 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800141 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800142 private static final boolean DEBUG_INSTALL = 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
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700225 // This is the object monitoring the system app dir.
226 final FileObserver mVendorInstallObserver;
227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 // This is the object monitoring mAppInstallDir.
229 final FileObserver mAppInstallObserver;
230
231 // This is the object monitoring mDrmAppPrivateInstallDir.
232 final FileObserver mDrmAppInstallObserver;
233
234 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
235 // LOCK HELD. Can be called with mInstallLock held.
236 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 final File mFrameworkDir;
239 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700240 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700242 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
244 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
245 // apps.
246 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 // Lock for state used when installing and doing other long running
251 // operations. Methods that must be called with this lock held have
252 // the prefix "LI".
253 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 // These are the directories in the 3rd party applications installed dir
256 // that we have currently loaded packages from. Keys are the application's
257 // installed zip file (absolute codePath), and values are Package.
258 final HashMap<String, PackageParser.Package> mAppDirs =
259 new HashMap<String, PackageParser.Package>();
260
261 // Information for the parser to write more useful error messages.
262 File mScanningPath;
263 int mLastScanError;
264
265 final int[] mOutPermissions = new int[3];
266
267 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 // Keys are String (package name), values are Package. This also serves
270 // as the lock for the global state. Methods that must be called with
271 // this lock held have the prefix "LP".
272 final HashMap<String, PackageParser.Package> mPackages =
273 new HashMap<String, PackageParser.Package>();
274
275 final Settings mSettings;
276 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277
278 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
279 int[] mGlobalGids;
280
281 // These are the built-in uid -> permission mappings that were read from the
282 // etc/permissions.xml file.
283 final SparseArray<HashSet<String>> mSystemPermissions =
284 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 // These are the built-in shared libraries that were read from the
287 // etc/permissions.xml file.
288 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800289
Dianne Hackborn49237342009-08-27 20:08:01 -0700290 // Temporary for building the final shared libraries for an .apk.
291 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800292
Dianne Hackborn49237342009-08-27 20:08:01 -0700293 // These are the features this devices supports that were read from the
294 // etc/permissions.xml file.
295 final HashMap<String, FeatureInfo> mAvailableFeatures =
296 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 // All available activities, for your resolving pleasure.
299 final ActivityIntentResolver mActivities =
300 new ActivityIntentResolver();
301
302 // All available receivers, for your resolving pleasure.
303 final ActivityIntentResolver mReceivers =
304 new ActivityIntentResolver();
305
306 // All available services, for your resolving pleasure.
307 final ServiceIntentResolver mServices = new ServiceIntentResolver();
308
309 // Keys are String (provider class name), values are Provider.
310 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
311 new HashMap<ComponentName, PackageParser.Provider>();
312
313 // Mapping from provider base names (first directory in content URI codePath)
314 // to the provider information.
315 final HashMap<String, PackageParser.Provider> mProviders =
316 new HashMap<String, PackageParser.Provider>();
317
318 // Mapping from instrumentation class names to info about them.
319 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
320 new HashMap<ComponentName, PackageParser.Instrumentation>();
321
322 // Mapping from permission names to info about them.
323 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
324 new HashMap<String, PackageParser.PermissionGroup>();
325
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800326 // Packages whose data we have transfered into another package, thus
327 // should no longer exist.
328 final HashSet<String> mTransferedPackages = new HashSet<String>();
329
Dianne Hackborn854060af2009-07-09 18:14:31 -0700330 // Broadcast actions that are only available to the system.
331 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 boolean mSystemReady;
334 boolean mSafeMode;
335 boolean mHasSystemUidErrors;
336
337 ApplicationInfo mAndroidApplication;
338 final ActivityInfo mResolveActivity = new ActivityInfo();
339 final ResolveInfo mResolveInfo = new ResolveInfo();
340 ComponentName mResolveComponentName;
341 PackageParser.Package mPlatformPackage;
342
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700343 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800344 final HashMap<String, ArrayList<String>> mPendingBroadcasts
345 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800346 // Service Connection to remote media container service to copy
347 // package uri's from external media onto secure containers
348 // or internal storage.
349 private IMediaContainerService mContainerService = null;
350
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700351 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800352 static final int MCS_BOUND = 3;
353 static final int END_COPY = 4;
354 static final int INIT_COPY = 5;
355 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800356 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800357 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800358 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800359 static final int MCS_RECONNECT = 10;
360 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700361 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700362 static final int WRITE_SETTINGS = 13;
363
364 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800365
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700366 // Delay time in millisecs
367 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800368 final private DefaultContainerConnection mDefContainerConn =
369 new DefaultContainerConnection();
370 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800371 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800372 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800373 IMediaContainerService imcs =
374 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800375 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800376 }
377
378 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800379 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800380 }
381 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700382
Christopher Tate1bb69062010-02-19 17:02:12 -0800383 // Recordkeeping of restore-after-install operations that are currently in flight
384 // between the Package Manager and the Backup Manager
385 class PostInstallData {
386 public InstallArgs args;
387 public PackageInstalledInfo res;
388
389 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
390 args = _a;
391 res = _r;
392 }
393 };
394 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
395 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
396
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700397 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800398 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800399 final ArrayList<HandlerParams> mPendingInstalls =
400 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800401
402 private boolean connectToService() {
403 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
404 " DefaultContainerService");
405 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700406 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800407 if (mContext.bindService(service, mDefContainerConn,
408 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800410 mBound = true;
411 return true;
412 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800414 return false;
415 }
416
417 private void disconnectService() {
418 mContainerService = null;
419 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700420 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800421 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700422 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800423 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800424
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700425 PackageHandler(Looper looper) {
426 super(looper);
427 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700428
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700429 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700430 try {
431 doHandleMessage(msg);
432 } finally {
433 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
434 }
435 }
436
437 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700438 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800439 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800440 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800441 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800442 int idx = mPendingInstalls.size();
443 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
444 // If a bind was already initiated we dont really
445 // need to do anything. The pending install
446 // will be processed later on.
447 if (!mBound) {
448 // If this is the only one pending we might
449 // have to bind to the service again.
450 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800451 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800452 params.serviceError();
453 return;
454 } else {
455 // Once we bind to the service, the first
456 // pending request will be processed.
457 mPendingInstalls.add(idx, params);
458 }
459 } else {
460 mPendingInstalls.add(idx, params);
461 // Already bound to the service. Just make
462 // sure we trigger off processing the first request.
463 if (idx == 0) {
464 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800465 }
466 }
467 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800468 }
469 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800471 if (msg.obj != null) {
472 mContainerService = (IMediaContainerService) msg.obj;
473 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800474 if (mContainerService == null) {
475 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800476 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800477 for (HandlerParams params : mPendingInstalls) {
478 mPendingInstalls.remove(0);
479 // Indicate service bind error
480 params.serviceError();
481 }
482 mPendingInstalls.clear();
483 } else if (mPendingInstalls.size() > 0) {
484 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800485 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800486 params.startCopy();
487 }
488 } else {
489 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800490 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800491 }
492 break;
493 }
494 case MCS_RECONNECT : {
495 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
496 if (mPendingInstalls.size() > 0) {
497 if (mBound) {
498 disconnectService();
499 }
500 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800501 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800502 for (HandlerParams params : mPendingInstalls) {
503 mPendingInstalls.remove(0);
504 // Indicate service bind error
505 params.serviceError();
506 }
507 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800508 }
509 }
510 break;
511 }
512 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800513 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
514 // Delete pending install
515 if (mPendingInstalls.size() > 0) {
516 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800517 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800518 if (mPendingInstalls.size() == 0) {
519 if (mBound) {
520 disconnectService();
521 }
522 } else {
523 // There are more pending requests in queue.
524 // Just post MCS_BOUND message to trigger processing
525 // of next pending install.
526 mHandler.sendEmptyMessage(MCS_BOUND);
527 }
528 break;
529 }
530 case MCS_GIVE_UP: {
531 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
532 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800533 break;
534 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700535 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800536 String packages[];
537 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700538 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700539 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700540 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700541 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800542 if (mPendingBroadcasts == null) {
543 return;
544 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700545 size = mPendingBroadcasts.size();
546 if (size <= 0) {
547 // Nothing to be done. Just return
548 return;
549 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800550 packages = new String[size];
551 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700552 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800553 Iterator<HashMap.Entry<String, ArrayList<String>>>
554 it = mPendingBroadcasts.entrySet().iterator();
555 int i = 0;
556 while (it.hasNext() && i < size) {
557 HashMap.Entry<String, ArrayList<String>> ent = it.next();
558 packages[i] = ent.getKey();
559 components[i] = ent.getValue();
560 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700561 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800562 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700563 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800564 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700565 mPendingBroadcasts.clear();
566 }
567 // Send broadcasts
568 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800569 sendPackageChangedBroadcast(packages[i], true,
570 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700571 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700572 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700573 break;
574 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800575 case START_CLEANING_PACKAGE: {
576 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700577 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800578 synchronized (mPackages) {
579 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
580 mSettings.mPackagesToBeCleaned.add(packageName);
581 }
582 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700583 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800584 startCleaningPackages();
585 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800586 case POST_INSTALL: {
587 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
588 PostInstallData data = mRunningInstalls.get(msg.arg1);
589 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700590 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800591
592 if (data != null) {
593 InstallArgs args = data.args;
594 PackageInstalledInfo res = data.res;
595
596 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700597 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800598 Bundle extras = new Bundle(1);
599 extras.putInt(Intent.EXTRA_UID, res.uid);
600 final boolean update = res.removedInfo.removedPackage != null;
601 if (update) {
602 extras.putBoolean(Intent.EXTRA_REPLACING, true);
603 }
604 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
605 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700606 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800607 if (update) {
608 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
609 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700610 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800611 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700612 if (res.removedInfo.args != null) {
613 // Remove the replaced package's older resources safely now
614 deleteOld = true;
615 }
616 }
617 // Force a gc to clear up things
618 Runtime.getRuntime().gc();
619 // We delete after a gc for applications on sdcard.
620 if (deleteOld) {
621 synchronized (mInstallLock) {
622 res.removedInfo.args.doPostDeleteLI(true);
623 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800624 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800625 if (args.observer != null) {
626 try {
627 args.observer.packageInstalled(res.name, res.returnCode);
628 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800629 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800630 }
631 }
632 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800633 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800634 }
635 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700636 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700637 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
638 boolean reportStatus = msg.arg1 == 1;
639 boolean doGc = msg.arg2 == 1;
640 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
641 if (doGc) {
642 // Force a gc to clear up stale containers.
643 Runtime.getRuntime().gc();
644 }
645 if (msg.obj != null) {
646 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
647 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
648 // Unload containers
649 unloadAllContainers(args);
650 }
651 if (reportStatus) {
652 try {
653 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
654 PackageHelper.getMountService().finishMediaUpdate();
655 } catch (RemoteException e) {
656 Log.e(TAG, "MountService not running?");
657 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700658 }
659 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700660 case WRITE_SETTINGS: {
661 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
662 synchronized (mPackages) {
663 removeMessages(WRITE_SETTINGS);
664 mSettings.writeLP();
665 }
666 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
667 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700668 }
669 }
670 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800671
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700672 void scheduleWriteSettingsLocked() {
673 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
674 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
675 }
676 }
677
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800678 static boolean installOnSd(int flags) {
679 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700680 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800681 return false;
682 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700683 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
684 return true;
685 }
686 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800687 }
688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 public static final IPackageManager main(Context context, boolean factoryTest) {
690 PackageManagerService m = new PackageManagerService(context, factoryTest);
691 ServiceManager.addService("package", m);
692 return m;
693 }
694
695 static String[] splitString(String str, char sep) {
696 int count = 1;
697 int i = 0;
698 while ((i=str.indexOf(sep, i)) >= 0) {
699 count++;
700 i++;
701 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 String[] res = new String[count];
704 i=0;
705 count = 0;
706 int lastI=0;
707 while ((i=str.indexOf(sep, i)) >= 0) {
708 res[count] = str.substring(lastI, i);
709 count++;
710 i++;
711 lastI = i;
712 }
713 res[count] = str.substring(lastI, str.length());
714 return res;
715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800718 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800722 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 mContext = context;
726 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700727 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 mMetrics = new DisplayMetrics();
729 mSettings = new Settings();
730 mSettings.addSharedUserLP("android.uid.system",
731 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
732 mSettings.addSharedUserLP("android.uid.phone",
733 MULTIPLE_APPLICATION_UIDS
734 ? RADIO_UID : FIRST_APPLICATION_UID,
735 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400736 mSettings.addSharedUserLP("android.uid.log",
737 MULTIPLE_APPLICATION_UIDS
738 ? LOG_UID : FIRST_APPLICATION_UID,
739 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740
741 String separateProcesses = SystemProperties.get("debug.separate_processes");
742 if (separateProcesses != null && separateProcesses.length() > 0) {
743 if ("*".equals(separateProcesses)) {
744 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
745 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800746 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 } else {
748 mDefParseFlags = 0;
749 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800750 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 + separateProcesses);
752 }
753 } else {
754 mDefParseFlags = 0;
755 mSeparateProcesses = null;
756 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 Installer installer = new Installer();
759 // Little hacky thing to check if installd is here, to determine
760 // whether we are running on the simulator and thus need to take
761 // care of building the /data file structure ourself.
762 // (apparently the sim now has a working installer)
763 if (installer.ping() && Process.supportsProcesses()) {
764 mInstaller = installer;
765 } else {
766 mInstaller = null;
767 }
768
769 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
770 Display d = wm.getDefaultDisplay();
771 d.getMetrics(mMetrics);
772
773 synchronized (mInstallLock) {
774 synchronized (mPackages) {
775 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700776 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 File dataDir = Environment.getDataDirectory();
779 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800780 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
782
783 if (mInstaller == null) {
784 // Make sure these dirs exist, when we are running in
785 // the simulator.
786 // Make a wide-open directory for random misc stuff.
787 File miscDir = new File(dataDir, "misc");
788 miscDir.mkdirs();
789 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800790 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 mDrmAppPrivateInstallDir.mkdirs();
792 }
793
794 readPermissions();
795
796 mRestoredSettings = mSettings.readLP();
797 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800798
799 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800801
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800802 // Set flag to monitor and not change apk file paths when
803 // scanning install directories.
804 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700805 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800806 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800807 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700808 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700813 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700816 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 /**
819 * Out of paranoia, ensure that everything in the boot class
820 * path has been dexed.
821 */
822 String bootClassPath = System.getProperty("java.boot.class.path");
823 if (bootClassPath != null) {
824 String[] paths = splitString(bootClassPath, ':');
825 for (int i=0; i<paths.length; i++) {
826 try {
827 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
828 libFiles.add(paths[i]);
829 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700830 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 }
832 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800833 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800835 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
837 }
838 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800839 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 /**
843 * Also ensure all external libraries have had dexopt run on them.
844 */
845 if (mSharedLibraries.size() > 0) {
846 Iterator<String> libs = mSharedLibraries.values().iterator();
847 while (libs.hasNext()) {
848 String lib = libs.next();
849 try {
850 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
851 libFiles.add(lib);
852 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700853 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 }
855 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800856 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800858 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 }
860 }
861 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 // Gross hack for now: we know this file doesn't contain any
864 // code, so don't dexopt it to avoid the resulting log spew.
865 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 /**
868 * And there are a number of commands implemented in Java, which
869 * we currently need to do the dexopt on so that they can be
870 * run from a non-root shell.
871 */
872 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700873 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 for (int i=0; i<frameworkFiles.length; i++) {
875 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
876 String path = libPath.getPath();
877 // Skip the file if we alrady did it.
878 if (libFiles.contains(path)) {
879 continue;
880 }
881 // Skip the file if it is not a type we want to dexopt.
882 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
883 continue;
884 }
885 try {
886 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
887 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700888 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 }
890 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800891 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800893 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 }
895 }
896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800897
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700898 if (didDexOpt) {
899 // If we had to do a dexopt of one of the previous
900 // things, then something on the system has changed.
901 // Consider this significant, and wipe away all other
902 // existing dexopt files to ensure we don't leave any
903 // dangling around.
904 String[] files = mDalvikCacheDir.list();
905 if (files != null) {
906 for (int i=0; i<files.length; i++) {
907 String fn = files[i];
908 if (fn.startsWith("data@app@")
909 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800910 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700911 (new File(mDalvikCacheDir, fn)).delete();
912 }
913 }
914 }
915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800917
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800918 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 mFrameworkInstallObserver = new AppDirObserver(
920 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
921 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700922 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
923 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800924 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800925
926 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
928 mSystemInstallObserver = new AppDirObserver(
929 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
930 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700931 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
932 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800933
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700934 // Collect all vendor packages.
935 mVendorAppDir = new File("/vendor/app");
936 mVendorInstallObserver = new AppDirObserver(
937 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
938 mVendorInstallObserver.startWatching();
939 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
940 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
941
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800942 if (mInstaller != null) {
943 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
944 mInstaller.moveFiles();
945 }
946
947 // Prune any system packages that no longer exist.
948 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
949 while (psit.hasNext()) {
950 PackageSetting ps = psit.next();
951 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800952 && !mPackages.containsKey(ps.name)
953 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800954 psit.remove();
955 String msg = "System package " + ps.name
956 + " no longer exists; wiping its data";
957 reportSettingsProblem(Log.WARN, msg);
958 if (mInstaller != null) {
959 // XXX how to set useEncryptedFSDir for packages that
960 // are not encrypted?
961 mInstaller.remove(ps.name, true);
962 }
963 }
964 }
965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 mAppInstallDir = new File(dataDir, "app");
967 if (mInstaller == null) {
968 // Make sure these dirs exist, when we are running in
969 // the simulator.
970 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
971 }
972 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800973 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 //clean up list
975 for(int i = 0; i < deletePkgsList.size(); i++) {
976 //clean up here
977 cleanupInstallFailedPackage(deletePkgsList.get(i));
978 }
979 //delete tmp files
980 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800981
982 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 SystemClock.uptimeMillis());
984 mAppInstallObserver = new AppDirObserver(
985 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
986 mAppInstallObserver.startWatching();
987 scanDirLI(mAppInstallDir, 0, scanMode);
988
989 mDrmAppInstallObserver = new AppDirObserver(
990 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
991 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800992 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800994 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800996 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 + ((SystemClock.uptimeMillis()-startTime)/1000f)
998 + " seconds");
999
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001000 // If the platform SDK has changed since the last time we booted,
1001 // we need to re-grant app permission to catch any new ones that
1002 // appear. This is really a hack, and means that apps can in some
1003 // cases get permissions that the user didn't initially explicitly
1004 // allow... it would be nice to have some better way to handle
1005 // this situation.
1006 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1007 != mSdkVersion;
1008 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1009 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1010 + "; regranting permissions for internal storage");
1011 mSettings.mInternalSdkPlatform = mSdkVersion;
1012
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001013 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014
1015 mSettings.writeLP();
1016
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001017 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 // Now after opening every single application zip, make sure they
1021 // are all flushed. Not really needed, but keeps things nice and
1022 // tidy.
1023 Runtime.getRuntime().gc();
1024 } // synchronized (mPackages)
1025 } // synchronized (mInstallLock)
1026 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 @Override
1029 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1030 throws RemoteException {
1031 try {
1032 return super.onTransact(code, data, reply, flags);
1033 } catch (RuntimeException e) {
1034 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001035 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 }
1037 throw e;
1038 }
1039 }
1040
Dianne Hackborne6620b22010-01-22 14:46:21 -08001041 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001042 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001044 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1045 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001047 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001048 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050 } else {
1051 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001052 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 File dataDir = new File(pkg.applicationInfo.dataDir);
1054 dataDir.delete();
1055 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001056 if (ps.codePath != null) {
1057 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001058 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001059 }
1060 }
1061 if (ps.resourcePath != null) {
1062 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001063 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001064 }
1065 }
1066 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
1068
1069 void readPermissions() {
1070 // Read permissions from .../etc/permission directory.
1071 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1072 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001073 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 return;
1075 }
1076 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001077 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 return;
1079 }
1080
1081 // Iterate over the files in the directory and scan .xml files
1082 for (File f : libraryDir.listFiles()) {
1083 // We'll read platform.xml last
1084 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1085 continue;
1086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001089 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 continue;
1091 }
1092 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001093 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 continue;
1095 }
1096
1097 readPermissionsFromXml(f);
1098 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1101 final File permFile = new File(Environment.getRootDirectory(),
1102 "etc/permissions/platform.xml");
1103 readPermissionsFromXml(permFile);
1104 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001105
1106 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 FileReader permReader = null;
1108 try {
1109 permReader = new FileReader(permFile);
1110 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001111 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 return;
1113 }
1114
1115 try {
1116 XmlPullParser parser = Xml.newPullParser();
1117 parser.setInput(permReader);
1118
1119 XmlUtils.beginDocument(parser, "permissions");
1120
1121 while (true) {
1122 XmlUtils.nextElement(parser);
1123 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1124 break;
1125 }
1126
1127 String name = parser.getName();
1128 if ("group".equals(name)) {
1129 String gidStr = parser.getAttributeValue(null, "gid");
1130 if (gidStr != null) {
1131 int gid = Integer.parseInt(gidStr);
1132 mGlobalGids = appendInt(mGlobalGids, gid);
1133 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001134 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 + parser.getPositionDescription());
1136 }
1137
1138 XmlUtils.skipCurrentTag(parser);
1139 continue;
1140 } else if ("permission".equals(name)) {
1141 String perm = parser.getAttributeValue(null, "name");
1142 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001143 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 + parser.getPositionDescription());
1145 XmlUtils.skipCurrentTag(parser);
1146 continue;
1147 }
1148 perm = perm.intern();
1149 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 } else if ("assign-permission".equals(name)) {
1152 String perm = parser.getAttributeValue(null, "name");
1153 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001154 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 + parser.getPositionDescription());
1156 XmlUtils.skipCurrentTag(parser);
1157 continue;
1158 }
1159 String uidStr = parser.getAttributeValue(null, "uid");
1160 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001161 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 + parser.getPositionDescription());
1163 XmlUtils.skipCurrentTag(parser);
1164 continue;
1165 }
1166 int uid = Process.getUidForName(uidStr);
1167 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001168 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 + uidStr + "\" at "
1170 + parser.getPositionDescription());
1171 XmlUtils.skipCurrentTag(parser);
1172 continue;
1173 }
1174 perm = perm.intern();
1175 HashSet<String> perms = mSystemPermissions.get(uid);
1176 if (perms == null) {
1177 perms = new HashSet<String>();
1178 mSystemPermissions.put(uid, perms);
1179 }
1180 perms.add(perm);
1181 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 } else if ("library".equals(name)) {
1184 String lname = parser.getAttributeValue(null, "name");
1185 String lfile = parser.getAttributeValue(null, "file");
1186 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001187 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 + parser.getPositionDescription());
1189 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001190 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 + parser.getPositionDescription());
1192 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001193 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001194 mSharedLibraries.put(lname, lfile);
1195 }
1196 XmlUtils.skipCurrentTag(parser);
1197 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001198
Dianne Hackborn49237342009-08-27 20:08:01 -07001199 } else if ("feature".equals(name)) {
1200 String fname = parser.getAttributeValue(null, "name");
1201 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001202 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001203 + parser.getPositionDescription());
1204 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001205 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001206 FeatureInfo fi = new FeatureInfo();
1207 fi.name = fname;
1208 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 }
1210 XmlUtils.skipCurrentTag(parser);
1211 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 } else {
1214 XmlUtils.skipCurrentTag(parser);
1215 continue;
1216 }
1217
1218 }
1219 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001220 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001222 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 }
1224 }
1225
1226 void readPermission(XmlPullParser parser, String name)
1227 throws IOException, XmlPullParserException {
1228
1229 name = name.intern();
1230
1231 BasePermission bp = mSettings.mPermissions.get(name);
1232 if (bp == null) {
1233 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1234 mSettings.mPermissions.put(name, bp);
1235 }
1236 int outerDepth = parser.getDepth();
1237 int type;
1238 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1239 && (type != XmlPullParser.END_TAG
1240 || parser.getDepth() > outerDepth)) {
1241 if (type == XmlPullParser.END_TAG
1242 || type == XmlPullParser.TEXT) {
1243 continue;
1244 }
1245
1246 String tagName = parser.getName();
1247 if ("group".equals(tagName)) {
1248 String gidStr = parser.getAttributeValue(null, "gid");
1249 if (gidStr != null) {
1250 int gid = Process.getGidForName(gidStr);
1251 bp.gids = appendInt(bp.gids, gid);
1252 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001253 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 + parser.getPositionDescription());
1255 }
1256 }
1257 XmlUtils.skipCurrentTag(parser);
1258 }
1259 }
1260
1261 static int[] appendInt(int[] cur, int val) {
1262 if (cur == null) {
1263 return new int[] { val };
1264 }
1265 final int N = cur.length;
1266 for (int i=0; i<N; i++) {
1267 if (cur[i] == val) {
1268 return cur;
1269 }
1270 }
1271 int[] ret = new int[N+1];
1272 System.arraycopy(cur, 0, ret, 0, N);
1273 ret[N] = val;
1274 return ret;
1275 }
1276
1277 static int[] appendInts(int[] cur, int[] add) {
1278 if (add == null) return cur;
1279 if (cur == null) return add;
1280 final int N = add.length;
1281 for (int i=0; i<N; i++) {
1282 cur = appendInt(cur, add[i]);
1283 }
1284 return cur;
1285 }
1286
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001287 static int[] removeInt(int[] cur, int val) {
1288 if (cur == null) {
1289 return null;
1290 }
1291 final int N = cur.length;
1292 for (int i=0; i<N; i++) {
1293 if (cur[i] == val) {
1294 int[] ret = new int[N-1];
1295 if (i > 0) {
1296 System.arraycopy(cur, 0, ret, 0, i);
1297 }
1298 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001299 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001300 }
1301 return ret;
1302 }
1303 }
1304 return cur;
1305 }
1306
1307 static int[] removeInts(int[] cur, int[] rem) {
1308 if (rem == null) return cur;
1309 if (cur == null) return cur;
1310 final int N = rem.length;
1311 for (int i=0; i<N; i++) {
1312 cur = removeInt(cur, rem[i]);
1313 }
1314 return cur;
1315 }
1316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001318 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1319 // The package has been uninstalled but has retained data and resources.
1320 return PackageParser.generatePackageInfo(p, null, flags);
1321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 final PackageSetting ps = (PackageSetting)p.mExtras;
1323 if (ps == null) {
1324 return null;
1325 }
1326 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1327 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1328 }
1329
1330 public PackageInfo getPackageInfo(String packageName, int flags) {
1331 synchronized (mPackages) {
1332 PackageParser.Package p = mPackages.get(packageName);
1333 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001334 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 + ": " + p);
1336 if (p != null) {
1337 return generatePackageInfo(p, flags);
1338 }
1339 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1340 return generatePackageInfoFromSettingsLP(packageName, flags);
1341 }
1342 }
1343 return null;
1344 }
1345
Dianne Hackborn47096932010-02-11 15:57:09 -08001346 public String[] currentToCanonicalPackageNames(String[] names) {
1347 String[] out = new String[names.length];
1348 synchronized (mPackages) {
1349 for (int i=names.length-1; i>=0; i--) {
1350 PackageSetting ps = mSettings.mPackages.get(names[i]);
1351 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1352 }
1353 }
1354 return out;
1355 }
1356
1357 public String[] canonicalToCurrentPackageNames(String[] names) {
1358 String[] out = new String[names.length];
1359 synchronized (mPackages) {
1360 for (int i=names.length-1; i>=0; i--) {
1361 String cur = mSettings.mRenamedPackages.get(names[i]);
1362 out[i] = cur != null ? cur : names[i];
1363 }
1364 }
1365 return out;
1366 }
1367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 public int getPackageUid(String packageName) {
1369 synchronized (mPackages) {
1370 PackageParser.Package p = mPackages.get(packageName);
1371 if(p != null) {
1372 return p.applicationInfo.uid;
1373 }
1374 PackageSetting ps = mSettings.mPackages.get(packageName);
1375 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1376 return -1;
1377 }
1378 p = ps.pkg;
1379 return p != null ? p.applicationInfo.uid : -1;
1380 }
1381 }
1382
1383 public int[] getPackageGids(String packageName) {
1384 synchronized (mPackages) {
1385 PackageParser.Package p = mPackages.get(packageName);
1386 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001387 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 + ": " + p);
1389 if (p != null) {
1390 final PackageSetting ps = (PackageSetting)p.mExtras;
1391 final SharedUserSetting suid = ps.sharedUser;
1392 return suid != null ? suid.gids : ps.gids;
1393 }
1394 }
1395 // stupid thing to indicate an error.
1396 return new int[0];
1397 }
1398
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001399 static final PermissionInfo generatePermissionInfo(
1400 BasePermission bp, int flags) {
1401 if (bp.perm != null) {
1402 return PackageParser.generatePermissionInfo(bp.perm, flags);
1403 }
1404 PermissionInfo pi = new PermissionInfo();
1405 pi.name = bp.name;
1406 pi.packageName = bp.sourcePackage;
1407 pi.nonLocalizedLabel = bp.name;
1408 pi.protectionLevel = bp.protectionLevel;
1409 return pi;
1410 }
1411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 public PermissionInfo getPermissionInfo(String name, int flags) {
1413 synchronized (mPackages) {
1414 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001415 if (p != null) {
1416 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
1418 return null;
1419 }
1420 }
1421
1422 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1423 synchronized (mPackages) {
1424 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1425 for (BasePermission p : mSettings.mPermissions.values()) {
1426 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001427 if (p.perm == null || p.perm.info.group == null) {
1428 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
1430 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001431 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1433 }
1434 }
1435 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 if (out.size() > 0) {
1438 return out;
1439 }
1440 return mPermissionGroups.containsKey(group) ? out : null;
1441 }
1442 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1445 synchronized (mPackages) {
1446 return PackageParser.generatePermissionGroupInfo(
1447 mPermissionGroups.get(name), flags);
1448 }
1449 }
1450
1451 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1452 synchronized (mPackages) {
1453 final int N = mPermissionGroups.size();
1454 ArrayList<PermissionGroupInfo> out
1455 = new ArrayList<PermissionGroupInfo>(N);
1456 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1457 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1458 }
1459 return out;
1460 }
1461 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1464 PackageSetting ps = mSettings.mPackages.get(packageName);
1465 if(ps != null) {
1466 if(ps.pkg == null) {
1467 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1468 if(pInfo != null) {
1469 return pInfo.applicationInfo;
1470 }
1471 return null;
1472 }
1473 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1474 }
1475 return null;
1476 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1479 PackageSetting ps = mSettings.mPackages.get(packageName);
1480 if(ps != null) {
1481 if(ps.pkg == null) {
1482 ps.pkg = new PackageParser.Package(packageName);
1483 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001484 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1485 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1486 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1487 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001488 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001489 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 }
1491 return generatePackageInfo(ps.pkg, flags);
1492 }
1493 return null;
1494 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1497 synchronized (mPackages) {
1498 PackageParser.Package p = mPackages.get(packageName);
1499 if (Config.LOGV) Log.v(
1500 TAG, "getApplicationInfo " + packageName
1501 + ": " + p);
1502 if (p != null) {
1503 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001504 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 }
1506 if ("android".equals(packageName)||"system".equals(packageName)) {
1507 return mAndroidApplication;
1508 }
1509 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1510 return generateApplicationInfoFromSettingsLP(packageName, flags);
1511 }
1512 }
1513 return null;
1514 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001515
1516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1518 mContext.enforceCallingOrSelfPermission(
1519 android.Manifest.permission.CLEAR_APP_CACHE, null);
1520 // Queue up an async operation since clearing cache may take a little while.
1521 mHandler.post(new Runnable() {
1522 public void run() {
1523 mHandler.removeCallbacks(this);
1524 int retCode = -1;
1525 if (mInstaller != null) {
1526 retCode = mInstaller.freeCache(freeStorageSize);
1527 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001528 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 }
1530 } //end if mInstaller
1531 if (observer != null) {
1532 try {
1533 observer.onRemoveCompleted(null, (retCode >= 0));
1534 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001535 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 }
1537 }
1538 }
1539 });
1540 }
1541
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001542 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001543 mContext.enforceCallingOrSelfPermission(
1544 android.Manifest.permission.CLEAR_APP_CACHE, null);
1545 // Queue up an async operation since clearing cache may take a little while.
1546 mHandler.post(new Runnable() {
1547 public void run() {
1548 mHandler.removeCallbacks(this);
1549 int retCode = -1;
1550 if (mInstaller != null) {
1551 retCode = mInstaller.freeCache(freeStorageSize);
1552 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001553 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001554 }
1555 }
1556 if(pi != null) {
1557 try {
1558 // Callback via pending intent
1559 int code = (retCode >= 0) ? 1 : 0;
1560 pi.sendIntent(null, code, null,
1561 null, null);
1562 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001563 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001564 }
1565 }
1566 }
1567 });
1568 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1571 synchronized (mPackages) {
1572 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001573
1574 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001576 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578 if (mResolveComponentName.equals(component)) {
1579 return mResolveActivity;
1580 }
1581 }
1582 return null;
1583 }
1584
1585 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1586 synchronized (mPackages) {
1587 PackageParser.Activity a = mReceivers.mActivities.get(component);
1588 if (Config.LOGV) Log.v(
1589 TAG, "getReceiverInfo " + component + ": " + a);
1590 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1591 return PackageParser.generateActivityInfo(a, flags);
1592 }
1593 }
1594 return null;
1595 }
1596
1597 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1598 synchronized (mPackages) {
1599 PackageParser.Service s = mServices.mServices.get(component);
1600 if (Config.LOGV) Log.v(
1601 TAG, "getServiceInfo " + component + ": " + s);
1602 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1603 return PackageParser.generateServiceInfo(s, flags);
1604 }
1605 }
1606 return null;
1607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001608
Dianne Hackborn361199b2010-08-30 17:42:07 -07001609 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1610 synchronized (mPackages) {
1611 PackageParser.Provider p = mProvidersByComponent.get(component);
1612 if (Config.LOGV) Log.v(
1613 TAG, "getProviderInfo " + component + ": " + p);
1614 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1615 return PackageParser.generateProviderInfo(p, flags);
1616 }
1617 }
1618 return null;
1619 }
1620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 public String[] getSystemSharedLibraryNames() {
1622 Set<String> libSet;
1623 synchronized (mPackages) {
1624 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001625 int size = libSet.size();
1626 if (size > 0) {
1627 String[] libs = new String[size];
1628 libSet.toArray(libs);
1629 return libs;
1630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001632 return null;
1633 }
1634
1635 public FeatureInfo[] getSystemAvailableFeatures() {
1636 Collection<FeatureInfo> featSet;
1637 synchronized (mPackages) {
1638 featSet = mAvailableFeatures.values();
1639 int size = featSet.size();
1640 if (size > 0) {
1641 FeatureInfo[] features = new FeatureInfo[size+1];
1642 featSet.toArray(features);
1643 FeatureInfo fi = new FeatureInfo();
1644 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1645 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1646 features[size] = fi;
1647 return features;
1648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 }
1650 return null;
1651 }
1652
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001653 public boolean hasSystemFeature(String name) {
1654 synchronized (mPackages) {
1655 return mAvailableFeatures.containsKey(name);
1656 }
1657 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 public int checkPermission(String permName, String pkgName) {
1660 synchronized (mPackages) {
1661 PackageParser.Package p = mPackages.get(pkgName);
1662 if (p != null && p.mExtras != null) {
1663 PackageSetting ps = (PackageSetting)p.mExtras;
1664 if (ps.sharedUser != null) {
1665 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1666 return PackageManager.PERMISSION_GRANTED;
1667 }
1668 } else if (ps.grantedPermissions.contains(permName)) {
1669 return PackageManager.PERMISSION_GRANTED;
1670 }
1671 }
1672 }
1673 return PackageManager.PERMISSION_DENIED;
1674 }
1675
1676 public int checkUidPermission(String permName, int uid) {
1677 synchronized (mPackages) {
1678 Object obj = mSettings.getUserIdLP(uid);
1679 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001680 GrantedPermissions gp = (GrantedPermissions)obj;
1681 if (gp.grantedPermissions.contains(permName)) {
1682 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 }
1684 } else {
1685 HashSet<String> perms = mSystemPermissions.get(uid);
1686 if (perms != null && perms.contains(permName)) {
1687 return PackageManager.PERMISSION_GRANTED;
1688 }
1689 }
1690 }
1691 return PackageManager.PERMISSION_DENIED;
1692 }
1693
1694 private BasePermission findPermissionTreeLP(String permName) {
1695 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1696 if (permName.startsWith(bp.name) &&
1697 permName.length() > bp.name.length() &&
1698 permName.charAt(bp.name.length()) == '.') {
1699 return bp;
1700 }
1701 }
1702 return null;
1703 }
1704
1705 private BasePermission checkPermissionTreeLP(String permName) {
1706 if (permName != null) {
1707 BasePermission bp = findPermissionTreeLP(permName);
1708 if (bp != null) {
1709 if (bp.uid == Binder.getCallingUid()) {
1710 return bp;
1711 }
1712 throw new SecurityException("Calling uid "
1713 + Binder.getCallingUid()
1714 + " is not allowed to add to permission tree "
1715 + bp.name + " owned by uid " + bp.uid);
1716 }
1717 }
1718 throw new SecurityException("No permission tree found for " + permName);
1719 }
1720
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001721 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1722 if (s1 == null) {
1723 return s2 == null;
1724 }
1725 if (s2 == null) {
1726 return false;
1727 }
1728 if (s1.getClass() != s2.getClass()) {
1729 return false;
1730 }
1731 return s1.equals(s2);
1732 }
1733
1734 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1735 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001736 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001737 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1738 if (!compareStrings(pi1.name, pi2.name)) return false;
1739 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1740 // We'll take care of setting this one.
1741 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1742 // These are not currently stored in settings.
1743 //if (!compareStrings(pi1.group, pi2.group)) return false;
1744 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1745 //if (pi1.labelRes != pi2.labelRes) return false;
1746 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1747 return true;
1748 }
1749
1750 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1751 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1752 throw new SecurityException("Label must be specified in permission");
1753 }
1754 BasePermission tree = checkPermissionTreeLP(info.name);
1755 BasePermission bp = mSettings.mPermissions.get(info.name);
1756 boolean added = bp == null;
1757 boolean changed = true;
1758 if (added) {
1759 bp = new BasePermission(info.name, tree.sourcePackage,
1760 BasePermission.TYPE_DYNAMIC);
1761 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1762 throw new SecurityException(
1763 "Not allowed to modify non-dynamic permission "
1764 + info.name);
1765 } else {
1766 if (bp.protectionLevel == info.protectionLevel
1767 && bp.perm.owner.equals(tree.perm.owner)
1768 && bp.uid == tree.uid
1769 && comparePermissionInfos(bp.perm.info, info)) {
1770 changed = false;
1771 }
1772 }
1773 bp.protectionLevel = info.protectionLevel;
1774 bp.perm = new PackageParser.Permission(tree.perm.owner,
1775 new PermissionInfo(info));
1776 bp.perm.info.packageName = tree.perm.info.packageName;
1777 bp.uid = tree.uid;
1778 if (added) {
1779 mSettings.mPermissions.put(info.name, bp);
1780 }
1781 if (changed) {
1782 if (!async) {
1783 mSettings.writeLP();
1784 } else {
1785 scheduleWriteSettingsLocked();
1786 }
1787 }
1788 return added;
1789 }
1790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 public boolean addPermission(PermissionInfo info) {
1792 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001793 return addPermissionLocked(info, false);
1794 }
1795 }
1796
1797 public boolean addPermissionAsync(PermissionInfo info) {
1798 synchronized (mPackages) {
1799 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 }
1801 }
1802
1803 public void removePermission(String name) {
1804 synchronized (mPackages) {
1805 checkPermissionTreeLP(name);
1806 BasePermission bp = mSettings.mPermissions.get(name);
1807 if (bp != null) {
1808 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1809 throw new SecurityException(
1810 "Not allowed to modify non-dynamic permission "
1811 + name);
1812 }
1813 mSettings.mPermissions.remove(name);
1814 mSettings.writeLP();
1815 }
1816 }
1817 }
1818
Dianne Hackborn854060af2009-07-09 18:14:31 -07001819 public boolean isProtectedBroadcast(String actionName) {
1820 synchronized (mPackages) {
1821 return mProtectedBroadcasts.contains(actionName);
1822 }
1823 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 public int checkSignatures(String pkg1, String pkg2) {
1826 synchronized (mPackages) {
1827 PackageParser.Package p1 = mPackages.get(pkg1);
1828 PackageParser.Package p2 = mPackages.get(pkg2);
1829 if (p1 == null || p1.mExtras == null
1830 || p2 == null || p2.mExtras == null) {
1831 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1832 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001833 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
1835 }
1836
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001837 public int checkUidSignatures(int uid1, int uid2) {
1838 synchronized (mPackages) {
1839 Signature[] s1;
1840 Signature[] s2;
1841 Object obj = mSettings.getUserIdLP(uid1);
1842 if (obj != null) {
1843 if (obj instanceof SharedUserSetting) {
1844 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1845 } else if (obj instanceof PackageSetting) {
1846 s1 = ((PackageSetting)obj).signatures.mSignatures;
1847 } else {
1848 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1849 }
1850 } else {
1851 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1852 }
1853 obj = mSettings.getUserIdLP(uid2);
1854 if (obj != null) {
1855 if (obj instanceof SharedUserSetting) {
1856 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1857 } else if (obj instanceof PackageSetting) {
1858 s2 = ((PackageSetting)obj).signatures.mSignatures;
1859 } else {
1860 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1861 }
1862 } else {
1863 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1864 }
1865 return checkSignaturesLP(s1, s2);
1866 }
1867 }
1868
1869 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1870 if (s1 == null) {
1871 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1873 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1874 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001875 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1877 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001878 HashSet<Signature> set1 = new HashSet<Signature>();
1879 for (Signature sig : s1) {
1880 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001882 HashSet<Signature> set2 = new HashSet<Signature>();
1883 for (Signature sig : s2) {
1884 set2.add(sig);
1885 }
1886 // Make sure s2 contains all signatures in s1.
1887 if (set1.equals(set2)) {
1888 return PackageManager.SIGNATURE_MATCH;
1889 }
1890 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 }
1892
1893 public String[] getPackagesForUid(int uid) {
1894 synchronized (mPackages) {
1895 Object obj = mSettings.getUserIdLP(uid);
1896 if (obj instanceof SharedUserSetting) {
1897 SharedUserSetting sus = (SharedUserSetting)obj;
1898 final int N = sus.packages.size();
1899 String[] res = new String[N];
1900 Iterator<PackageSetting> it = sus.packages.iterator();
1901 int i=0;
1902 while (it.hasNext()) {
1903 res[i++] = it.next().name;
1904 }
1905 return res;
1906 } else if (obj instanceof PackageSetting) {
1907 PackageSetting ps = (PackageSetting)obj;
1908 return new String[] { ps.name };
1909 }
1910 }
1911 return null;
1912 }
1913
1914 public String getNameForUid(int uid) {
1915 synchronized (mPackages) {
1916 Object obj = mSettings.getUserIdLP(uid);
1917 if (obj instanceof SharedUserSetting) {
1918 SharedUserSetting sus = (SharedUserSetting)obj;
1919 return sus.name + ":" + sus.userId;
1920 } else if (obj instanceof PackageSetting) {
1921 PackageSetting ps = (PackageSetting)obj;
1922 return ps.name;
1923 }
1924 }
1925 return null;
1926 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 public int getUidForSharedUser(String sharedUserName) {
1929 if(sharedUserName == null) {
1930 return -1;
1931 }
1932 synchronized (mPackages) {
1933 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1934 if(suid == null) {
1935 return -1;
1936 }
1937 return suid.userId;
1938 }
1939 }
1940
1941 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1942 int flags) {
1943 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001944 return chooseBestActivity(intent, resolvedType, flags, query);
1945 }
1946
Mihai Predaeae850c2009-05-13 10:13:48 +02001947 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1948 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 if (query != null) {
1950 final int N = query.size();
1951 if (N == 1) {
1952 return query.get(0);
1953 } else if (N > 1) {
1954 // If there is more than one activity with the same priority,
1955 // then let the user decide between them.
1956 ResolveInfo r0 = query.get(0);
1957 ResolveInfo r1 = query.get(1);
1958 if (false) {
1959 System.out.println(r0.activityInfo.name +
1960 "=" + r0.priority + " vs " +
1961 r1.activityInfo.name +
1962 "=" + r1.priority);
1963 }
1964 // If the first activity has a higher priority, or a different
1965 // default, then it is always desireable to pick it.
1966 if (r0.priority != r1.priority
1967 || r0.preferredOrder != r1.preferredOrder
1968 || r0.isDefault != r1.isDefault) {
1969 return query.get(0);
1970 }
1971 // If we have saved a preference for a preferred activity for
1972 // this Intent, use that.
1973 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1974 flags, query, r0.priority);
1975 if (ri != null) {
1976 return ri;
1977 }
1978 return mResolveInfo;
1979 }
1980 }
1981 return null;
1982 }
1983
1984 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1985 int flags, List<ResolveInfo> query, int priority) {
1986 synchronized (mPackages) {
1987 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1988 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001989 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1991 if (prefs != null && prefs.size() > 0) {
1992 // First figure out how good the original match set is.
1993 // We will only allow preferred activities that came
1994 // from the same match quality.
1995 int match = 0;
1996 final int N = query.size();
1997 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1998 for (int j=0; j<N; j++) {
1999 ResolveInfo ri = query.get(j);
2000 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2001 + ": 0x" + Integer.toHexString(match));
2002 if (ri.match > match) match = ri.match;
2003 }
2004 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2005 + Integer.toHexString(match));
2006 match &= IntentFilter.MATCH_CATEGORY_MASK;
2007 final int M = prefs.size();
2008 for (int i=0; i<M; i++) {
2009 PreferredActivity pa = prefs.get(i);
2010 if (pa.mMatch != match) {
2011 continue;
2012 }
2013 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2014 if (DEBUG_PREFERRED) {
2015 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002016 if (ai != null) {
2017 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2018 } else {
2019 Log.v(TAG, " null");
2020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 }
2022 if (ai != null) {
2023 for (int j=0; j<N; j++) {
2024 ResolveInfo ri = query.get(j);
2025 if (!ri.activityInfo.applicationInfo.packageName
2026 .equals(ai.applicationInfo.packageName)) {
2027 continue;
2028 }
2029 if (!ri.activityInfo.name.equals(ai.name)) {
2030 continue;
2031 }
2032
2033 // Okay we found a previously set preferred app.
2034 // If the result set is different from when this
2035 // was created, we need to clear it and re-ask the
2036 // user their preference.
2037 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002038 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 + intent + " type " + resolvedType);
2040 mSettings.mPreferredActivities.removeFilter(pa);
2041 return null;
2042 }
2043
2044 // Yay!
2045 return ri;
2046 }
2047 }
2048 }
2049 }
2050 }
2051 return null;
2052 }
2053
2054 public List<ResolveInfo> queryIntentActivities(Intent intent,
2055 String resolvedType, int flags) {
2056 ComponentName comp = intent.getComponent();
2057 if (comp != null) {
2058 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2059 ActivityInfo ai = getActivityInfo(comp, flags);
2060 if (ai != null) {
2061 ResolveInfo ri = new ResolveInfo();
2062 ri.activityInfo = ai;
2063 list.add(ri);
2064 }
2065 return list;
2066 }
2067
2068 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002069 String pkgName = intent.getPackage();
2070 if (pkgName == null) {
2071 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2072 resolvedType, flags);
2073 }
2074 PackageParser.Package pkg = mPackages.get(pkgName);
2075 if (pkg != null) {
2076 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2077 resolvedType, flags, pkg.activities);
2078 }
2079 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
2081 }
2082
2083 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2084 Intent[] specifics, String[] specificTypes, Intent intent,
2085 String resolvedType, int flags) {
2086 final String resultsAction = intent.getAction();
2087
2088 List<ResolveInfo> results = queryIntentActivities(
2089 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2090 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2091
2092 int specificsPos = 0;
2093 int N;
2094
2095 // todo: note that the algorithm used here is O(N^2). This
2096 // isn't a problem in our current environment, but if we start running
2097 // into situations where we have more than 5 or 10 matches then this
2098 // should probably be changed to something smarter...
2099
2100 // First we go through and resolve each of the specific items
2101 // that were supplied, taking care of removing any corresponding
2102 // duplicate items in the generic resolve list.
2103 if (specifics != null) {
2104 for (int i=0; i<specifics.length; i++) {
2105 final Intent sintent = specifics[i];
2106 if (sintent == null) {
2107 continue;
2108 }
2109
2110 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2111 String action = sintent.getAction();
2112 if (resultsAction != null && resultsAction.equals(action)) {
2113 // If this action was explicitly requested, then don't
2114 // remove things that have it.
2115 action = null;
2116 }
2117 ComponentName comp = sintent.getComponent();
2118 ResolveInfo ri = null;
2119 ActivityInfo ai = null;
2120 if (comp == null) {
2121 ri = resolveIntent(
2122 sintent,
2123 specificTypes != null ? specificTypes[i] : null,
2124 flags);
2125 if (ri == null) {
2126 continue;
2127 }
2128 if (ri == mResolveInfo) {
2129 // ACK! Must do something better with this.
2130 }
2131 ai = ri.activityInfo;
2132 comp = new ComponentName(ai.applicationInfo.packageName,
2133 ai.name);
2134 } else {
2135 ai = getActivityInfo(comp, flags);
2136 if (ai == null) {
2137 continue;
2138 }
2139 }
2140
2141 // Look for any generic query activities that are duplicates
2142 // of this specific one, and remove them from the results.
2143 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2144 N = results.size();
2145 int j;
2146 for (j=specificsPos; j<N; j++) {
2147 ResolveInfo sri = results.get(j);
2148 if ((sri.activityInfo.name.equals(comp.getClassName())
2149 && sri.activityInfo.applicationInfo.packageName.equals(
2150 comp.getPackageName()))
2151 || (action != null && sri.filter.matchAction(action))) {
2152 results.remove(j);
2153 if (Config.LOGV) Log.v(
2154 TAG, "Removing duplicate item from " + j
2155 + " due to specific " + specificsPos);
2156 if (ri == null) {
2157 ri = sri;
2158 }
2159 j--;
2160 N--;
2161 }
2162 }
2163
2164 // Add this specific item to its proper place.
2165 if (ri == null) {
2166 ri = new ResolveInfo();
2167 ri.activityInfo = ai;
2168 }
2169 results.add(specificsPos, ri);
2170 ri.specificIndex = i;
2171 specificsPos++;
2172 }
2173 }
2174
2175 // Now we go through the remaining generic results and remove any
2176 // duplicate actions that are found here.
2177 N = results.size();
2178 for (int i=specificsPos; i<N-1; i++) {
2179 final ResolveInfo rii = results.get(i);
2180 if (rii.filter == null) {
2181 continue;
2182 }
2183
2184 // Iterate over all of the actions of this result's intent
2185 // filter... typically this should be just one.
2186 final Iterator<String> it = rii.filter.actionsIterator();
2187 if (it == null) {
2188 continue;
2189 }
2190 while (it.hasNext()) {
2191 final String action = it.next();
2192 if (resultsAction != null && resultsAction.equals(action)) {
2193 // If this action was explicitly requested, then don't
2194 // remove things that have it.
2195 continue;
2196 }
2197 for (int j=i+1; j<N; j++) {
2198 final ResolveInfo rij = results.get(j);
2199 if (rij.filter != null && rij.filter.hasAction(action)) {
2200 results.remove(j);
2201 if (Config.LOGV) Log.v(
2202 TAG, "Removing duplicate item from " + j
2203 + " due to action " + action + " at " + i);
2204 j--;
2205 N--;
2206 }
2207 }
2208 }
2209
2210 // If the caller didn't request filter information, drop it now
2211 // so we don't have to marshall/unmarshall it.
2212 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2213 rii.filter = null;
2214 }
2215 }
2216
2217 // Filter out the caller activity if so requested.
2218 if (caller != null) {
2219 N = results.size();
2220 for (int i=0; i<N; i++) {
2221 ActivityInfo ainfo = results.get(i).activityInfo;
2222 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2223 && caller.getClassName().equals(ainfo.name)) {
2224 results.remove(i);
2225 break;
2226 }
2227 }
2228 }
2229
2230 // If the caller didn't request filter information,
2231 // drop them now so we don't have to
2232 // marshall/unmarshall it.
2233 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2234 N = results.size();
2235 for (int i=0; i<N; i++) {
2236 results.get(i).filter = null;
2237 }
2238 }
2239
2240 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2241 return results;
2242 }
2243
2244 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2245 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002246 ComponentName comp = intent.getComponent();
2247 if (comp != null) {
2248 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2249 ActivityInfo ai = getReceiverInfo(comp, flags);
2250 if (ai != null) {
2251 ResolveInfo ri = new ResolveInfo();
2252 ri.activityInfo = ai;
2253 list.add(ri);
2254 }
2255 return list;
2256 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002259 String pkgName = intent.getPackage();
2260 if (pkgName == null) {
2261 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2262 resolvedType, flags);
2263 }
2264 PackageParser.Package pkg = mPackages.get(pkgName);
2265 if (pkg != null) {
2266 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2267 resolvedType, flags, pkg.receivers);
2268 }
2269 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 }
2271 }
2272
2273 public ResolveInfo resolveService(Intent intent, String resolvedType,
2274 int flags) {
2275 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2276 flags);
2277 if (query != null) {
2278 if (query.size() >= 1) {
2279 // If there is more than one service with the same priority,
2280 // just arbitrarily pick the first one.
2281 return query.get(0);
2282 }
2283 }
2284 return null;
2285 }
2286
2287 public List<ResolveInfo> queryIntentServices(Intent intent,
2288 String resolvedType, int flags) {
2289 ComponentName comp = intent.getComponent();
2290 if (comp != null) {
2291 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2292 ServiceInfo si = getServiceInfo(comp, flags);
2293 if (si != null) {
2294 ResolveInfo ri = new ResolveInfo();
2295 ri.serviceInfo = si;
2296 list.add(ri);
2297 }
2298 return list;
2299 }
2300
2301 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002302 String pkgName = intent.getPackage();
2303 if (pkgName == null) {
2304 return (List<ResolveInfo>)mServices.queryIntent(intent,
2305 resolvedType, flags);
2306 }
2307 PackageParser.Package pkg = mPackages.get(pkgName);
2308 if (pkg != null) {
2309 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2310 resolvedType, flags, pkg.services);
2311 }
2312 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313 }
2314 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 public List<PackageInfo> getInstalledPackages(int flags) {
2317 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2318
2319 synchronized (mPackages) {
2320 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2321 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2322 while (i.hasNext()) {
2323 final PackageSetting ps = i.next();
2324 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2325 if(psPkg != null) {
2326 finalList.add(psPkg);
2327 }
2328 }
2329 }
2330 else {
2331 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2332 while (i.hasNext()) {
2333 final PackageParser.Package p = i.next();
2334 if (p.applicationInfo != null) {
2335 PackageInfo pi = generatePackageInfo(p, flags);
2336 if(pi != null) {
2337 finalList.add(pi);
2338 }
2339 }
2340 }
2341 }
2342 }
2343 return finalList;
2344 }
2345
2346 public List<ApplicationInfo> getInstalledApplications(int flags) {
2347 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2348 synchronized(mPackages) {
2349 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2350 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2351 while (i.hasNext()) {
2352 final PackageSetting ps = i.next();
2353 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2354 if(ai != null) {
2355 finalList.add(ai);
2356 }
2357 }
2358 }
2359 else {
2360 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2361 while (i.hasNext()) {
2362 final PackageParser.Package p = i.next();
2363 if (p.applicationInfo != null) {
2364 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2365 if(ai != null) {
2366 finalList.add(ai);
2367 }
2368 }
2369 }
2370 }
2371 }
2372 return finalList;
2373 }
2374
2375 public List<ApplicationInfo> getPersistentApplications(int flags) {
2376 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2377
2378 synchronized (mPackages) {
2379 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2380 while (i.hasNext()) {
2381 PackageParser.Package p = i.next();
2382 if (p.applicationInfo != null
2383 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002384 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002385 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 }
2387 }
2388 }
2389
2390 return finalList;
2391 }
2392
2393 public ProviderInfo resolveContentProvider(String name, int flags) {
2394 synchronized (mPackages) {
2395 final PackageParser.Provider provider = mProviders.get(name);
2396 return provider != null
2397 && mSettings.isEnabledLP(provider.info, flags)
2398 && (!mSafeMode || (provider.info.applicationInfo.flags
2399 &ApplicationInfo.FLAG_SYSTEM) != 0)
2400 ? PackageParser.generateProviderInfo(provider, flags)
2401 : null;
2402 }
2403 }
2404
Fred Quintana718d8a22009-04-29 17:53:20 -07002405 /**
2406 * @deprecated
2407 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 public void querySyncProviders(List outNames, List outInfo) {
2409 synchronized (mPackages) {
2410 Iterator<Map.Entry<String, PackageParser.Provider>> i
2411 = mProviders.entrySet().iterator();
2412
2413 while (i.hasNext()) {
2414 Map.Entry<String, PackageParser.Provider> entry = i.next();
2415 PackageParser.Provider p = entry.getValue();
2416
2417 if (p.syncable
2418 && (!mSafeMode || (p.info.applicationInfo.flags
2419 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2420 outNames.add(entry.getKey());
2421 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2422 }
2423 }
2424 }
2425 }
2426
2427 public List<ProviderInfo> queryContentProviders(String processName,
2428 int uid, int flags) {
2429 ArrayList<ProviderInfo> finalList = null;
2430
2431 synchronized (mPackages) {
2432 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2433 while (i.hasNext()) {
2434 PackageParser.Provider p = i.next();
2435 if (p.info.authority != null
2436 && (processName == null ||
2437 (p.info.processName.equals(processName)
2438 && p.info.applicationInfo.uid == uid))
2439 && mSettings.isEnabledLP(p.info, flags)
2440 && (!mSafeMode || (p.info.applicationInfo.flags
2441 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2442 if (finalList == null) {
2443 finalList = new ArrayList<ProviderInfo>(3);
2444 }
2445 finalList.add(PackageParser.generateProviderInfo(p,
2446 flags));
2447 }
2448 }
2449 }
2450
2451 if (finalList != null) {
2452 Collections.sort(finalList, mProviderInitOrderSorter);
2453 }
2454
2455 return finalList;
2456 }
2457
2458 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2459 int flags) {
2460 synchronized (mPackages) {
2461 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2462 return PackageParser.generateInstrumentationInfo(i, flags);
2463 }
2464 }
2465
2466 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2467 int flags) {
2468 ArrayList<InstrumentationInfo> finalList =
2469 new ArrayList<InstrumentationInfo>();
2470
2471 synchronized (mPackages) {
2472 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2473 while (i.hasNext()) {
2474 PackageParser.Instrumentation p = i.next();
2475 if (targetPackage == null
2476 || targetPackage.equals(p.info.targetPackage)) {
2477 finalList.add(PackageParser.generateInstrumentationInfo(p,
2478 flags));
2479 }
2480 }
2481 }
2482
2483 return finalList;
2484 }
2485
2486 private void scanDirLI(File dir, int flags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002488 if (files == null) {
2489 Log.d(TAG, "No files in app dir " + dir);
2490 return;
2491 }
2492
2493 Log.d(TAG, "Scanning app dir " + dir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494
2495 int i;
2496 for (i=0; i<files.length; i++) {
2497 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002498 if (!isPackageFilename(files[i])) {
2499 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002500 continue;
2501 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002502 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002504 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002505 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2506 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002507 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002508 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002509 file.delete();
2510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 }
2512 }
2513
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002514 private static File getSettingsProblemFile() {
2515 File dataDir = Environment.getDataDirectory();
2516 File systemDir = new File(dataDir, "system");
2517 File fname = new File(systemDir, "uiderrors.txt");
2518 return fname;
2519 }
2520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 private static void reportSettingsProblem(int priority, String msg) {
2522 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002523 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 FileOutputStream out = new FileOutputStream(fname, true);
2525 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002526 SimpleDateFormat formatter = new SimpleDateFormat();
2527 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2528 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 pw.close();
2530 FileUtils.setPermissions(
2531 fname.toString(),
2532 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2533 -1, -1);
2534 } catch (java.io.IOException e) {
2535 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002536 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 }
2538
2539 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2540 PackageParser.Package pkg, File srcFile, int parseFlags) {
2541 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002542 if (ps != null
2543 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002544 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002545 if (ps.signatures.mSignatures != null
2546 && ps.signatures.mSignatures.length != 0) {
2547 // Optimization: reuse the existing cached certificates
2548 // if the package appears to be unchanged.
2549 pkg.mSignatures = ps.signatures.mSignatures;
2550 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 }
Jeff Browne7600722010-04-07 18:28:23 -07002552
2553 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002554 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002555 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2556 }
2557
2558 if (!pp.collectCertificates(pkg, parseFlags)) {
2559 mLastScanError = pp.getParseError();
2560 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 }
2562 }
2563 return true;
2564 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 /*
2567 * Scan a package and return the newly parsed package.
2568 * Returns null in case of errors and the error code is stored in mLastScanError
2569 */
2570 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002571 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002573 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002575 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002578 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 if (pkg == null) {
2580 mLastScanError = pp.getParseError();
2581 return null;
2582 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002583 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 PackageSetting updatedPkg;
2585 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002586 // Look to see if we already know about this package.
2587 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002588 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002589 // This package has been renamed to its original name. Let's
2590 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002591 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002592 }
2593 // If there was no original package, see one for the real package name.
2594 if (ps == null) {
2595 ps = mSettings.peekPackageLP(pkg.packageName);
2596 }
2597 // Check to see if this package could be hiding/updating a system
2598 // package. Must look for it either under the original or real
2599 // package name depending on our state.
2600 updatedPkg = mSettings.mDisabledSysPackages.get(
2601 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002603 // First check if this is a system package that may involve an update
2604 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002605 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002606 // The path has changed from what was last scanned... check the
2607 // version of the new path against what we have stored to determine
2608 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002609 if (pkg.mVersionCode < ps.versionCode) {
2610 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002611 // Ignore entry. Skip it.
2612 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002613 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002614 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002615 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2616 return null;
2617 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002618 // The current app on the system partion is better than
2619 // what we have updated to on the data partition; switch
2620 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002621 // At this point, its safely assumed that package installation for
2622 // apps in system partition will go through. If not there won't be a working
2623 // version of the app
2624 synchronized (mPackages) {
2625 // Just remove the loaded entries from package lists.
2626 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002627 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002628 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002629 + "reverting from " + ps.codePathString
2630 + ": new version " + pkg.mVersionCode
2631 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002632 InstallArgs args = new FileInstallArgs(ps.codePathString,
2633 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002634 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002635 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 }
2638 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002639 if (updatedPkg != null) {
2640 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2641 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2642 }
2643 // Verify certificates against what was last scanned
2644 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002645 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002646 return null;
2647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 // The apk is forward locked (not public) if its code and resources
2649 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002650 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002652 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002653 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002654
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002655 String codePath = null;
2656 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002657 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2658 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002659 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002660 } else {
2661 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002662 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002663 }
2664 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002665 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002666 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002667 codePath = pkg.mScanPath;
2668 // Set application objects path explicitly.
2669 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002671 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 }
2673
Kenny Root85387d72010-08-26 10:13:11 -07002674 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2675 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002676 pkg.mPath = pkg.mScanPath = destCodePath;
2677 pkg.applicationInfo.sourceDir = destCodePath;
2678 pkg.applicationInfo.publicSourceDir = destResPath;
2679 }
2680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 private static String fixProcessName(String defProcessName,
2682 String processName, int uid) {
2683 if (processName == null) {
2684 return defProcessName;
2685 }
2686 return processName;
2687 }
2688
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002689 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002690 PackageParser.Package pkg) {
2691 if (pkgSetting.signatures.mSignatures != null) {
2692 // Already existing package. Make sure signatures match
2693 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2694 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002695 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002696 + " signatures do not match the previously installed version; ignoring!");
2697 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 return false;
2699 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002700 }
2701 // Check for shared user signatures
2702 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2703 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2704 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2705 Slog.e(TAG, "Package " + pkg.packageName
2706 + " has no signatures that match those in shared user "
2707 + pkgSetting.sharedUser.name + "; ignoring!");
2708 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2709 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 }
2712 return true;
2713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002714
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002715 public boolean performDexOpt(String packageName) {
2716 if (!mNoDexOpt) {
2717 return false;
2718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002719
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002720 PackageParser.Package p;
2721 synchronized (mPackages) {
2722 p = mPackages.get(packageName);
2723 if (p == null || p.mDidDexOpt) {
2724 return false;
2725 }
2726 }
2727 synchronized (mInstallLock) {
2728 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2729 }
2730 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002731
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002732 static final int DEX_OPT_SKIPPED = 0;
2733 static final int DEX_OPT_PERFORMED = 1;
2734 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002735
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002736 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2737 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002738 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002739 String path = pkg.mScanPath;
2740 int ret = 0;
2741 try {
2742 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002743 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002744 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002745 pkg.mDidDexOpt = true;
2746 performed = true;
2747 }
2748 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002749 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002750 ret = -1;
2751 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002752 Slog.w(TAG, "IOException reading apk: " + path, e);
2753 ret = -1;
2754 } catch (dalvik.system.StaleDexCacheError e) {
2755 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2756 ret = -1;
2757 } catch (Exception e) {
2758 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002759 ret = -1;
2760 }
2761 if (ret < 0) {
2762 //error from installer
2763 return DEX_OPT_FAILED;
2764 }
2765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002766
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002767 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2768 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002769
2770 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2771 return Environment.isEncryptedFilesystemEnabled() &&
2772 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2773 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002774
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002775 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2776 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002777 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002778 + " to " + newPkg.packageName
2779 + ": old package not in system partition");
2780 return false;
2781 } else if (mPackages.get(oldPkg.name) != null) {
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 still exists");
2785 return false;
2786 }
2787 return true;
2788 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002789
2790 private File getDataPathForPackage(PackageParser.Package pkg) {
2791 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2792 File dataPath;
2793 if (useEncryptedFSDir) {
2794 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2795 } else {
2796 dataPath = new File(mAppDataDir, pkg.packageName);
2797 }
2798 return dataPath;
2799 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002800
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002801 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2802 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002803 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002804 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2805 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002806 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002807 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002808 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2809 return null;
2810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 mScanningPath = scanFile;
2812 if (pkg == null) {
2813 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2814 return null;
2815 }
2816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2818 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2819 }
2820
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002821 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 synchronized (mPackages) {
2823 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002824 Slog.w(TAG, "*************************************************");
2825 Slog.w(TAG, "Core android package being redefined. Skipping.");
2826 Slog.w(TAG, " file=" + mScanningPath);
2827 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2829 return null;
2830 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 // Set up information for our fall-back user intent resolution
2833 // activity.
2834 mPlatformPackage = pkg;
2835 pkg.mVersionCode = mSdkVersion;
2836 mAndroidApplication = pkg.applicationInfo;
2837 mResolveActivity.applicationInfo = mAndroidApplication;
2838 mResolveActivity.name = ResolverActivity.class.getName();
2839 mResolveActivity.packageName = mAndroidApplication.packageName;
2840 mResolveActivity.processName = mAndroidApplication.processName;
2841 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2842 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2843 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2844 mResolveActivity.exported = true;
2845 mResolveActivity.enabled = true;
2846 mResolveInfo.activityInfo = mResolveActivity;
2847 mResolveInfo.priority = 0;
2848 mResolveInfo.preferredOrder = 0;
2849 mResolveInfo.match = 0;
2850 mResolveComponentName = new ComponentName(
2851 mAndroidApplication.packageName, mResolveActivity.name);
2852 }
2853 }
2854
2855 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002856 TAG, "Scanning package " + pkg.packageName);
2857 if (mPackages.containsKey(pkg.packageName)
2858 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002859 Slog.w(TAG, "*************************************************");
2860 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002862 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2864 return null;
2865 }
2866
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002867 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002868 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2869 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871 SharedUserSetting suid = null;
2872 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002873
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002874 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2875 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002876 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002877 pkg.mRealPackage = null;
2878 pkg.mAdoptPermissions = null;
2879 }
2880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 synchronized (mPackages) {
2882 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002883 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2884 if (mTmpSharedLibraries == null ||
2885 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2886 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2887 }
2888 int num = 0;
2889 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2890 for (int i=0; i<N; i++) {
2891 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002893 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002895 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2897 return null;
2898 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002899 mTmpSharedLibraries[num] = file;
2900 num++;
2901 }
2902 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2903 for (int i=0; i<N; i++) {
2904 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2905 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002906 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002907 + " desires unavailable shared library "
2908 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2909 } else {
2910 mTmpSharedLibraries[num] = file;
2911 num++;
2912 }
2913 }
2914 if (num > 0) {
2915 pkg.usesLibraryFiles = new String[num];
2916 System.arraycopy(mTmpSharedLibraries, 0,
2917 pkg.usesLibraryFiles, 0, num);
2918 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002919
Dianne Hackborn49237342009-08-27 20:08:01 -07002920 if (pkg.reqFeatures != null) {
2921 N = pkg.reqFeatures.size();
2922 for (int i=0; i<N; i++) {
2923 FeatureInfo fi = pkg.reqFeatures.get(i);
2924 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2925 // Don't care.
2926 continue;
2927 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002928
Dianne Hackborn49237342009-08-27 20:08:01 -07002929 if (fi.name != null) {
2930 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002931 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002932 + " requires unavailable feature "
2933 + fi.name + "; failing!");
2934 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2935 return null;
2936 }
2937 }
2938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 }
2940 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 if (pkg.mSharedUserId != null) {
2943 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2944 pkg.applicationInfo.flags, true);
2945 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002946 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 + " for shared user failed");
2948 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2949 return null;
2950 }
2951 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2952 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2953 + suid.userId + "): packages=" + suid.packages);
2954 }
2955 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002956
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002957 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002958 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002959 Log.w(TAG, "WAITING FOR DEBUGGER");
2960 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002961 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2962 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002963 }
2964 }
2965
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002966 // Check if we are renaming from an original package name.
2967 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002968 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002969 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002970 // This package may need to be renamed to a previously
2971 // installed name. Let's check on that...
2972 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002973 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002974 // This package had originally been installed as the
2975 // original name, and we have already taken care of
2976 // transitioning to the new one. Just update the new
2977 // one to continue using the old name.
2978 realName = pkg.mRealPackage;
2979 if (!pkg.packageName.equals(renamed)) {
2980 // Callers into this function may have already taken
2981 // care of renaming the package; only do it here if
2982 // it is not already done.
2983 pkg.setPackageName(renamed);
2984 }
2985
Dianne Hackbornc1552392010-03-03 16:19:01 -08002986 } else {
2987 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2988 if ((origPackage=mSettings.peekPackageLP(
2989 pkg.mOriginalPackages.get(i))) != null) {
2990 // We do have the package already installed under its
2991 // original name... should we use it?
2992 if (!verifyPackageUpdate(origPackage, pkg)) {
2993 // New package is not compatible with original.
2994 origPackage = null;
2995 continue;
2996 } else if (origPackage.sharedUser != null) {
2997 // Make sure uid is compatible between packages.
2998 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002999 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003000 + " to " + pkg.packageName + ": old uid "
3001 + origPackage.sharedUser.name
3002 + " differs from " + pkg.mSharedUserId);
3003 origPackage = null;
3004 continue;
3005 }
3006 } else {
3007 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3008 + pkg.packageName + " to old name " + origPackage.name);
3009 }
3010 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003011 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003012 }
3013 }
3014 }
3015
3016 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003017 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003018 + " was transferred to another, but its .apk remains");
3019 }
3020
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003021 // Just create the setting, don't add it yet. For already existing packages
3022 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003023 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003024 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3025 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003027 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3029 return null;
3030 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003031
3032 if (pkgSetting.origPackage != null) {
3033 // If we are first transitioning from an original package,
3034 // fix up the new package's name now. We need to do this after
3035 // looking up the package under its new name, so getPackageLP
3036 // can take care of fiddling things correctly.
3037 pkg.setPackageName(origPackage.name);
3038
3039 // File a report about this.
3040 String msg = "New package " + pkgSetting.realName
3041 + " renamed to replace old package " + pkgSetting.name;
3042 reportSettingsProblem(Log.WARN, msg);
3043
3044 // Make a note of it.
3045 mTransferedPackages.add(origPackage.name);
3046
3047 // No longer need to retain this.
3048 pkgSetting.origPackage = null;
3049 }
3050
3051 if (realName != null) {
3052 // Make a note of it.
3053 mTransferedPackages.add(pkg.packageName);
3054 }
3055
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003056 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3058 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 pkg.applicationInfo.uid = pkgSetting.userId;
3061 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003062
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003063 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003064 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 return null;
3066 }
3067 // The signature has changed, but this package is in the system
3068 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003069 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 // However... if this package is part of a shared user, but it
3071 // doesn't match the signature of the shared user, let's fail.
3072 // What this means is that you can't change the signatures
3073 // associated with an overall shared user, which doesn't seem all
3074 // that unreasonable.
3075 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003076 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3077 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3078 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3080 return null;
3081 }
3082 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003083 // File a report about this.
3084 String msg = "System package " + pkg.packageName
3085 + " signature changed; retaining data.";
3086 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003088
The Android Open Source Project10592532009-03-18 17:39:46 -07003089 // Verify that this new package doesn't have any content providers
3090 // that conflict with existing packages. Only do this if the
3091 // package isn't already installed, since we don't want to break
3092 // things that are installed.
3093 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3094 int N = pkg.providers.size();
3095 int i;
3096 for (i=0; i<N; i++) {
3097 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003098 if (p.info.authority != null) {
3099 String names[] = p.info.authority.split(";");
3100 for (int j = 0; j < names.length; j++) {
3101 if (mProviders.containsKey(names[j])) {
3102 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003103 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003104 " (in package " + pkg.applicationInfo.packageName +
3105 ") is already used by "
3106 + ((other != null && other.getComponentName() != null)
3107 ? other.getComponentName().getPackageName() : "?"));
3108 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3109 return null;
3110 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003111 }
3112 }
3113 }
3114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 }
3116
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003117 final String pkgName = pkg.packageName;
3118
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003119 if (pkg.mAdoptPermissions != null) {
3120 // This package wants to adopt ownership of permissions from
3121 // another package.
3122 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3123 String origName = pkg.mAdoptPermissions.get(i);
3124 PackageSetting orig = mSettings.peekPackageLP(origName);
3125 if (orig != null) {
3126 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003127 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003128 + origName + " to " + pkg.packageName);
3129 mSettings.transferPermissions(origName, pkg.packageName);
3130 }
3131 }
3132 }
3133 }
3134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 long scanFileTime = scanFile.lastModified();
3136 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003137 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 pkg.applicationInfo.processName = fixProcessName(
3139 pkg.applicationInfo.packageName,
3140 pkg.applicationInfo.processName,
3141 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142
3143 File dataPath;
3144 if (mPlatformPackage == pkg) {
3145 // The system package is special.
3146 dataPath = new File (Environment.getDataDirectory(), "system");
3147 pkg.applicationInfo.dataDir = dataPath.getPath();
3148 } else {
3149 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003150 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003151 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003152
3153 boolean uidError = false;
3154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 if (dataPath.exists()) {
3156 mOutPermissions[1] = 0;
3157 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003158
3159 // If we have mismatched owners for the data path, we have a
3160 // problem (unless we're running in the simulator.)
3161 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 boolean recovered = false;
3163 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3164 // If this is a system app, we can at least delete its
3165 // current data so the application will still work.
3166 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003167 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003168 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 // Old data gone!
3170 String msg = "System package " + pkg.packageName
3171 + " has changed from uid: "
3172 + mOutPermissions[1] + " to "
3173 + pkg.applicationInfo.uid + "; old data erased";
3174 reportSettingsProblem(Log.WARN, msg);
3175 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003178 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 pkg.applicationInfo.uid);
3180 if (ret == -1) {
3181 // Ack should not happen!
3182 msg = "System package " + pkg.packageName
3183 + " could not have data directory re-created after delete.";
3184 reportSettingsProblem(Log.WARN, msg);
3185 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3186 return null;
3187 }
3188 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 if (!recovered) {
3191 mHasSystemUidErrors = true;
3192 }
3193 }
3194 if (!recovered) {
3195 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3196 + pkg.applicationInfo.uid + "/fs_"
3197 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003198 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 String msg = "Package " + pkg.packageName
3200 + " has mismatched uid: "
3201 + mOutPermissions[1] + " on disk, "
3202 + pkg.applicationInfo.uid + " in settings";
3203 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003204 mSettings.mReadMessages.append(msg);
3205 mSettings.mReadMessages.append('\n');
3206 uidError = true;
3207 if (!pkgSetting.uidError) {
3208 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 }
3211 }
3212 }
3213 pkg.applicationInfo.dataDir = dataPath.getPath();
3214 } else {
3215 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3216 Log.v(TAG, "Want this data dir: " + dataPath);
3217 //invoke installer to do the actual installation
3218 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003219 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 pkg.applicationInfo.uid);
3221 if(ret < 0) {
3222 // Error from installer
3223 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3224 return null;
3225 }
3226 } else {
3227 dataPath.mkdirs();
3228 if (dataPath.exists()) {
3229 FileUtils.setPermissions(
3230 dataPath.toString(),
3231 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3232 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3233 }
3234 }
3235 if (dataPath.exists()) {
3236 pkg.applicationInfo.dataDir = dataPath.getPath();
3237 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003238 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 pkg.applicationInfo.dataDir = null;
3240 }
3241 }
Kenny Root85387d72010-08-26 10:13:11 -07003242
3243 /*
3244 * Set the data dir to the default "/data/data/<package name>/lib"
3245 * if we got here without anyone telling us different (e.g., apps
3246 * stored on SD card have their native libraries stored in the ASEC
3247 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003248 *
3249 * This happens during an upgrade from a package settings file that
3250 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003251 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003252 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3253 if (pkgSetting.nativeLibraryPathString == null) {
3254 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3255 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3256 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3257 } else {
3258 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3259 }
Kenny Root85387d72010-08-26 10:13:11 -07003260 }
3261
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003262 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 }
3264
Kenny Root85387d72010-08-26 10:13:11 -07003265 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 if (mInstaller != null) {
3267 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003268 /* Note: We don't want to unpack the native binaries for
3269 * system applications, unless they have been updated
3270 * (the binaries are already under /system/lib).
3271 * Also, don't unpack libs for apps on the external card
3272 * since they should have their libraries in the ASEC
3273 * container already.
3274 *
3275 * In other words, we're going to unpack the binaries
3276 * only for non-system apps and system app upgrades.
3277 */
Kenny Root831baa22010-10-05 12:29:25 -07003278 if (pkg.applicationInfo.nativeLibraryDir != null) {
3279 final File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3280 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3281 /*
3282 * Upgrading from a previous version of the OS sometimes
3283 * leaves native libraries in the /data/data/<app>/lib
3284 * directory for system apps even when they shouldn't be.
3285 * Recent changes in the JNI library search path
3286 * necessitates we remove those to match previous behavior.
3287 */
3288 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(sharedLibraryDir)) {
3289 Log.i(TAG, "removed obsolete native libraries for system package " + path);
3290 }
3291 } else if (!isExternal(pkg)) {
3292 Log.i(TAG, path + " changed; unpacking");
3293 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
3294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003296 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003297
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003298 if ((scanMode&SCAN_NO_DEX) == 0) {
3299 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3301 return null;
3302 }
3303 }
3304 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 if (mFactoryTest && pkg.requestedPermissions.contains(
3307 android.Manifest.permission.FACTORY_TEST)) {
3308 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3309 }
3310
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003311 // Request the ActivityManager to kill the process(only for existing packages)
3312 // so that we do not end up in a confused state while the user is still using the older
3313 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003314 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003315 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003316 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003317 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003320 // We don't expect installation to fail beyond this point,
3321 if ((scanMode&SCAN_MONITOR) != 0) {
3322 mAppDirs.put(pkg.mPath, pkg);
3323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003325 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003327 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003328 // Make sure we don't accidentally delete its data.
3329 mSettings.mPackagesToBeCleaned.remove(pkgName);
3330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 int N = pkg.providers.size();
3332 StringBuilder r = null;
3333 int i;
3334 for (i=0; i<N; i++) {
3335 PackageParser.Provider p = pkg.providers.get(i);
3336 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3337 p.info.processName, pkg.applicationInfo.uid);
3338 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3339 p.info.name), p);
3340 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003341 if (p.info.authority != null) {
3342 String names[] = p.info.authority.split(";");
3343 p.info.authority = null;
3344 for (int j = 0; j < names.length; j++) {
3345 if (j == 1 && p.syncable) {
3346 // We only want the first authority for a provider to possibly be
3347 // syncable, so if we already added this provider using a different
3348 // authority clear the syncable flag. We copy the provider before
3349 // changing it because the mProviders object contains a reference
3350 // to a provider that we don't want to change.
3351 // Only do this for the second authority since the resulting provider
3352 // object can be the same for all future authorities for this provider.
3353 p = new PackageParser.Provider(p);
3354 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003356 if (!mProviders.containsKey(names[j])) {
3357 mProviders.put(names[j], p);
3358 if (p.info.authority == null) {
3359 p.info.authority = names[j];
3360 } else {
3361 p.info.authority = p.info.authority + ";" + names[j];
3362 }
3363 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3364 Log.d(TAG, "Registered content provider: " + names[j] +
3365 ", className = " + p.info.name +
3366 ", isSyncable = " + p.info.isSyncable);
3367 } else {
3368 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003369 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003370 " (in package " + pkg.applicationInfo.packageName +
3371 "): name already used by "
3372 + ((other != null && other.getComponentName() != null)
3373 ? other.getComponentName().getPackageName() : "?"));
3374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 }
3376 }
3377 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3378 if (r == null) {
3379 r = new StringBuilder(256);
3380 } else {
3381 r.append(' ');
3382 }
3383 r.append(p.info.name);
3384 }
3385 }
3386 if (r != null) {
3387 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3388 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 N = pkg.services.size();
3391 r = null;
3392 for (i=0; i<N; i++) {
3393 PackageParser.Service s = pkg.services.get(i);
3394 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3395 s.info.processName, pkg.applicationInfo.uid);
3396 mServices.addService(s);
3397 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3398 if (r == null) {
3399 r = new StringBuilder(256);
3400 } else {
3401 r.append(' ');
3402 }
3403 r.append(s.info.name);
3404 }
3405 }
3406 if (r != null) {
3407 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3408 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 N = pkg.receivers.size();
3411 r = null;
3412 for (i=0; i<N; i++) {
3413 PackageParser.Activity a = pkg.receivers.get(i);
3414 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3415 a.info.processName, pkg.applicationInfo.uid);
3416 mReceivers.addActivity(a, "receiver");
3417 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3418 if (r == null) {
3419 r = new StringBuilder(256);
3420 } else {
3421 r.append(' ');
3422 }
3423 r.append(a.info.name);
3424 }
3425 }
3426 if (r != null) {
3427 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3428 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 N = pkg.activities.size();
3431 r = null;
3432 for (i=0; i<N; i++) {
3433 PackageParser.Activity a = pkg.activities.get(i);
3434 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3435 a.info.processName, pkg.applicationInfo.uid);
3436 mActivities.addActivity(a, "activity");
3437 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3438 if (r == null) {
3439 r = new StringBuilder(256);
3440 } else {
3441 r.append(' ');
3442 }
3443 r.append(a.info.name);
3444 }
3445 }
3446 if (r != null) {
3447 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3448 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 N = pkg.permissionGroups.size();
3451 r = null;
3452 for (i=0; i<N; i++) {
3453 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3454 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3455 if (cur == null) {
3456 mPermissionGroups.put(pg.info.name, pg);
3457 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3458 if (r == null) {
3459 r = new StringBuilder(256);
3460 } else {
3461 r.append(' ');
3462 }
3463 r.append(pg.info.name);
3464 }
3465 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003466 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 + pg.info.packageName + " ignored: original from "
3468 + cur.info.packageName);
3469 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3470 if (r == null) {
3471 r = new StringBuilder(256);
3472 } else {
3473 r.append(' ');
3474 }
3475 r.append("DUP:");
3476 r.append(pg.info.name);
3477 }
3478 }
3479 }
3480 if (r != null) {
3481 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3482 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 N = pkg.permissions.size();
3485 r = null;
3486 for (i=0; i<N; i++) {
3487 PackageParser.Permission p = pkg.permissions.get(i);
3488 HashMap<String, BasePermission> permissionMap =
3489 p.tree ? mSettings.mPermissionTrees
3490 : mSettings.mPermissions;
3491 p.group = mPermissionGroups.get(p.info.group);
3492 if (p.info.group == null || p.group != null) {
3493 BasePermission bp = permissionMap.get(p.info.name);
3494 if (bp == null) {
3495 bp = new BasePermission(p.info.name, p.info.packageName,
3496 BasePermission.TYPE_NORMAL);
3497 permissionMap.put(p.info.name, bp);
3498 }
3499 if (bp.perm == null) {
3500 if (bp.sourcePackage == null
3501 || bp.sourcePackage.equals(p.info.packageName)) {
3502 BasePermission tree = findPermissionTreeLP(p.info.name);
3503 if (tree == null
3504 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003505 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 bp.perm = p;
3507 bp.uid = pkg.applicationInfo.uid;
3508 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3509 if (r == null) {
3510 r = new StringBuilder(256);
3511 } else {
3512 r.append(' ');
3513 }
3514 r.append(p.info.name);
3515 }
3516 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003517 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 + p.info.packageName + " ignored: base tree "
3519 + tree.name + " is from package "
3520 + tree.sourcePackage);
3521 }
3522 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003523 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 + p.info.packageName + " ignored: original from "
3525 + bp.sourcePackage);
3526 }
3527 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3528 if (r == null) {
3529 r = new StringBuilder(256);
3530 } else {
3531 r.append(' ');
3532 }
3533 r.append("DUP:");
3534 r.append(p.info.name);
3535 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003536 if (bp.perm == p) {
3537 bp.protectionLevel = p.info.protectionLevel;
3538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003540 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 + p.info.packageName + " ignored: no group "
3542 + p.group);
3543 }
3544 }
3545 if (r != null) {
3546 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3547 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 N = pkg.instrumentation.size();
3550 r = null;
3551 for (i=0; i<N; i++) {
3552 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3553 a.info.packageName = pkg.applicationInfo.packageName;
3554 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3555 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3556 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003557 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003558 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003559 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3560 if (r == null) {
3561 r = new StringBuilder(256);
3562 } else {
3563 r.append(' ');
3564 }
3565 r.append(a.info.name);
3566 }
3567 }
3568 if (r != null) {
3569 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3570 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003571
Dianne Hackborn854060af2009-07-09 18:14:31 -07003572 if (pkg.protectedBroadcasts != null) {
3573 N = pkg.protectedBroadcasts.size();
3574 for (i=0; i<N; i++) {
3575 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3576 }
3577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 pkgSetting.setTimeStamp(scanFileTime);
3580 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 return pkg;
3583 }
3584
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003585 private void killApplication(String pkgName, int uid) {
3586 // Request the ActivityManager to kill the process(only for existing packages)
3587 // so that we do not end up in a confused state while the user is still using the older
3588 // version of the application while the new one gets installed.
3589 IActivityManager am = ActivityManagerNative.getDefault();
3590 if (am != null) {
3591 try {
3592 am.killApplicationWithUid(pkgName, uid);
3593 } catch (RemoteException e) {
3594 }
3595 }
3596 }
3597
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003598 // Return the path of the directory that will contain the native binaries
3599 // of a given installed package. This is relative to the data path.
3600 //
Kenny Root85387d72010-08-26 10:13:11 -07003601 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3602 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3603 if (nativeLibraryDir != null) {
3604 return new File(nativeLibraryDir);
3605 } else {
3606 // Fall back for old packages
3607 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3608 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003609 }
3610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3612 if (chatty && Config.LOGD) Log.d(
3613 TAG, "Removing package " + pkg.applicationInfo.packageName );
3614
3615 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003616 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 mPackages.remove(pkg.applicationInfo.packageName);
3619 if (pkg.mPath != null) {
3620 mAppDirs.remove(pkg.mPath);
3621 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 PackageSetting ps = (PackageSetting)pkg.mExtras;
3624 if (ps != null && ps.sharedUser != null) {
3625 // XXX don't do this until the data is removed.
3626 if (false) {
3627 ps.sharedUser.packages.remove(ps);
3628 if (ps.sharedUser.packages.size() == 0) {
3629 // Remove.
3630 }
3631 }
3632 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 int N = pkg.providers.size();
3635 StringBuilder r = null;
3636 int i;
3637 for (i=0; i<N; i++) {
3638 PackageParser.Provider p = pkg.providers.get(i);
3639 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3640 p.info.name));
3641 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 /* The is another ContentProvider with this authority when
3644 * this app was installed so this authority is null,
3645 * Ignore it as we don't have to unregister the provider.
3646 */
3647 continue;
3648 }
3649 String names[] = p.info.authority.split(";");
3650 for (int j = 0; j < names.length; j++) {
3651 if (mProviders.get(names[j]) == p) {
3652 mProviders.remove(names[j]);
3653 if (chatty && Config.LOGD) Log.d(
3654 TAG, "Unregistered content provider: " + names[j] +
3655 ", className = " + p.info.name +
3656 ", isSyncable = " + p.info.isSyncable);
3657 }
3658 }
3659 if (chatty) {
3660 if (r == null) {
3661 r = new StringBuilder(256);
3662 } else {
3663 r.append(' ');
3664 }
3665 r.append(p.info.name);
3666 }
3667 }
3668 if (r != null) {
3669 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3670 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 N = pkg.services.size();
3673 r = null;
3674 for (i=0; i<N; i++) {
3675 PackageParser.Service s = pkg.services.get(i);
3676 mServices.removeService(s);
3677 if (chatty) {
3678 if (r == null) {
3679 r = new StringBuilder(256);
3680 } else {
3681 r.append(' ');
3682 }
3683 r.append(s.info.name);
3684 }
3685 }
3686 if (r != null) {
3687 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3688 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003690 N = pkg.receivers.size();
3691 r = null;
3692 for (i=0; i<N; i++) {
3693 PackageParser.Activity a = pkg.receivers.get(i);
3694 mReceivers.removeActivity(a, "receiver");
3695 if (chatty) {
3696 if (r == null) {
3697 r = new StringBuilder(256);
3698 } else {
3699 r.append(' ');
3700 }
3701 r.append(a.info.name);
3702 }
3703 }
3704 if (r != null) {
3705 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3706 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 N = pkg.activities.size();
3709 r = null;
3710 for (i=0; i<N; i++) {
3711 PackageParser.Activity a = pkg.activities.get(i);
3712 mActivities.removeActivity(a, "activity");
3713 if (chatty) {
3714 if (r == null) {
3715 r = new StringBuilder(256);
3716 } else {
3717 r.append(' ');
3718 }
3719 r.append(a.info.name);
3720 }
3721 }
3722 if (r != null) {
3723 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3724 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 N = pkg.permissions.size();
3727 r = null;
3728 for (i=0; i<N; i++) {
3729 PackageParser.Permission p = pkg.permissions.get(i);
3730 boolean tree = false;
3731 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3732 if (bp == null) {
3733 tree = true;
3734 bp = mSettings.mPermissionTrees.get(p.info.name);
3735 }
3736 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003737 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 if (chatty) {
3739 if (r == null) {
3740 r = new StringBuilder(256);
3741 } else {
3742 r.append(' ');
3743 }
3744 r.append(p.info.name);
3745 }
3746 }
3747 }
3748 if (r != null) {
3749 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3750 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 N = pkg.instrumentation.size();
3753 r = null;
3754 for (i=0; i<N; i++) {
3755 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003756 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 if (chatty) {
3758 if (r == null) {
3759 r = new StringBuilder(256);
3760 } else {
3761 r.append(' ');
3762 }
3763 r.append(a.info.name);
3764 }
3765 }
3766 if (r != null) {
3767 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3768 }
3769 }
3770 }
3771
3772 private static final boolean isPackageFilename(String name) {
3773 return name != null && name.endsWith(".apk");
3774 }
3775
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003776 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3777 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3778 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3779 return true;
3780 }
3781 }
3782 return false;
3783 }
3784
3785 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003786 PackageParser.Package pkgInfo, boolean grantPermissions,
3787 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 // Make sure there are no dangling permission trees.
3789 Iterator<BasePermission> it = mSettings.mPermissionTrees
3790 .values().iterator();
3791 while (it.hasNext()) {
3792 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003793 if (bp.packageSetting == null) {
3794 // We may not yet have parsed the package, so just see if
3795 // we still know about its settings.
3796 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3797 }
3798 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003799 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800 + " from package " + bp.sourcePackage);
3801 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003802 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3803 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3804 Slog.i(TAG, "Removing old permission tree: " + bp.name
3805 + " from package " + bp.sourcePackage);
3806 grantPermissions = true;
3807 it.remove();
3808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 }
3810 }
3811
3812 // Make sure all dynamic permissions have been assigned to a package,
3813 // and make sure there are no dangling permissions.
3814 it = mSettings.mPermissions.values().iterator();
3815 while (it.hasNext()) {
3816 BasePermission bp = it.next();
3817 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3818 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3819 + bp.name + " pkg=" + bp.sourcePackage
3820 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003821 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822 BasePermission tree = findPermissionTreeLP(bp.name);
3823 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003824 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 bp.perm = new PackageParser.Permission(tree.perm.owner,
3826 new PermissionInfo(bp.pendingInfo));
3827 bp.perm.info.packageName = tree.perm.info.packageName;
3828 bp.perm.info.name = bp.name;
3829 bp.uid = tree.uid;
3830 }
3831 }
3832 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003833 if (bp.packageSetting == null) {
3834 // We may not yet have parsed the package, so just see if
3835 // we still know about its settings.
3836 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3837 }
3838 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003839 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003840 + " from package " + bp.sourcePackage);
3841 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003842 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3843 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3844 Slog.i(TAG, "Removing old permission: " + bp.name
3845 + " from package " + bp.sourcePackage);
3846 grantPermissions = true;
3847 it.remove();
3848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 }
3850 }
3851
3852 // Now update the permissions for all packages, in particular
3853 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003854 if (grantPermissions) {
3855 for (PackageParser.Package pkg : mPackages.values()) {
3856 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003857 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003858 }
3859 }
3860 }
3861
3862 if (pkgInfo != null) {
3863 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 }
3865 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3868 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3869 if (ps == null) {
3870 return;
3871 }
3872 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003873 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 if (replace) {
3876 ps.permissionsFixed = false;
3877 if (gp == ps) {
3878 gp.grantedPermissions.clear();
3879 gp.gids = mGlobalGids;
3880 }
3881 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 if (gp.gids == null) {
3884 gp.gids = mGlobalGids;
3885 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887 final int N = pkg.requestedPermissions.size();
3888 for (int i=0; i<N; i++) {
3889 String name = pkg.requestedPermissions.get(i);
3890 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 if (false) {
3892 if (gp != ps) {
3893 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003894 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 }
3896 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003897 if (bp != null && bp.packageSetting != null) {
3898 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003900 boolean allowedSig = false;
3901 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3902 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003904 } else if (bp.packageSetting == null) {
3905 // This permission is invalid; skip it.
3906 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003907 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3908 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3909 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003911 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003913 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003914 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 // For updated system applications, the signatureOrSystem permission
3916 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003917 if (isUpdatedSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3919 if(sysPs.grantedPermissions.contains(perm)) {
3920 allowed = true;
3921 } else {
3922 allowed = false;
3923 }
3924 } else {
3925 allowed = true;
3926 }
3927 }
3928 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003929 if (allowed) {
3930 allowedSig = true;
3931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 } else {
3933 allowed = false;
3934 }
3935 if (false) {
3936 if (gp != ps) {
3937 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3938 }
3939 }
3940 if (allowed) {
3941 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3942 && ps.permissionsFixed) {
3943 // If this is an existing, non-system package, then
3944 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003945 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003947 // Except... if this is a permission that was added
3948 // to the platform (note: need to only do this when
3949 // updating the platform).
3950 final int NP = PackageParser.NEW_PERMISSIONS.length;
3951 for (int ip=0; ip<NP; ip++) {
3952 final PackageParser.NewPermissionInfo npi
3953 = PackageParser.NEW_PERMISSIONS[ip];
3954 if (npi.name.equals(perm)
3955 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3956 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003957 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003958 + pkg.packageName);
3959 break;
3960 }
3961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 }
3963 }
3964 if (allowed) {
3965 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003966 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 gp.grantedPermissions.add(perm);
3968 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003969 } else if (!ps.haveGids) {
3970 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971 }
3972 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003973 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 + " to package " + pkg.packageName
3975 + " because it was previously installed without");
3976 }
3977 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003978 if (gp.grantedPermissions.remove(perm)) {
3979 changedPermission = true;
3980 gp.gids = removeInts(gp.gids, bp.gids);
3981 Slog.i(TAG, "Un-granting permission " + perm
3982 + " from package " + pkg.packageName
3983 + " (protectionLevel=" + bp.protectionLevel
3984 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3985 + ")");
3986 } else {
3987 Slog.w(TAG, "Not granting permission " + perm
3988 + " to package " + pkg.packageName
3989 + " (protectionLevel=" + bp.protectionLevel
3990 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3991 + ")");
3992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 }
3994 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003995 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 + " in package " + pkg.packageName);
3997 }
3998 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003999
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004000 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004001 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4002 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 // This is the first that we have heard about this package, so the
4004 // permissions we have now selected are fixed until explicitly
4005 // changed.
4006 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004008 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 private final class ActivityIntentResolver
4012 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004013 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004015 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 }
4017
Mihai Preda074edef2009-05-18 17:13:31 +02004018 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004020 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4022 }
4023
Mihai Predaeae850c2009-05-13 10:13:48 +02004024 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4025 ArrayList<PackageParser.Activity> packageActivities) {
4026 if (packageActivities == null) {
4027 return null;
4028 }
4029 mFlags = flags;
4030 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4031 int N = packageActivities.size();
4032 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4033 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004034
4035 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004036 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004037 intentFilters = packageActivities.get(i).intents;
4038 if (intentFilters != null && intentFilters.size() > 0) {
4039 listCut.add(intentFilters);
4040 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004041 }
4042 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4043 }
4044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004046 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 if (SHOW_INFO || Config.LOGV) Log.v(
4048 TAG, " " + type + " " +
4049 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4050 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4051 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004052 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4054 if (SHOW_INFO || Config.LOGV) {
4055 Log.v(TAG, " IntentFilter:");
4056 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4057 }
4058 if (!intent.debugCheck()) {
4059 Log.w(TAG, "==> For Activity " + a.info.name);
4060 }
4061 addFilter(intent);
4062 }
4063 }
4064
4065 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004066 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 if (SHOW_INFO || Config.LOGV) Log.v(
4068 TAG, " " + type + " " +
4069 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4070 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4071 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004072 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4074 if (SHOW_INFO || Config.LOGV) {
4075 Log.v(TAG, " IntentFilter:");
4076 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4077 }
4078 removeFilter(intent);
4079 }
4080 }
4081
4082 @Override
4083 protected boolean allowFilterResult(
4084 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4085 ActivityInfo filterAi = filter.activity.info;
4086 for (int i=dest.size()-1; i>=0; i--) {
4087 ActivityInfo destAi = dest.get(i).activityInfo;
4088 if (destAi.name == filterAi.name
4089 && destAi.packageName == filterAi.packageName) {
4090 return false;
4091 }
4092 }
4093 return true;
4094 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004097 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4098 return info.activity.owner.packageName;
4099 }
4100
4101 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4103 int match) {
4104 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4105 return null;
4106 }
4107 final PackageParser.Activity activity = info.activity;
4108 if (mSafeMode && (activity.info.applicationInfo.flags
4109 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4110 return null;
4111 }
4112 final ResolveInfo res = new ResolveInfo();
4113 res.activityInfo = PackageParser.generateActivityInfo(activity,
4114 mFlags);
4115 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4116 res.filter = info;
4117 }
4118 res.priority = info.getPriority();
4119 res.preferredOrder = activity.owner.mPreferredOrder;
4120 //System.out.println("Result: " + res.activityInfo.className +
4121 // " = " + res.priority);
4122 res.match = match;
4123 res.isDefault = info.hasDefault;
4124 res.labelRes = info.labelRes;
4125 res.nonLocalizedLabel = info.nonLocalizedLabel;
4126 res.icon = info.icon;
4127 return res;
4128 }
4129
4130 @Override
4131 protected void sortResults(List<ResolveInfo> results) {
4132 Collections.sort(results, mResolvePrioritySorter);
4133 }
4134
4135 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004136 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004137 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004138 out.print(prefix); out.print(
4139 Integer.toHexString(System.identityHashCode(filter.activity)));
4140 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004141 out.print(filter.activity.getComponentShortName());
4142 out.print(" filter ");
4143 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 }
4145
4146// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4147// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4148// final List<ResolveInfo> retList = Lists.newArrayList();
4149// while (i.hasNext()) {
4150// final ResolveInfo resolveInfo = i.next();
4151// if (isEnabledLP(resolveInfo.activityInfo)) {
4152// retList.add(resolveInfo);
4153// }
4154// }
4155// return retList;
4156// }
4157
4158 // Keys are String (activity class name), values are Activity.
4159 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4160 = new HashMap<ComponentName, PackageParser.Activity>();
4161 private int mFlags;
4162 }
4163
4164 private final class ServiceIntentResolver
4165 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004166 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004168 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 }
4170
Mihai Preda074edef2009-05-18 17:13:31 +02004171 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004173 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4175 }
4176
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004177 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4178 ArrayList<PackageParser.Service> packageServices) {
4179 if (packageServices == null) {
4180 return null;
4181 }
4182 mFlags = flags;
4183 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4184 int N = packageServices.size();
4185 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4186 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4187
4188 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4189 for (int i = 0; i < N; ++i) {
4190 intentFilters = packageServices.get(i).intents;
4191 if (intentFilters != null && intentFilters.size() > 0) {
4192 listCut.add(intentFilters);
4193 }
4194 }
4195 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4196 }
4197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004198 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004199 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 if (SHOW_INFO || Config.LOGV) Log.v(
4201 TAG, " " + (s.info.nonLocalizedLabel != null
4202 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4203 if (SHOW_INFO || Config.LOGV) Log.v(
4204 TAG, " Class=" + s.info.name);
4205 int NI = s.intents.size();
4206 int j;
4207 for (j=0; j<NI; j++) {
4208 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4209 if (SHOW_INFO || Config.LOGV) {
4210 Log.v(TAG, " IntentFilter:");
4211 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4212 }
4213 if (!intent.debugCheck()) {
4214 Log.w(TAG, "==> For Service " + s.info.name);
4215 }
4216 addFilter(intent);
4217 }
4218 }
4219
4220 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004221 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004222 if (SHOW_INFO || Config.LOGV) Log.v(
4223 TAG, " " + (s.info.nonLocalizedLabel != null
4224 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4225 if (SHOW_INFO || Config.LOGV) Log.v(
4226 TAG, " Class=" + s.info.name);
4227 int NI = s.intents.size();
4228 int j;
4229 for (j=0; j<NI; j++) {
4230 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4231 if (SHOW_INFO || Config.LOGV) {
4232 Log.v(TAG, " IntentFilter:");
4233 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4234 }
4235 removeFilter(intent);
4236 }
4237 }
4238
4239 @Override
4240 protected boolean allowFilterResult(
4241 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4242 ServiceInfo filterSi = filter.service.info;
4243 for (int i=dest.size()-1; i>=0; i--) {
4244 ServiceInfo destAi = dest.get(i).serviceInfo;
4245 if (destAi.name == filterSi.name
4246 && destAi.packageName == filterSi.packageName) {
4247 return false;
4248 }
4249 }
4250 return true;
4251 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004253 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004254 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4255 return info.service.owner.packageName;
4256 }
4257
4258 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4260 int match) {
4261 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4262 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4263 return null;
4264 }
4265 final PackageParser.Service service = info.service;
4266 if (mSafeMode && (service.info.applicationInfo.flags
4267 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4268 return null;
4269 }
4270 final ResolveInfo res = new ResolveInfo();
4271 res.serviceInfo = PackageParser.generateServiceInfo(service,
4272 mFlags);
4273 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4274 res.filter = filter;
4275 }
4276 res.priority = info.getPriority();
4277 res.preferredOrder = service.owner.mPreferredOrder;
4278 //System.out.println("Result: " + res.activityInfo.className +
4279 // " = " + res.priority);
4280 res.match = match;
4281 res.isDefault = info.hasDefault;
4282 res.labelRes = info.labelRes;
4283 res.nonLocalizedLabel = info.nonLocalizedLabel;
4284 res.icon = info.icon;
4285 return res;
4286 }
4287
4288 @Override
4289 protected void sortResults(List<ResolveInfo> results) {
4290 Collections.sort(results, mResolvePrioritySorter);
4291 }
4292
4293 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004294 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004296 out.print(prefix); out.print(
4297 Integer.toHexString(System.identityHashCode(filter.service)));
4298 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004299 out.print(filter.service.getComponentShortName());
4300 out.print(" filter ");
4301 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 }
4303
4304// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4305// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4306// final List<ResolveInfo> retList = Lists.newArrayList();
4307// while (i.hasNext()) {
4308// final ResolveInfo resolveInfo = (ResolveInfo) i;
4309// if (isEnabledLP(resolveInfo.serviceInfo)) {
4310// retList.add(resolveInfo);
4311// }
4312// }
4313// return retList;
4314// }
4315
4316 // Keys are String (activity class name), values are Activity.
4317 private final HashMap<ComponentName, PackageParser.Service> mServices
4318 = new HashMap<ComponentName, PackageParser.Service>();
4319 private int mFlags;
4320 };
4321
4322 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4323 new Comparator<ResolveInfo>() {
4324 public int compare(ResolveInfo r1, ResolveInfo r2) {
4325 int v1 = r1.priority;
4326 int v2 = r2.priority;
4327 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4328 if (v1 != v2) {
4329 return (v1 > v2) ? -1 : 1;
4330 }
4331 v1 = r1.preferredOrder;
4332 v2 = r2.preferredOrder;
4333 if (v1 != v2) {
4334 return (v1 > v2) ? -1 : 1;
4335 }
4336 if (r1.isDefault != r2.isDefault) {
4337 return r1.isDefault ? -1 : 1;
4338 }
4339 v1 = r1.match;
4340 v2 = r2.match;
4341 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4342 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4343 }
4344 };
4345
4346 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4347 new Comparator<ProviderInfo>() {
4348 public int compare(ProviderInfo p1, ProviderInfo p2) {
4349 final int v1 = p1.initOrder;
4350 final int v2 = p2.initOrder;
4351 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4352 }
4353 };
4354
Kenny Root93565c4b2010-06-18 15:46:06 -07004355 private static final boolean DEBUG_OBB = false;
4356
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004357 private static final void sendPackageBroadcast(String action, String pkg,
4358 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 IActivityManager am = ActivityManagerNative.getDefault();
4360 if (am != null) {
4361 try {
4362 final Intent intent = new Intent(action,
4363 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4364 if (extras != null) {
4365 intent.putExtras(extras);
4366 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004367 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004368 am.broadcastIntent(null, intent, null, finishedReceiver,
4369 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004370 } catch (RemoteException ex) {
4371 }
4372 }
4373 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004374
4375 public String nextPackageToClean(String lastPackage) {
4376 synchronized (mPackages) {
4377 if (!mMediaMounted) {
4378 // If the external storage is no longer mounted at this point,
4379 // the caller may not have been able to delete all of this
4380 // packages files and can not delete any more. Bail.
4381 return null;
4382 }
4383 if (lastPackage != null) {
4384 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4385 }
4386 return mSettings.mPackagesToBeCleaned.size() > 0
4387 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4388 }
4389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004391 void schedulePackageCleaning(String packageName) {
4392 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4393 }
4394
4395 void startCleaningPackages() {
4396 synchronized (mPackages) {
4397 if (!mMediaMounted) {
4398 return;
4399 }
4400 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4401 return;
4402 }
4403 }
4404 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4405 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4406 IActivityManager am = ActivityManagerNative.getDefault();
4407 if (am != null) {
4408 try {
4409 am.startService(null, intent, null);
4410 } catch (RemoteException e) {
4411 }
4412 }
4413 }
4414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004415 private final class AppDirObserver extends FileObserver {
4416 public AppDirObserver(String path, int mask, boolean isrom) {
4417 super(path, mask);
4418 mRootDir = path;
4419 mIsRom = isrom;
4420 }
4421
4422 public void onEvent(int event, String path) {
4423 String removedPackage = null;
4424 int removedUid = -1;
4425 String addedPackage = null;
4426 int addedUid = -1;
4427
4428 synchronized (mInstallLock) {
4429 String fullPathStr = null;
4430 File fullPath = null;
4431 if (path != null) {
4432 fullPath = new File(mRootDir, path);
4433 fullPathStr = fullPath.getPath();
4434 }
4435
4436 if (Config.LOGV) Log.v(
4437 TAG, "File " + fullPathStr + " changed: "
4438 + Integer.toHexString(event));
4439
4440 if (!isPackageFilename(path)) {
4441 if (Config.LOGV) Log.v(
4442 TAG, "Ignoring change of non-package file: " + fullPathStr);
4443 return;
4444 }
4445
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004446 // Ignore packages that are being installed or
4447 // have just been installed.
4448 if (ignoreCodePath(fullPathStr)) {
4449 return;
4450 }
4451 PackageParser.Package p = null;
4452 synchronized (mPackages) {
4453 p = mAppDirs.get(fullPathStr);
4454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004456 if (p != null) {
4457 removePackageLI(p, true);
4458 removedPackage = p.applicationInfo.packageName;
4459 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004460 }
4461 }
4462
4463 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004464 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004465 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004466 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4467 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 PackageParser.PARSE_CHATTY |
4469 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004470 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004471 if (p != null) {
4472 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004473 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004474 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475 }
4476 addedPackage = p.applicationInfo.packageName;
4477 addedUid = p.applicationInfo.uid;
4478 }
4479 }
4480 }
4481
4482 synchronized (mPackages) {
4483 mSettings.writeLP();
4484 }
4485 }
4486
4487 if (removedPackage != null) {
4488 Bundle extras = new Bundle(1);
4489 extras.putInt(Intent.EXTRA_UID, removedUid);
4490 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004491 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4492 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 }
4494 if (addedPackage != null) {
4495 Bundle extras = new Bundle(1);
4496 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004497 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4498 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499 }
4500 }
4501
4502 private final String mRootDir;
4503 private final boolean mIsRom;
4504 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 /* Called when a downloaded package installation has been confirmed by the user */
4507 public void installPackage(
4508 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004509 installPackage(packageURI, observer, flags, null);
4510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004511
Jacek Surazski65e13172009-04-28 15:26:38 +02004512 /* Called when a downloaded package installation has been confirmed by the user */
4513 public void installPackage(
4514 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4515 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 mContext.enforceCallingOrSelfPermission(
4517 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004518
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004519 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004520 msg.obj = new InstallParams(packageURI, observer, flags,
4521 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004522 mHandler.sendMessage(msg);
4523 }
4524
Christopher Tate1bb69062010-02-19 17:02:12 -08004525 public void finishPackageInstall(int token) {
4526 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4527 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4528 mHandler.sendMessage(msg);
4529 }
4530
Kenny Root93565c4b2010-06-18 15:46:06 -07004531 public void setPackageObbPath(String packageName, String path) {
4532 if (DEBUG_OBB)
4533 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4534 PackageSetting pkgSetting;
4535 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004536 final int permission = mContext.checkCallingPermission(
4537 android.Manifest.permission.INSTALL_PACKAGES);
4538 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004539 synchronized (mPackages) {
4540 pkgSetting = mSettings.mPackages.get(packageName);
4541 if (pkgSetting == null) {
4542 throw new IllegalArgumentException("Unknown package: " + packageName);
4543 }
4544 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4545 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4546 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4547 + pkgSetting.userId);
4548 }
4549 pkgSetting.obbPathString = path;
4550 mSettings.writeLP();
4551 }
4552 }
4553
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004554 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004555 // Queue up an async operation since the package installation may take a little while.
4556 mHandler.post(new Runnable() {
4557 public void run() {
4558 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004559 // Result object to be returned
4560 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004561 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004562 res.uid = -1;
4563 res.pkg = null;
4564 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004565 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004566 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004567 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004568 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004569 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004570 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004571 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004572
4573 // A restore should be performed at this point if (a) the install
4574 // succeeded, (b) the operation is not an update, and (c) the new
4575 // package has a backupAgent defined.
4576 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004577 boolean doRestore = (!update
4578 && res.pkg != null
4579 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004580
4581 // Set up the post-install work request bookkeeping. This will be used
4582 // and cleaned up by the post-install event handling regardless of whether
4583 // there's a restore pass performed. Token values are >= 1.
4584 int token;
4585 if (mNextInstallToken < 0) mNextInstallToken = 1;
4586 token = mNextInstallToken++;
4587
4588 PostInstallData data = new PostInstallData(args, res);
4589 mRunningInstalls.put(token, data);
4590 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4591
4592 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4593 // Pass responsibility to the Backup Manager. It will perform a
4594 // restore if appropriate, then pass responsibility back to the
4595 // Package Manager to run the post-install observer callbacks
4596 // and broadcasts.
4597 IBackupManager bm = IBackupManager.Stub.asInterface(
4598 ServiceManager.getService(Context.BACKUP_SERVICE));
4599 if (bm != null) {
4600 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4601 + " to BM for possible restore");
4602 try {
4603 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4604 } catch (RemoteException e) {
4605 // can't happen; the backup manager is local
4606 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004607 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004608 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004609 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004610 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004611 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004612 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004614 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004615
4616 if (!doRestore) {
4617 // No restore possible, or the Backup Manager was mysteriously not
4618 // available -- just fire the post-install work request directly.
4619 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4620 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4621 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004623 }
4624 });
4625 }
4626
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004627 abstract class HandlerParams {
4628 final static int MAX_RETRIES = 4;
4629 int retry = 0;
4630 final void startCopy() {
4631 try {
4632 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4633 retry++;
4634 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004635 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004636 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4637 handleServiceError();
4638 return;
4639 } else {
4640 handleStartCopy();
4641 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4642 mHandler.sendEmptyMessage(MCS_UNBIND);
4643 }
4644 } catch (RemoteException e) {
4645 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4646 mHandler.sendEmptyMessage(MCS_RECONNECT);
4647 }
4648 handleReturnCode();
4649 }
4650
4651 final void serviceError() {
4652 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4653 handleServiceError();
4654 handleReturnCode();
4655 }
4656 abstract void handleStartCopy() throws RemoteException;
4657 abstract void handleServiceError();
4658 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004659 }
4660
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004661 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004662 final IPackageInstallObserver observer;
4663 int flags;
4664 final Uri packageURI;
4665 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004666 private InstallArgs mArgs;
4667 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004668 InstallParams(Uri packageURI,
4669 IPackageInstallObserver observer, int flags,
4670 String installerPackageName) {
4671 this.packageURI = packageURI;
4672 this.flags = flags;
4673 this.observer = observer;
4674 this.installerPackageName = installerPackageName;
4675 }
4676
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004677 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4678 String packageName = pkgLite.packageName;
4679 int installLocation = pkgLite.installLocation;
4680 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4681 synchronized (mPackages) {
4682 PackageParser.Package pkg = mPackages.get(packageName);
4683 if (pkg != null) {
4684 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4685 // Check for updated system application.
4686 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4687 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004688 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004689 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4690 }
4691 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4692 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004693 if (onSd) {
4694 // Install flag overrides everything.
4695 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4696 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004697 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004698 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4699 // Application explicitly specified internal.
4700 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4701 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4702 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004703 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004704 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004705 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004706 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4707 }
4708 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004709 }
4710 }
4711 } else {
4712 // Invalid install. Return error code
4713 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4714 }
4715 }
4716 }
4717 // All the special cases have been taken care of.
4718 // Return result based on recommended install location.
4719 if (onSd) {
4720 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4721 }
4722 return pkgLite.recommendedInstallLocation;
4723 }
4724
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004725 /*
4726 * Invoke remote method to get package information and install
4727 * location values. Override install location based on default
4728 * policy if needed and then create install arguments based
4729 * on the install location.
4730 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004731 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004732 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004733 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4734 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004735 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4736 if (onInt && onSd) {
4737 // Check if both bits are set.
4738 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4739 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4740 } else if (fwdLocked && onSd) {
4741 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004742 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004743 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004744 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004745 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004746 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004747 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004748 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4749 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4750 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4751 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4752 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004753 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4754 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4755 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004756 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4757 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004758 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004759 // Override with defaults if needed.
4760 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004761 if (!onSd && !onInt) {
4762 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004763 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4764 // Set the flag to install on external media.
4765 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004766 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004767 } else {
4768 // Make sure the flag for installing on external
4769 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004770 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004771 flags &= ~PackageManager.INSTALL_EXTERNAL;
4772 }
4773 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004774 }
4775 }
4776 // Create the file args now.
4777 mArgs = createInstallArgs(this);
4778 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4779 // Create copy only if we are not in an erroneous state.
4780 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004781 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004782 }
4783 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004784 }
4785
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004786 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004787 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004788 // If mArgs is null, then MCS couldn't be reached. When it
4789 // reconnects, it will try again to install. At that point, this
4790 // will succeed.
4791 if (mArgs != null) {
4792 processPendingInstall(mArgs, mRet);
4793 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004794 }
4795
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004796 @Override
4797 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004798 mArgs = createInstallArgs(this);
4799 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004800 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004801 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004802
4803 /*
4804 * Utility class used in movePackage api.
4805 * srcArgs and targetArgs are not set for invalid flags and make
4806 * sure to do null checks when invoking methods on them.
4807 * We probably want to return ErrorPrams for both failed installs
4808 * and moves.
4809 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004810 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004811 final IPackageMoveObserver observer;
4812 final int flags;
4813 final String packageName;
4814 final InstallArgs srcArgs;
4815 final InstallArgs targetArgs;
4816 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004817
4818 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4819 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004820 this.srcArgs = srcArgs;
4821 this.observer = observer;
4822 this.flags = flags;
4823 this.packageName = packageName;
4824 if (srcArgs != null) {
4825 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004826 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004827 } else {
4828 targetArgs = null;
4829 }
4830 }
4831
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004832 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004833 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4834 // Check for storage space on target medium
4835 if (!targetArgs.checkFreeStorage(mContainerService)) {
4836 Log.w(TAG, "Insufficient storage to install");
4837 return;
4838 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004839 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004840 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004841 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004842 if (DEBUG_SD_INSTALL) {
4843 StringBuilder builder = new StringBuilder();
4844 if (srcArgs != null) {
4845 builder.append("src: ");
4846 builder.append(srcArgs.getCodePath());
4847 }
4848 if (targetArgs != null) {
4849 builder.append(" target : ");
4850 builder.append(targetArgs.getCodePath());
4851 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004852 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004853 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004854 }
4855
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004856 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004857 void handleReturnCode() {
4858 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004859 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4860 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4861 currentStatus = PackageManager.MOVE_SUCCEEDED;
4862 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4863 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4864 }
4865 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004866 }
4867
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004868 @Override
4869 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004870 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004871 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004872 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004873
4874 private InstallArgs createInstallArgs(InstallParams params) {
4875 if (installOnSd(params.flags)) {
4876 return new SdInstallArgs(params);
4877 } else {
4878 return new FileInstallArgs(params);
4879 }
4880 }
4881
Kenny Root85387d72010-08-26 10:13:11 -07004882 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4883 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004884 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004885 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004886 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004887 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004888 }
4889 }
4890
Kenny Root85387d72010-08-26 10:13:11 -07004891 // Used by package mover
4892 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004893 if (installOnSd(flags)) {
4894 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4895 return new SdInstallArgs(packageURI, cid);
4896 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004897 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004898 }
4899 }
4900
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004901 static abstract class InstallArgs {
4902 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004903 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004904 final int flags;
4905 final Uri packageURI;
4906 final String installerPackageName;
4907
4908 InstallArgs(Uri packageURI,
4909 IPackageInstallObserver observer, int flags,
4910 String installerPackageName) {
4911 this.packageURI = packageURI;
4912 this.flags = flags;
4913 this.observer = observer;
4914 this.installerPackageName = installerPackageName;
4915 }
4916
4917 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004918 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004919 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004920 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004921 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004922 abstract String getCodePath();
4923 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004924 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004925 // Need installer lock especially for dex file removal.
4926 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004927 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004928 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004929 }
4930
4931 class FileInstallArgs extends InstallArgs {
4932 File installDir;
4933 String codeFileName;
4934 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004935 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004936 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004937
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004938 FileInstallArgs(InstallParams params) {
4939 super(params.packageURI, params.observer,
4940 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004941 }
4942
Kenny Root85387d72010-08-26 10:13:11 -07004943 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004944 super(null, null, 0, null);
4945 File codeFile = new File(fullCodePath);
4946 installDir = codeFile.getParentFile();
4947 codeFileName = fullCodePath;
4948 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004949 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004950 }
4951
Kenny Root85387d72010-08-26 10:13:11 -07004952 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004953 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004954 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004955 String apkName = getNextCodePath(null, pkgName, ".apk");
4956 codeFileName = new File(installDir, apkName + ".apk").getPath();
4957 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004958 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004959 }
4960
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004961 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4962 return imcs.checkFreeStorage(false, packageURI);
4963 }
4964
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004965 String getCodePath() {
4966 return codeFileName;
4967 }
4968
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004969 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07004970 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004971 codeFileName = createTempPackageFile(installDir).getPath();
4972 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004973 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004974 }
4975
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004976 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004977 if (temp) {
4978 // Generate temp file name
4979 createCopyFile();
4980 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004981 // Get a ParcelFileDescriptor to write to the output file
4982 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004983 if (!created) {
4984 try {
4985 codeFile.createNewFile();
4986 // Set permissions
4987 if (!setPermissions()) {
4988 // Failed setting permissions.
4989 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4990 }
4991 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004992 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004993 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4994 }
4995 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004996 ParcelFileDescriptor out = null;
4997 try {
Kenny Root85387d72010-08-26 10:13:11 -07004998 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004999 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005000 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005001 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5002 }
5003 // Copy the resource now
5004 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5005 try {
5006 if (imcs.copyResource(packageURI, out)) {
5007 ret = PackageManager.INSTALL_SUCCEEDED;
5008 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005009 } finally {
5010 try { if (out != null) out.close(); } catch (IOException e) {}
5011 }
Kenny Root85387d72010-08-26 10:13:11 -07005012
5013 if (!temp) {
5014 NativeLibraryHelper.copyNativeBinariesLI(codeFile, new File(libraryPath));
5015 }
5016
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005017 return ret;
5018 }
5019
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005020 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005021 if (status != PackageManager.INSTALL_SUCCEEDED) {
5022 cleanUp();
5023 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005024 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005025 }
5026
5027 boolean doRename(int status, final String pkgName, String oldCodePath) {
5028 if (status != PackageManager.INSTALL_SUCCEEDED) {
5029 cleanUp();
5030 return false;
5031 } else {
5032 // Rename based on packageName
5033 File codeFile = new File(getCodePath());
5034 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5035 File desFile = new File(installDir, apkName + ".apk");
5036 if (!codeFile.renameTo(desFile)) {
5037 return false;
5038 }
5039 // Reset paths since the file has been renamed.
5040 codeFileName = desFile.getPath();
5041 resourceFileName = getResourcePathFromCodePath();
5042 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005043 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005044 // Failed setting permissions.
5045 return false;
5046 }
5047 return true;
5048 }
5049 }
5050
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005051 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005052 if (status != PackageManager.INSTALL_SUCCEEDED) {
5053 cleanUp();
5054 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005055 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005056 }
5057
5058 String getResourcePath() {
5059 return resourceFileName;
5060 }
5061
5062 String getResourcePathFromCodePath() {
5063 String codePath = getCodePath();
5064 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5065 String apkNameOnly = getApkName(codePath);
5066 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5067 } else {
5068 return codePath;
5069 }
5070 }
5071
Kenny Root85387d72010-08-26 10:13:11 -07005072 @Override
5073 String getNativeLibraryPath() {
5074 return libraryPath;
5075 }
5076
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005077 private boolean cleanUp() {
5078 boolean ret = true;
5079 String sourceDir = getCodePath();
5080 String publicSourceDir = getResourcePath();
5081 if (sourceDir != null) {
5082 File sourceFile = new File(sourceDir);
5083 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005084 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005085 ret = false;
5086 }
5087 // Delete application's code and resources
5088 sourceFile.delete();
5089 }
5090 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5091 final File publicSourceFile = new File(publicSourceDir);
5092 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005093 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005094 }
5095 if (publicSourceFile.exists()) {
5096 publicSourceFile.delete();
5097 }
5098 }
5099 return ret;
5100 }
5101
5102 void cleanUpResourcesLI() {
5103 String sourceDir = getCodePath();
5104 if (cleanUp() && mInstaller != null) {
5105 int retCode = mInstaller.rmdex(sourceDir);
5106 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005107 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005108 + " at location "
5109 + sourceDir + ", retcode=" + retCode);
5110 // we don't consider this to be a failure of the core package deletion
5111 }
5112 }
Kenny Root85387d72010-08-26 10:13:11 -07005113 if (libraryPath != null) {
Kenny Root8f7cc022010-09-12 09:04:56 -07005114 NativeLibraryHelper.removeNativeBinariesLI(libraryPath);
Kenny Root85387d72010-08-26 10:13:11 -07005115 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005116 }
5117
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005118 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005119 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005120 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005121 final int filePermissions =
5122 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5123 |FileUtils.S_IROTH;
5124 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5125 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005126 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005127 getCodePath()
5128 + ". The return code was: " + retCode);
5129 // TODO Define new internal error
5130 return false;
5131 }
5132 return true;
5133 }
5134 return true;
5135 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005136
5137 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005138 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005139 cleanUpResourcesLI();
5140 return true;
5141 }
Kenny Root85387d72010-08-26 10:13:11 -07005142
5143 private boolean isFwdLocked() {
5144 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5145 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005146 }
5147
5148 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005149 static final String RES_FILE_NAME = "pkg.apk";
5150
Kenny Root85387d72010-08-26 10:13:11 -07005151 String cid;
5152 String packagePath;
5153 String libraryPath;
5154
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005155 SdInstallArgs(InstallParams params) {
5156 super(params.packageURI, params.observer,
5157 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005158 }
5159
Kenny Root85387d72010-08-26 10:13:11 -07005160 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005161 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005162 // Extract cid from fullCodePath
5163 int eidx = fullCodePath.lastIndexOf("/");
5164 String subStr1 = fullCodePath.substring(0, eidx);
5165 int sidx = subStr1.lastIndexOf("/");
5166 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005167 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005168 }
5169
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005170 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005171 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5172 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005173 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005174 }
5175
5176 SdInstallArgs(Uri packageURI, String cid) {
5177 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005178 this.cid = cid;
5179 }
5180
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005181 void createCopyFile() {
5182 cid = getTempContainerId();
5183 }
5184
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005185 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5186 return imcs.checkFreeStorage(true, packageURI);
5187 }
5188
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005189 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005190 if (temp) {
5191 createCopyFile();
5192 }
Kenny Root85387d72010-08-26 10:13:11 -07005193 String newCachePath = imcs.copyResourceToContainer(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005194 packageURI, cid,
5195 getEncryptKey(), RES_FILE_NAME);
Kenny Root85387d72010-08-26 10:13:11 -07005196 if (newCachePath != null) {
5197 setCachePath(newCachePath);
5198 return PackageManager.INSTALL_SUCCEEDED;
5199 } else {
5200 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5201 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005202 }
5203
5204 @Override
5205 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005206 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005207 }
5208
5209 @Override
5210 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005211 return packagePath;
5212 }
5213
5214 @Override
5215 String getNativeLibraryPath() {
5216 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005217 }
5218
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005219 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005220 if (status != PackageManager.INSTALL_SUCCEEDED) {
5221 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005222 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005223 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005224 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005225 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005226 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5227 Process.SYSTEM_UID);
5228 if (newCachePath != null) {
5229 setCachePath(newCachePath);
5230 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005231 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5232 }
5233 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005234 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005235 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005236 }
5237
5238 boolean doRename(int status, final String pkgName,
5239 String oldCodePath) {
5240 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005241 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005242 if (PackageHelper.isContainerMounted(cid)) {
5243 // Unmount the container
5244 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005245 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005246 return false;
5247 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005248 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005249 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005250 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5251 " which might be stale. Will try to clean up.");
5252 // Clean up the stale container and proceed to recreate.
5253 if (!PackageHelper.destroySdDir(newCacheId)) {
5254 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5255 return false;
5256 }
5257 // Successfully cleaned up stale container. Try to rename again.
5258 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5259 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5260 + " inspite of cleaning it up.");
5261 return false;
5262 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005263 }
5264 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005265 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005266 newCachePath = PackageHelper.mountSdDir(newCacheId,
5267 getEncryptKey(), Process.SYSTEM_UID);
5268 } else {
5269 newCachePath = PackageHelper.getSdDir(newCacheId);
5270 }
5271 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005272 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005273 return false;
5274 }
5275 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005276 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005277 " at new path: " + newCachePath);
5278 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005279 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005280 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005281 }
5282
Kenny Root85387d72010-08-26 10:13:11 -07005283 private void setCachePath(String newCachePath) {
5284 File cachePath = new File(newCachePath);
5285 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5286 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5287 }
5288
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005289 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005290 if (status != PackageManager.INSTALL_SUCCEEDED) {
5291 cleanUp();
5292 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005293 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005294 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005295 PackageHelper.mountSdDir(cid,
5296 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005297 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005298 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005299 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005300 }
5301
5302 private void cleanUp() {
5303 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005304 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005305 }
5306
5307 void cleanUpResourcesLI() {
5308 String sourceFile = getCodePath();
5309 // Remove dex file
5310 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005311 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005312 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005313 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005314 + " at location "
5315 + sourceFile.toString() + ", retcode=" + retCode);
5316 // we don't consider this to be a failure of the core package deletion
5317 }
5318 }
5319 cleanUp();
5320 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005321
5322 boolean matchContainer(String app) {
5323 if (cid.startsWith(app)) {
5324 return true;
5325 }
5326 return false;
5327 }
5328
5329 String getPackageName() {
5330 int idx = cid.lastIndexOf("-");
5331 if (idx == -1) {
5332 return cid;
5333 }
5334 return cid.substring(0, idx);
5335 }
5336
5337 boolean doPostDeleteLI(boolean delete) {
5338 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005339 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005340 if (mounted) {
5341 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005342 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005343 }
5344 if (ret && delete) {
5345 cleanUpResourcesLI();
5346 }
5347 return ret;
5348 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005349 };
5350
5351 // Utility method used to create code paths based on package name and available index.
5352 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5353 String idxStr = "";
5354 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005355 // Fall back to default value of idx=1 if prefix is not
5356 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005357 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005358 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005359 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005360 if (subStr.endsWith(suffix)) {
5361 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005362 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005363 // If oldCodePath already contains prefix find out the
5364 // ending index to either increment or decrement.
5365 int sidx = subStr.lastIndexOf(prefix);
5366 if (sidx != -1) {
5367 subStr = subStr.substring(sidx + prefix.length());
5368 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005369 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5370 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005371 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005372 try {
5373 idx = Integer.parseInt(subStr);
5374 if (idx <= 1) {
5375 idx++;
5376 } else {
5377 idx--;
5378 }
5379 } catch(NumberFormatException e) {
5380 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005381 }
5382 }
5383 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005384 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005385 return prefix + idxStr;
5386 }
5387
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005388 // Utility method used to ignore ADD/REMOVE events
5389 // by directory observer.
5390 private static boolean ignoreCodePath(String fullPathStr) {
5391 String apkName = getApkName(fullPathStr);
5392 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5393 if (idx != -1 && ((idx+1) < apkName.length())) {
5394 // Make sure the package ends with a numeral
5395 String version = apkName.substring(idx+1);
5396 try {
5397 Integer.parseInt(version);
5398 return true;
5399 } catch (NumberFormatException e) {}
5400 }
5401 return false;
5402 }
5403
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005404 // Utility method that returns the relative package path with respect
5405 // to the installation directory. Like say for /data/data/com.test-1.apk
5406 // string com.test-1 is returned.
5407 static String getApkName(String codePath) {
5408 if (codePath == null) {
5409 return null;
5410 }
5411 int sidx = codePath.lastIndexOf("/");
5412 int eidx = codePath.lastIndexOf(".");
5413 if (eidx == -1) {
5414 eidx = codePath.length();
5415 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005416 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005417 return null;
5418 }
5419 return codePath.substring(sidx+1, eidx);
5420 }
5421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005422 class PackageInstalledInfo {
5423 String name;
5424 int uid;
5425 PackageParser.Package pkg;
5426 int returnCode;
5427 PackageRemovedInfo removedInfo;
5428 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430 /*
5431 * Install a non-existing package.
5432 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005433 private void installNewPackageLI(PackageParser.Package pkg,
5434 int parseFlags,
5435 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005436 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005437 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005438 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005439
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005440 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 res.name = pkgName;
5442 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005443 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5444 // A package with the same name is already installed, though
5445 // it has been renamed to an older name. The package we
5446 // are trying to install should be installed as an update to
5447 // the existing one, but that has not been requested, so bail.
5448 Slog.w(TAG, "Attempt to re-install " + pkgName
5449 + " without first uninstalling package running as "
5450 + mSettings.mRenamedPackages.get(pkgName));
5451 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5452 return;
5453 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005454 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005456 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 + " without first uninstalling.");
5458 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5459 return;
5460 }
5461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005462 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005463 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005465 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5467 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5468 }
5469 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005470 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005471 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005472 res);
5473 // delete the partially installed application. the data directory will have to be
5474 // restored if it was already existing
5475 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5476 // remove package from internal structures. Note that we want deletePackageX to
5477 // delete the package data and cache directories that it created in
5478 // scanPackageLocked, unless those directories existed before we even tried to
5479 // install.
5480 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005481 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005482 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005483 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 }
5485 }
5486 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005487
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005488 private void replacePackageLI(PackageParser.Package pkg,
5489 int parseFlags,
5490 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005491 String installerPackageName, PackageInstalledInfo res) {
5492
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005493 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005494 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 // First find the old package info and check signatures
5496 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005497 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005498 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005499 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005500 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5501 return;
5502 }
5503 }
Kenny Root85387d72010-08-26 10:13:11 -07005504 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005505 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005506 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005508 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 }
5510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005513 PackageParser.Package pkg,
5514 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005515 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005516 PackageParser.Package newPackage = null;
5517 String pkgName = deletedPackage.packageName;
5518 boolean deletedPkg = true;
5519 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005520
Jacek Surazski65e13172009-04-28 15:26:38 +02005521 String oldInstallerPackageName = null;
5522 synchronized (mPackages) {
5523 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5524 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005527 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005528 res.removedInfo, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 // If the existing package was'nt successfully deleted
5530 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5531 deletedPkg = false;
5532 } else {
5533 // Successfully deleted the old package. Now proceed with re-installation
5534 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005535 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005537 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005538 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5539 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005540 }
5541 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005542 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005543 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 res);
5545 updatedSettings = true;
5546 }
5547 }
5548
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005549 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550 // remove package from internal structures. Note that we want deletePackageX to
5551 // delete the package data and cache directories that it created in
5552 // scanPackageLocked, unless those directories existed before we even tried to
5553 // install.
5554 if(updatedSettings) {
5555 deletePackageLI(
5556 pkgName, true,
5557 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005558 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559 }
5560 // Since we failed to install the new package we need to restore the old
5561 // package that we deleted.
5562 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005563 File restoreFile = new File(deletedPackage.mPath);
5564 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005565 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005566 return;
5567 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005568 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005569 boolean oldOnSd = isExternal(deletedPackage);
5570 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5571 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5572 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5573 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5574 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5575 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5576 return;
5577 }
5578 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005579 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005580 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005581 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005582 mSettings.writeLP();
5583 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005584 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 }
5586 }
5587 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005590 PackageParser.Package pkg,
5591 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005592 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005593 PackageParser.Package newPackage = null;
5594 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005595 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 PackageParser.PARSE_IS_SYSTEM;
5597 String packageName = deletedPackage.packageName;
5598 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5599 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005600 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 return;
5602 }
5603 PackageParser.Package oldPkg;
5604 PackageSetting oldPkgSetting;
5605 synchronized (mPackages) {
5606 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005607 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5609 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005610 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 return;
5612 }
5613 }
5614 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5615 res.removedInfo.removedPackage = packageName;
5616 // Remove existing system package
5617 removePackageLI(oldPkg, true);
5618 synchronized (mPackages) {
5619 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5620 }
5621
5622 // Successfully disabled the old package. Now proceed with re-installation
5623 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5624 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005625 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005626 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005627 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005628 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5629 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5630 }
5631 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005632 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633 updatedSettings = true;
5634 }
5635
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005636 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 // Re installation failed. Restore old information
5638 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005639 if (newPackage != null) {
5640 removePackageLI(newPackage, true);
5641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005643 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005645 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 // Restore the old system information in Settings
5647 synchronized(mPackages) {
5648 if(updatedSettings) {
5649 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005650 mSettings.setInstallerPackageName(packageName,
5651 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005652 }
5653 mSettings.writeLP();
5654 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005655 } else {
5656 // If this is an update to an existing update, setup
5657 // to remove the existing update.
5658 synchronized (mPackages) {
5659 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5660 if (ps != null && ps.codePathString != null &&
5661 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5662 int installFlags = 0;
5663 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005664 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005665 }
5666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005667 }
5668 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005669
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005670 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005671 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005672 int retCode;
5673 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5674 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5675 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005676 if (mNoDexOpt) {
5677 /*
5678 * If we're in an engineering build, programs are lazily run
5679 * through dexopt. If the .dex file doesn't exist yet, it
5680 * will be created when the program is run next.
5681 */
5682 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5683 } else {
5684 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5685 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5686 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005687 }
5688 }
5689 return PackageManager.INSTALL_SUCCEEDED;
5690 }
5691
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005692 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005693 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005694 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 synchronized (mPackages) {
5696 //write settings. the installStatus will be incomplete at this stage.
5697 //note that the new package setting would have already been
5698 //added to mPackages. It hasn't been persisted yet.
5699 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5700 mSettings.writeLP();
5701 }
5702
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005703 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005704 != PackageManager.INSTALL_SUCCEEDED) {
5705 // Discontinue if moving dex files failed.
5706 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005708 if((res.returnCode = setPermissionsLI(newPackage))
5709 != PackageManager.INSTALL_SUCCEEDED) {
5710 if (mInstaller != null) {
5711 mInstaller.rmdex(newPackage.mScanPath);
5712 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005713 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005714 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005715 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005718 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005719 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 res.name = pkgName;
5721 res.uid = newPackage.applicationInfo.uid;
5722 res.pkg = newPackage;
5723 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005724 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5726 //to update install status
5727 mSettings.writeLP();
5728 }
5729 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005730
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005731 private void installPackageLI(InstallArgs args,
5732 boolean newInstall, PackageInstalledInfo res) {
5733 int pFlags = args.flags;
5734 String installerPackageName = args.installerPackageName;
5735 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005736 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005737 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005738 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005739 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005740 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005741 // Result object to be returned
5742 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5743
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005744 // Retrieve PackageSettings and parse package
5745 int parseFlags = PackageParser.PARSE_CHATTY |
5746 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5747 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5748 parseFlags |= mDefParseFlags;
5749 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5750 pp.setSeparateProcesses(mSeparateProcesses);
5751 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5752 null, mMetrics, parseFlags);
5753 if (pkg == null) {
5754 res.returnCode = pp.getParseError();
5755 return;
5756 }
5757 String pkgName = res.name = pkg.packageName;
5758 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5759 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5760 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5761 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005763 }
5764 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5765 res.returnCode = pp.getParseError();
5766 return;
5767 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005768 // Get rid of all references to package scan path via parser.
5769 pp = null;
5770 String oldCodePath = null;
5771 boolean systemApp = false;
5772 synchronized (mPackages) {
5773 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005774 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5775 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005776 if (pkg.mOriginalPackages != null
5777 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005778 && mPackages.containsKey(oldName)) {
5779 // This package is derived from an original package,
5780 // and this device has been updating from that original
5781 // name. We must continue using the original name, so
5782 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005783 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005784 pkgName = pkg.packageName;
5785 replace = true;
5786 } else if (mPackages.containsKey(pkgName)) {
5787 // This package, under its official name, already exists
5788 // on the device; we should replace it.
5789 replace = true;
5790 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005791 }
5792 PackageSetting ps = mSettings.mPackages.get(pkgName);
5793 if (ps != null) {
5794 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5795 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5796 systemApp = (ps.pkg.applicationInfo.flags &
5797 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005798 }
5799 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005800 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005801
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005802 if (systemApp && onSd) {
5803 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005804 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005805 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5806 return;
5807 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005808
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005809 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5810 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5811 return;
5812 }
5813 // Set application objects path explicitly after the rename
5814 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005815 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005816 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005817 replacePackageLI(pkg, parseFlags, scanMode,
5818 installerPackageName, res);
5819 } else {
5820 installNewPackageLI(pkg, parseFlags, scanMode,
5821 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 }
5823 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005824
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005825 private int setPermissionsLI(PackageParser.Package newPackage) {
5826 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005827 int retCode = 0;
5828 // TODO Gross hack but fix later. Ideally move this to be a post installation
5829 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005830 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005831 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 try {
5833 extractPublicFiles(newPackage, destResourceFile);
5834 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005835 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 -08005836 " forward-locked app.");
5837 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5838 } finally {
5839 //TODO clean up the extracted public files
5840 }
5841 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005842 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843 newPackage.applicationInfo.uid);
5844 } else {
5845 final int filePermissions =
5846 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005847 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005848 newPackage.applicationInfo.uid);
5849 }
5850 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005851 // The permissions on the resource file was set when it was copied for
5852 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005856 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005857 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005858 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005859 // TODO Define new internal error
5860 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 }
5862 return PackageManager.INSTALL_SUCCEEDED;
5863 }
5864
Kenny Root85387d72010-08-26 10:13:11 -07005865 private static boolean isForwardLocked(PackageParser.Package pkg) {
5866 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 }
5868
Kenny Root85387d72010-08-26 10:13:11 -07005869 private static boolean isExternal(PackageParser.Package pkg) {
5870 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5871 }
5872
5873 private static boolean isSystemApp(PackageParser.Package pkg) {
5874 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5875 }
5876
5877 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5878 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005879 }
5880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 private void extractPublicFiles(PackageParser.Package newPackage,
5882 File publicZipFile) throws IOException {
5883 final ZipOutputStream publicZipOutStream =
5884 new ZipOutputStream(new FileOutputStream(publicZipFile));
5885 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5886
5887 // Copy manifest, resources.arsc and res directory to public zip
5888
5889 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5890 while (privateZipEntries.hasMoreElements()) {
5891 final ZipEntry zipEntry = privateZipEntries.nextElement();
5892 final String zipEntryName = zipEntry.getName();
5893 if ("AndroidManifest.xml".equals(zipEntryName)
5894 || "resources.arsc".equals(zipEntryName)
5895 || zipEntryName.startsWith("res/")) {
5896 try {
5897 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5898 } catch (IOException e) {
5899 try {
5900 publicZipOutStream.close();
5901 throw e;
5902 } finally {
5903 publicZipFile.delete();
5904 }
5905 }
5906 }
5907 }
5908
5909 publicZipOutStream.close();
5910 FileUtils.setPermissions(
5911 publicZipFile.getAbsolutePath(),
5912 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5913 -1, -1);
5914 }
5915
5916 private static void copyZipEntry(ZipEntry zipEntry,
5917 ZipFile inZipFile,
5918 ZipOutputStream outZipStream) throws IOException {
5919 byte[] buffer = new byte[4096];
5920 int num;
5921
5922 ZipEntry newEntry;
5923 if (zipEntry.getMethod() == ZipEntry.STORED) {
5924 // Preserve the STORED method of the input entry.
5925 newEntry = new ZipEntry(zipEntry);
5926 } else {
5927 // Create a new entry so that the compressed len is recomputed.
5928 newEntry = new ZipEntry(zipEntry.getName());
5929 }
5930 outZipStream.putNextEntry(newEntry);
5931
5932 InputStream data = inZipFile.getInputStream(zipEntry);
5933 while ((num = data.read(buffer)) > 0) {
5934 outZipStream.write(buffer, 0, num);
5935 }
5936 outZipStream.flush();
5937 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005939 private void deleteTempPackageFiles() {
5940 FilenameFilter filter = new FilenameFilter() {
5941 public boolean accept(File dir, String name) {
5942 return name.startsWith("vmdl") && name.endsWith(".tmp");
5943 }
5944 };
5945 String tmpFilesList[] = mAppInstallDir.list(filter);
5946 if(tmpFilesList == null) {
5947 return;
5948 }
5949 for(int i = 0; i < tmpFilesList.length; i++) {
5950 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5951 tmpFile.delete();
5952 }
5953 }
5954
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005955 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005956 File tmpPackageFile;
5957 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005958 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005960 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 return null;
5962 }
5963 try {
5964 FileUtils.setPermissions(
5965 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5966 -1, -1);
5967 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005968 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 return null;
5970 }
5971 return tmpPackageFile;
5972 }
5973
5974 public void deletePackage(final String packageName,
5975 final IPackageDeleteObserver observer,
5976 final int flags) {
5977 mContext.enforceCallingOrSelfPermission(
5978 android.Manifest.permission.DELETE_PACKAGES, null);
5979 // Queue up an async operation since the package deletion may take a little while.
5980 mHandler.post(new Runnable() {
5981 public void run() {
5982 mHandler.removeCallbacks(this);
5983 final boolean succeded = deletePackageX(packageName, true, true, flags);
5984 if (observer != null) {
5985 try {
5986 observer.packageDeleted(succeded);
5987 } catch (RemoteException e) {
5988 Log.i(TAG, "Observer no longer exists.");
5989 } //end catch
5990 } //end if
5991 } //end run
5992 });
5993 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005995 /**
5996 * This method is an internal method that could be get invoked either
5997 * to delete an installed package or to clean up a failed installation.
5998 * After deleting an installed package, a broadcast is sent to notify any
5999 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006000 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 * installation wouldn't have sent the initial broadcast either
6002 * The key steps in deleting a package are
6003 * deleting the package information in internal structures like mPackages,
6004 * deleting the packages base directories through installd
6005 * updating mSettings to reflect current status
6006 * persisting settings for later use
6007 * sending a broadcast if necessary
6008 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6010 boolean deleteCodeAndResources, int flags) {
6011 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006012 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006014 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6015 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6016 try {
6017 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006018 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006019 return false;
6020 }
6021 } catch (RemoteException e) {
6022 }
6023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006025 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006026 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006030 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006031 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006032
6033 // If the removed package was a system update, the old system packaged
6034 // was re-enabled; we need to broadcast this information
6035 if (systemUpdate) {
6036 Bundle extras = new Bundle(1);
6037 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6038 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6039
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006040 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6041 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006044 // Force a gc here.
6045 Runtime.getRuntime().gc();
6046 // Delete the resources here after sending the broadcast to let
6047 // other processes clean up before deleting resources.
6048 if (info.args != null) {
6049 synchronized (mInstallLock) {
6050 info.args.doPostDeleteLI(deleteCodeAndResources);
6051 }
6052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006053 return res;
6054 }
6055
6056 static class PackageRemovedInfo {
6057 String removedPackage;
6058 int uid = -1;
6059 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006060 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006061 // Clean up resources deleted packages.
6062 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006063
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006064 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006065 Bundle extras = new Bundle(1);
6066 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6067 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6068 if (replacing) {
6069 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6070 }
6071 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006072 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006073 }
6074 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006075 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 }
6077 }
6078 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006080 /*
6081 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6082 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006083 * 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 -08006084 * delete a partially installed application.
6085 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006086 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006087 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006089 if (outInfo != null) {
6090 outInfo.removedPackage = packageName;
6091 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006092 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 // Retrieve object to delete permissions for shared user later on
6094 PackageSetting deletedPs;
6095 synchronized (mPackages) {
6096 deletedPs = mSettings.mPackages.get(packageName);
6097 }
6098 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006099 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006101 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006103 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 + packageName + ", retcode=" + retCode);
6105 // we don't consider this to be a failure of the core package deletion
6106 }
6107 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006108 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 PackageParser.Package pkg = mPackages.get(packageName);
6110 File dataDir = new File(pkg.applicationInfo.dataDir);
6111 dataDir.delete();
6112 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006113 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 }
6115 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006116 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006117 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6118 if (outInfo != null) {
6119 outInfo.removedUid = mSettings.removePackageLP(packageName);
6120 }
6121 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006122 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006123 if (deletedPs.sharedUser != null) {
6124 // remove permissions associated with package
6125 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6126 }
6127 }
6128 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006129 // remove from preferred activities.
6130 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6131 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6132 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6133 removed.add(pa);
6134 }
6135 }
6136 for (PreferredActivity pa : removed) {
6137 mSettings.mPreferredActivities.removeFilter(pa);
6138 }
6139 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006140 if (writeSettings) {
6141 // Save settings now
6142 mSettings.writeLP();
6143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006144 }
6145 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 /*
6148 * Tries to delete system package.
6149 */
6150 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006151 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 ApplicationInfo applicationInfo = p.applicationInfo;
6153 //applicable for non-partially installed applications only
6154 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006155 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 return false;
6157 }
6158 PackageSetting ps = null;
6159 // Confirm if the system package has been updated
6160 // An updated system app can be deleted. This will also have to restore
6161 // the system pkg from system partition
6162 synchronized (mPackages) {
6163 ps = mSettings.getDisabledSystemPkg(p.packageName);
6164 }
6165 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006166 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 return false;
6168 } else {
6169 Log.i(TAG, "Deleting system pkg from data partition");
6170 }
6171 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006172 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006173 final boolean deleteCodeAndResources;
6174 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006175 // Delete code and resources for downgrades
6176 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006177 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006178 } else {
6179 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006180 deleteCodeAndResources = false;
6181 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006182 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006183 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6184 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 if (!ret) {
6186 return false;
6187 }
6188 synchronized (mPackages) {
6189 // Reinstate the old system package
6190 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006191 // Remove any native libraries from the upgraded package.
6192 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 }
6194 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006195 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006197 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006200 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 return false;
6202 }
6203 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006204 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006205 if (writeSettings) {
6206 mSettings.writeLP();
6207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 }
6209 return true;
6210 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006213 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6214 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 ApplicationInfo applicationInfo = p.applicationInfo;
6216 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006217 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 return false;
6219 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006220 if (outInfo != null) {
6221 outInfo.uid = applicationInfo.uid;
6222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223
6224 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006225 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226
6227 // Delete application code and resources
6228 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006229 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006230 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6231 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6232 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6233 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 }
6235 return true;
6236 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 /*
6239 * This method handles package deletion in general
6240 */
6241 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006242 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6243 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006245 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 return false;
6247 }
6248 PackageParser.Package p;
6249 boolean dataOnly = false;
6250 synchronized (mPackages) {
6251 p = mPackages.get(packageName);
6252 if (p == null) {
6253 //this retrieves partially installed apps
6254 dataOnly = true;
6255 PackageSetting ps = mSettings.mPackages.get(packageName);
6256 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006257 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 return false;
6259 }
6260 p = ps.pkg;
6261 }
6262 }
6263 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006264 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 return false;
6266 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 if (dataOnly) {
6269 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006270 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 return true;
6272 }
6273 // At this point the package should have ApplicationInfo associated with it
6274 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006275 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 return false;
6277 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006278 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006279 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 Log.i(TAG, "Removing system package:"+p.packageName);
6281 // When an updated system application is deleted we delete the existing resources as well and
6282 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006283 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006284 } else {
6285 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006286 // Kill application pre-emptively especially for apps on sd.
6287 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006288 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6289 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006291 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 public void clearApplicationUserData(final String packageName,
6295 final IPackageDataObserver observer) {
6296 mContext.enforceCallingOrSelfPermission(
6297 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6298 // Queue up an async operation since the package deletion may take a little while.
6299 mHandler.post(new Runnable() {
6300 public void run() {
6301 mHandler.removeCallbacks(this);
6302 final boolean succeeded;
6303 synchronized (mInstallLock) {
6304 succeeded = clearApplicationUserDataLI(packageName);
6305 }
6306 if (succeeded) {
6307 // invoke DeviceStorageMonitor's update method to clear any notifications
6308 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6309 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6310 if (dsm != null) {
6311 dsm.updateMemory();
6312 }
6313 }
6314 if(observer != null) {
6315 try {
6316 observer.onRemoveCompleted(packageName, succeeded);
6317 } catch (RemoteException e) {
6318 Log.i(TAG, "Observer no longer exists.");
6319 }
6320 } //end if observer
6321 } //end run
6322 });
6323 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 private boolean clearApplicationUserDataLI(String packageName) {
6326 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006327 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 return false;
6329 }
6330 PackageParser.Package p;
6331 boolean dataOnly = false;
6332 synchronized (mPackages) {
6333 p = mPackages.get(packageName);
6334 if(p == null) {
6335 dataOnly = true;
6336 PackageSetting ps = mSettings.mPackages.get(packageName);
6337 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006338 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 return false;
6340 }
6341 p = ps.pkg;
6342 }
6343 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006344 boolean useEncryptedFSDir = false;
6345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 if(!dataOnly) {
6347 //need to check this only for fully installed applications
6348 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006349 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006350 return false;
6351 }
6352 final ApplicationInfo applicationInfo = p.applicationInfo;
6353 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006354 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 return false;
6356 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006357 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 }
6359 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006360 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006361 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006362 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 + packageName);
6364 return false;
6365 }
6366 }
6367 return true;
6368 }
6369
6370 public void deleteApplicationCacheFiles(final String packageName,
6371 final IPackageDataObserver observer) {
6372 mContext.enforceCallingOrSelfPermission(
6373 android.Manifest.permission.DELETE_CACHE_FILES, null);
6374 // Queue up an async operation since the package deletion may take a little while.
6375 mHandler.post(new Runnable() {
6376 public void run() {
6377 mHandler.removeCallbacks(this);
6378 final boolean succeded;
6379 synchronized (mInstallLock) {
6380 succeded = deleteApplicationCacheFilesLI(packageName);
6381 }
6382 if(observer != null) {
6383 try {
6384 observer.onRemoveCompleted(packageName, succeded);
6385 } catch (RemoteException e) {
6386 Log.i(TAG, "Observer no longer exists.");
6387 }
6388 } //end if observer
6389 } //end run
6390 });
6391 }
6392
6393 private boolean deleteApplicationCacheFilesLI(String packageName) {
6394 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006395 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 return false;
6397 }
6398 PackageParser.Package p;
6399 synchronized (mPackages) {
6400 p = mPackages.get(packageName);
6401 }
6402 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006403 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 return false;
6405 }
6406 final ApplicationInfo applicationInfo = p.applicationInfo;
6407 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006408 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 return false;
6410 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006411 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006413 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006415 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 + packageName);
6417 return false;
6418 }
6419 }
6420 return true;
6421 }
6422
6423 public void getPackageSizeInfo(final String packageName,
6424 final IPackageStatsObserver observer) {
6425 mContext.enforceCallingOrSelfPermission(
6426 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6427 // Queue up an async operation since the package deletion may take a little while.
6428 mHandler.post(new Runnable() {
6429 public void run() {
6430 mHandler.removeCallbacks(this);
6431 PackageStats lStats = new PackageStats(packageName);
6432 final boolean succeded;
6433 synchronized (mInstallLock) {
6434 succeded = getPackageSizeInfoLI(packageName, lStats);
6435 }
6436 if(observer != null) {
6437 try {
6438 observer.onGetStatsCompleted(lStats, succeded);
6439 } catch (RemoteException e) {
6440 Log.i(TAG, "Observer no longer exists.");
6441 }
6442 } //end if observer
6443 } //end run
6444 });
6445 }
6446
6447 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6448 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006449 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006450 return false;
6451 }
6452 PackageParser.Package p;
6453 boolean dataOnly = false;
6454 synchronized (mPackages) {
6455 p = mPackages.get(packageName);
6456 if(p == null) {
6457 dataOnly = true;
6458 PackageSetting ps = mSettings.mPackages.get(packageName);
6459 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006460 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006461 return false;
6462 }
6463 p = ps.pkg;
6464 }
6465 }
6466 String publicSrcDir = null;
6467 if(!dataOnly) {
6468 final ApplicationInfo applicationInfo = p.applicationInfo;
6469 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006470 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 return false;
6472 }
6473 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6474 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006475 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006476 if (mInstaller != null) {
6477 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006478 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 if (res < 0) {
6480 return false;
6481 } else {
6482 return true;
6483 }
6484 }
6485 return true;
6486 }
6487
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006490 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491 }
6492
6493 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006494 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 }
6496
6497 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006498 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 }
6500
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006501 int getUidTargetSdkVersionLockedLP(int uid) {
6502 Object obj = mSettings.getUserIdLP(uid);
6503 if (obj instanceof SharedUserSetting) {
6504 SharedUserSetting sus = (SharedUserSetting)obj;
6505 final int N = sus.packages.size();
6506 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6507 Iterator<PackageSetting> it = sus.packages.iterator();
6508 int i=0;
6509 while (it.hasNext()) {
6510 PackageSetting ps = it.next();
6511 if (ps.pkg != null) {
6512 int v = ps.pkg.applicationInfo.targetSdkVersion;
6513 if (v < vers) vers = v;
6514 }
6515 }
6516 return vers;
6517 } else if (obj instanceof PackageSetting) {
6518 PackageSetting ps = (PackageSetting)obj;
6519 if (ps.pkg != null) {
6520 return ps.pkg.applicationInfo.targetSdkVersion;
6521 }
6522 }
6523 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6524 }
6525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 public void addPreferredActivity(IntentFilter filter, int match,
6527 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006529 if (mContext.checkCallingOrSelfPermission(
6530 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6531 != PackageManager.PERMISSION_GRANTED) {
6532 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6533 < Build.VERSION_CODES.FROYO) {
6534 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6535 + Binder.getCallingUid());
6536 return;
6537 }
6538 mContext.enforceCallingOrSelfPermission(
6539 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6540 }
6541
6542 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6544 mSettings.mPreferredActivities.addFilter(
6545 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006546 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006547 }
6548 }
6549
Satish Sampath8dbe6122009-06-02 23:35:54 +01006550 public void replacePreferredActivity(IntentFilter filter, int match,
6551 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006552 if (filter.countActions() != 1) {
6553 throw new IllegalArgumentException(
6554 "replacePreferredActivity expects filter to have only 1 action.");
6555 }
6556 if (filter.countCategories() != 1) {
6557 throw new IllegalArgumentException(
6558 "replacePreferredActivity expects filter to have only 1 category.");
6559 }
6560 if (filter.countDataAuthorities() != 0
6561 || filter.countDataPaths() != 0
6562 || filter.countDataSchemes() != 0
6563 || filter.countDataTypes() != 0) {
6564 throw new IllegalArgumentException(
6565 "replacePreferredActivity expects filter to have no data authorities, " +
6566 "paths, schemes or types.");
6567 }
6568 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006569 if (mContext.checkCallingOrSelfPermission(
6570 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6571 != PackageManager.PERMISSION_GRANTED) {
6572 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6573 < Build.VERSION_CODES.FROYO) {
6574 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6575 + Binder.getCallingUid());
6576 return;
6577 }
6578 mContext.enforceCallingOrSelfPermission(
6579 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6580 }
6581
Satish Sampath8dbe6122009-06-02 23:35:54 +01006582 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6583 String action = filter.getAction(0);
6584 String category = filter.getCategory(0);
6585 while (it.hasNext()) {
6586 PreferredActivity pa = it.next();
6587 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6588 it.remove();
6589 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6590 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6591 }
6592 }
6593 addPreferredActivity(filter, match, set, activity);
6594 }
6595 }
6596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006597 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006599 int uid = Binder.getCallingUid();
6600 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006601 if (pkg == null || pkg.applicationInfo.uid != uid) {
6602 if (mContext.checkCallingOrSelfPermission(
6603 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6604 != PackageManager.PERMISSION_GRANTED) {
6605 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6606 < Build.VERSION_CODES.FROYO) {
6607 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6608 + Binder.getCallingUid());
6609 return;
6610 }
6611 mContext.enforceCallingOrSelfPermission(
6612 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6613 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006614 }
6615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006617 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 }
6619 }
6620 }
6621
6622 boolean clearPackagePreferredActivitiesLP(String packageName) {
6623 boolean changed = false;
6624 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6625 while (it.hasNext()) {
6626 PreferredActivity pa = it.next();
6627 if (pa.mActivity.getPackageName().equals(packageName)) {
6628 it.remove();
6629 changed = true;
6630 }
6631 }
6632 return changed;
6633 }
6634
6635 public int getPreferredActivities(List<IntentFilter> outFilters,
6636 List<ComponentName> outActivities, String packageName) {
6637
6638 int num = 0;
6639 synchronized (mPackages) {
6640 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6641 while (it.hasNext()) {
6642 PreferredActivity pa = it.next();
6643 if (packageName == null
6644 || pa.mActivity.getPackageName().equals(packageName)) {
6645 if (outFilters != null) {
6646 outFilters.add(new IntentFilter(pa));
6647 }
6648 if (outActivities != null) {
6649 outActivities.add(pa.mActivity);
6650 }
6651 }
6652 }
6653 }
6654
6655 return num;
6656 }
6657
6658 public void setApplicationEnabledSetting(String appPackageName,
6659 int newState, int flags) {
6660 setEnabledSetting(appPackageName, null, newState, flags);
6661 }
6662
6663 public void setComponentEnabledSetting(ComponentName componentName,
6664 int newState, int flags) {
6665 setEnabledSetting(componentName.getPackageName(),
6666 componentName.getClassName(), newState, flags);
6667 }
6668
6669 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006670 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6672 || newState == COMPONENT_ENABLED_STATE_ENABLED
6673 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6674 throw new IllegalArgumentException("Invalid new component state: "
6675 + newState);
6676 }
6677 PackageSetting pkgSetting;
6678 final int uid = Binder.getCallingUid();
6679 final int permission = mContext.checkCallingPermission(
6680 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6681 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006682 boolean sendNow = false;
6683 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006684 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006686 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006688 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006689 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006690 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006691 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006692 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006693 }
6694 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006695 "Unknown component: " + packageName
6696 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 }
6698 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6699 throw new SecurityException(
6700 "Permission Denial: attempt to change component state from pid="
6701 + Binder.getCallingPid()
6702 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6703 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006704 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006705 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006706 if (pkgSetting.enabled == newState) {
6707 // Nothing to do
6708 return;
6709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006711 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 } else {
6713 // We're dealing with a component level state change
6714 switch (newState) {
6715 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006716 if (!pkgSetting.enableComponentLP(className)) {
6717 return;
6718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719 break;
6720 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006721 if (!pkgSetting.disableComponentLP(className)) {
6722 return;
6723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 break;
6725 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006726 if (!pkgSetting.restoreComponentLP(className)) {
6727 return;
6728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 break;
6730 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006731 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006732 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 }
6734 }
6735 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006736 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006737 components = mPendingBroadcasts.get(packageName);
6738 boolean newPackage = components == null;
6739 if (newPackage) {
6740 components = new ArrayList<String>();
6741 }
6742 if (!components.contains(componentName)) {
6743 components.add(componentName);
6744 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006745 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6746 sendNow = true;
6747 // Purge entry from pending broadcast list if another one exists already
6748 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006749 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006750 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006751 if (newPackage) {
6752 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006753 }
6754 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6755 // Schedule a message
6756 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6757 }
6758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761 long callingId = Binder.clearCallingIdentity();
6762 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006763 if (sendNow) {
6764 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006765 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 } finally {
6768 Binder.restoreCallingIdentity(callingId);
6769 }
6770 }
6771
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006772 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006773 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6774 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6775 + " components=" + componentNames);
6776 Bundle extras = new Bundle(4);
6777 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6778 String nameList[] = new String[componentNames.size()];
6779 componentNames.toArray(nameList);
6780 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006781 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6782 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006783 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006784 }
6785
Jacek Surazski65e13172009-04-28 15:26:38 +02006786 public String getInstallerPackageName(String packageName) {
6787 synchronized (mPackages) {
6788 PackageSetting pkg = mSettings.mPackages.get(packageName);
6789 if (pkg == null) {
6790 throw new IllegalArgumentException("Unknown package: " + packageName);
6791 }
6792 return pkg.installerPackageName;
6793 }
6794 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 public int getApplicationEnabledSetting(String appPackageName) {
6797 synchronized (mPackages) {
6798 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6799 if (pkg == null) {
6800 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6801 }
6802 return pkg.enabled;
6803 }
6804 }
6805
6806 public int getComponentEnabledSetting(ComponentName componentName) {
6807 synchronized (mPackages) {
6808 final String packageNameStr = componentName.getPackageName();
6809 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6810 if (pkg == null) {
6811 throw new IllegalArgumentException("Unknown component: " + componentName);
6812 }
6813 final String classNameStr = componentName.getClassName();
6814 return pkg.currentEnabledStateLP(classNameStr);
6815 }
6816 }
6817
6818 public void enterSafeMode() {
6819 if (!mSystemReady) {
6820 mSafeMode = true;
6821 }
6822 }
6823
6824 public void systemReady() {
6825 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006826
6827 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006828 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006829 mContext.getContentResolver(),
6830 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006831 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006832 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006833 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006835 }
6836
6837 public boolean isSafeMode() {
6838 return mSafeMode;
6839 }
6840
6841 public boolean hasSystemUidErrors() {
6842 return mHasSystemUidErrors;
6843 }
6844
6845 static String arrayToString(int[] array) {
6846 StringBuffer buf = new StringBuffer(128);
6847 buf.append('[');
6848 if (array != null) {
6849 for (int i=0; i<array.length; i++) {
6850 if (i > 0) buf.append(", ");
6851 buf.append(array[i]);
6852 }
6853 }
6854 buf.append(']');
6855 return buf.toString();
6856 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858 @Override
6859 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6860 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6861 != PackageManager.PERMISSION_GRANTED) {
6862 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6863 + Binder.getCallingPid()
6864 + ", uid=" + Binder.getCallingUid()
6865 + " without permission "
6866 + android.Manifest.permission.DUMP);
6867 return;
6868 }
6869
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006870 boolean dumpStar = true;
6871 boolean dumpLibs = false;
6872 boolean dumpFeatures = false;
6873 boolean dumpResolvers = false;
6874 boolean dumpPermissions = false;
6875 boolean dumpPackages = false;
6876 boolean dumpSharedUsers = false;
6877 boolean dumpMessages = false;
6878 boolean dumpProviders = false;
6879
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006880 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006881 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006882
6883 int opti = 0;
6884 while (opti < args.length) {
6885 String opt = args[opti];
6886 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6887 break;
6888 }
6889 opti++;
6890 if ("-a".equals(opt)) {
6891 // Right now we only know how to print all.
6892 } else if ("-h".equals(opt)) {
6893 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006894 pw.println(" [-h] [-f] [cmd] ...");
6895 pw.println(" -f: print details of intent filters");
6896 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006897 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006898 pw.println(" l[ibraries]: list known shared libraries");
6899 pw.println(" f[ibraries]: list device features");
6900 pw.println(" r[esolvers]: dump intent resolvers");
6901 pw.println(" perm[issions]: dump permissions");
6902 pw.println(" prov[iders]: dump content providers");
6903 pw.println(" p[ackages]: dump installed packages");
6904 pw.println(" s[hared-users]: dump shared user IDs");
6905 pw.println(" m[essages]: print collected runtime messages");
6906 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006907 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006908 } else if ("-f".equals(opt)) {
6909 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006910 } else {
6911 pw.println("Unknown argument: " + opt + "; use -h for help");
6912 }
6913 }
6914
6915 // Is the caller requesting to dump a particular piece of data?
6916 if (opti < args.length) {
6917 String cmd = args[opti];
6918 opti++;
6919 // Is this a package name?
6920 if ("android".equals(cmd) || cmd.contains(".")) {
6921 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006922 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
6923 dumpStar = false;
6924 dumpLibs = true;
6925 } else if ("f".equals(cmd) || "features".equals(cmd)) {
6926 dumpStar = false;
6927 dumpFeatures = true;
6928 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
6929 dumpStar = false;
6930 dumpResolvers = true;
6931 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
6932 dumpStar = false;
6933 dumpPermissions = true;
6934 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
6935 dumpStar = false;
6936 dumpPackages = true;
6937 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
6938 dumpStar = false;
6939 dumpSharedUsers = true;
6940 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
6941 dumpStar = false;
6942 dumpProviders = true;
6943 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
6944 dumpStar = false;
6945 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006946 }
6947 }
6948
6949 boolean printedTitle = false;
6950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006952 if ((dumpStar || dumpLibs) && packageName == null) {
6953 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006954 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006955 pw.println("Libraries:");
6956 Iterator<String> it = mSharedLibraries.keySet().iterator();
6957 while (it.hasNext()) {
6958 String name = it.next();
6959 pw.print(" ");
6960 pw.print(name);
6961 pw.print(" -> ");
6962 pw.println(mSharedLibraries.get(name));
6963 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006964 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006965
6966 if ((dumpStar || dumpFeatures) && packageName == null) {
6967 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006968 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006969 pw.println("Features:");
6970 Iterator<String> it = mAvailableFeatures.keySet().iterator();
6971 while (it.hasNext()) {
6972 String name = it.next();
6973 pw.print(" ");
6974 pw.println(name);
6975 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006976 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006977
6978 if (dumpStar || dumpResolvers) {
6979 if (mActivities.dump(pw, printedTitle
6980 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
6981 " ", packageName, showFilters)) {
6982 printedTitle = true;
6983 }
6984 if (mReceivers.dump(pw, printedTitle
6985 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6986 " ", packageName, showFilters)) {
6987 printedTitle = true;
6988 }
6989 if (mServices.dump(pw, printedTitle
6990 ? "\nService Resolver Table:" : "Service Resolver Table:",
6991 " ", packageName, showFilters)) {
6992 printedTitle = true;
6993 }
6994 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6995 ? "\nPreferred Activities:" : "Preferred Activities:",
6996 " ", packageName, showFilters)) {
6997 printedTitle = true;
6998 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006999 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007000
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007001 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007002 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007003 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007004 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7005 continue;
7006 }
7007 if (!printedSomething) {
7008 if (printedTitle) pw.println(" ");
7009 pw.println("Permissions:");
7010 printedSomething = true;
7011 printedTitle = true;
7012 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007013 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7014 pw.print(Integer.toHexString(System.identityHashCode(p)));
7015 pw.println("):");
7016 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7017 pw.print(" uid="); pw.print(p.uid);
7018 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007019 pw.print(" type="); pw.print(p.type);
7020 pw.print(" prot="); pw.println(p.protectionLevel);
7021 if (p.packageSetting != null) {
7022 pw.print(" packageSetting="); pw.println(p.packageSetting);
7023 }
7024 if (p.perm != null) {
7025 pw.print(" perm="); pw.println(p.perm);
7026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 }
7028 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007029
7030 if (dumpStar || dumpProviders) {
7031 printedSomething = false;
7032 for (PackageParser.Provider p : mProviders.values()) {
7033 if (packageName != null && !packageName.equals(p.info.packageName)) {
7034 continue;
7035 }
7036 if (!printedSomething) {
7037 if (printedTitle) pw.println(" ");
7038 pw.println("Registered ContentProviders:");
7039 printedSomething = true;
7040 printedTitle = true;
7041 }
7042 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7043 pw.println(p.toString());
7044 }
7045 }
7046
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007047 printedSomething = false;
7048 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007049 if (dumpStar || dumpPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007051 if (packageName != null && !packageName.equals(ps.realName)
7052 && !packageName.equals(ps.name)) {
7053 continue;
7054 }
7055 if (!printedSomething) {
7056 if (printedTitle) pw.println(" ");
7057 pw.println("Packages:");
7058 printedSomething = true;
7059 printedTitle = true;
7060 }
7061 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007062 pw.print(" Package [");
7063 pw.print(ps.realName != null ? ps.realName : ps.name);
7064 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007065 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7066 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007067 if (ps.realName != null) {
7068 pw.print(" compat name="); pw.println(ps.name);
7069 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007070 pw.print(" userId="); pw.print(ps.userId);
7071 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7072 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7073 pw.print(" pkg="); pw.println(ps.pkg);
7074 pw.print(" codePath="); pw.println(ps.codePathString);
7075 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007076 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007077 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007078 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007079 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007080 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007081 if (ps.pkg.mOperationPending) {
7082 pw.println(" mOperationPending=true");
7083 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007084 pw.print(" supportsScreens=[");
7085 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007086 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007087 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7088 if (!first) pw.print(", ");
7089 first = false;
7090 pw.print("small");
7091 }
7092 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007093 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007094 if (!first) pw.print(", ");
7095 first = false;
7096 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007097 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007098 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007099 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007100 if (!first) pw.print(", ");
7101 first = false;
7102 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007103 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007104 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007105 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007106 if (!first) pw.print(", ");
7107 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007108 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007109 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007110 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007111 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007112 if (!first) pw.print(", ");
7113 first = false;
7114 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007115 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007116 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007117 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7118 if (!first) pw.print(", ");
7119 first = false;
7120 pw.print("anyDensity");
7121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007122 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007123 pw.println("]");
Kenny Root7d794fb2010-09-13 16:29:49 -07007124 pw.print(" timeStamp="); pw.println(String.valueOf(ps.timeStamp));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007125 pw.print(" signatures="); pw.println(ps.signatures);
7126 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007127 pw.print(" haveGids="); pw.println(ps.haveGids);
7128 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007129 pw.print(" installStatus="); pw.print(ps.installStatus);
7130 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007131 if (ps.disabledComponents.size() > 0) {
7132 pw.println(" disabledComponents:");
7133 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007134 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007135 }
7136 }
7137 if (ps.enabledComponents.size() > 0) {
7138 pw.println(" enabledComponents:");
7139 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007140 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007141 }
7142 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007143 if (ps.grantedPermissions.size() > 0) {
7144 pw.println(" grantedPermissions:");
7145 for (String s : ps.grantedPermissions) {
7146 pw.print(" "); pw.println(s);
7147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007149 }
7150 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007151 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007152 if (dumpStar || dumpPackages) {
7153 if (mSettings.mRenamedPackages.size() > 0) {
7154 for (HashMap.Entry<String, String> e
7155 : mSettings.mRenamedPackages.entrySet()) {
7156 if (packageName != null && !packageName.equals(e.getKey())
7157 && !packageName.equals(e.getValue())) {
7158 continue;
7159 }
7160 if (!printedSomething) {
7161 if (printedTitle) pw.println(" ");
7162 pw.println("Renamed packages:");
7163 printedSomething = true;
7164 printedTitle = true;
7165 }
7166 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7167 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007168 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007169 }
7170 printedSomething = false;
7171 if (mSettings.mDisabledSysPackages.size() > 0) {
7172 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7173 if (packageName != null && !packageName.equals(ps.realName)
7174 && !packageName.equals(ps.name)) {
7175 continue;
7176 }
7177 if (!printedSomething) {
7178 if (printedTitle) pw.println(" ");
7179 pw.println("Hidden system packages:");
7180 printedSomething = true;
7181 printedTitle = true;
7182 }
7183 pw.print(" Package [");
7184 pw.print(ps.realName != null ? ps.realName : ps.name);
7185 pw.print("] (");
7186 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7187 pw.println("):");
7188 if (ps.realName != null) {
7189 pw.print(" compat name="); pw.println(ps.name);
7190 }
7191 pw.print(" userId="); pw.println(ps.userId);
7192 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7193 pw.print(" codePath="); pw.println(ps.codePathString);
7194 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007195 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007196 }
7197 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007198 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007199 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007200 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007201 if (packageName != null && su != packageSharedUser) {
7202 continue;
7203 }
7204 if (!printedSomething) {
7205 if (printedTitle) pw.println(" ");
7206 pw.println("Shared users:");
7207 printedSomething = true;
7208 printedTitle = true;
7209 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007210 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7211 pw.print(Integer.toHexString(System.identityHashCode(su)));
7212 pw.println("):");
7213 pw.print(" userId="); pw.print(su.userId);
7214 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007215 pw.println(" grantedPermissions:");
7216 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007217 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 }
7220 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007221
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007222 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007223 if (printedTitle) pw.println(" ");
7224 printedTitle = true;
7225 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007226 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007227
7228 pw.println(" ");
7229 pw.println("Package warning messages:");
7230 File fname = getSettingsProblemFile();
7231 FileInputStream in;
7232 try {
7233 in = new FileInputStream(fname);
7234 int avail = in.available();
7235 byte[] data = new byte[avail];
7236 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007237 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007238 } catch (FileNotFoundException e) {
7239 } catch (IOException e) {
7240 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007242 }
7243 }
7244
7245 static final class BasePermission {
7246 final static int TYPE_NORMAL = 0;
7247 final static int TYPE_BUILTIN = 1;
7248 final static int TYPE_DYNAMIC = 2;
7249
7250 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007251 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007252 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007253 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007254 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 PackageParser.Permission perm;
7256 PermissionInfo pendingInfo;
7257 int uid;
7258 int[] gids;
7259
7260 BasePermission(String _name, String _sourcePackage, int _type) {
7261 name = _name;
7262 sourcePackage = _sourcePackage;
7263 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007264 // Default to most conservative protection level.
7265 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7266 }
7267
7268 public String toString() {
7269 return "BasePermission{"
7270 + Integer.toHexString(System.identityHashCode(this))
7271 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007272 }
7273 }
7274
7275 static class PackageSignatures {
7276 private Signature[] mSignatures;
7277
7278 PackageSignatures(Signature[] sigs) {
7279 assignSignatures(sigs);
7280 }
7281
7282 PackageSignatures() {
7283 }
7284
7285 void writeXml(XmlSerializer serializer, String tagName,
7286 ArrayList<Signature> pastSignatures) throws IOException {
7287 if (mSignatures == null) {
7288 return;
7289 }
7290 serializer.startTag(null, tagName);
7291 serializer.attribute(null, "count",
7292 Integer.toString(mSignatures.length));
7293 for (int i=0; i<mSignatures.length; i++) {
7294 serializer.startTag(null, "cert");
7295 final Signature sig = mSignatures[i];
7296 final int sigHash = sig.hashCode();
7297 final int numPast = pastSignatures.size();
7298 int j;
7299 for (j=0; j<numPast; j++) {
7300 Signature pastSig = pastSignatures.get(j);
7301 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7302 serializer.attribute(null, "index", Integer.toString(j));
7303 break;
7304 }
7305 }
7306 if (j >= numPast) {
7307 pastSignatures.add(sig);
7308 serializer.attribute(null, "index", Integer.toString(numPast));
7309 serializer.attribute(null, "key", sig.toCharsString());
7310 }
7311 serializer.endTag(null, "cert");
7312 }
7313 serializer.endTag(null, tagName);
7314 }
7315
7316 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7317 throws IOException, XmlPullParserException {
7318 String countStr = parser.getAttributeValue(null, "count");
7319 if (countStr == null) {
7320 reportSettingsProblem(Log.WARN,
7321 "Error in package manager settings: <signatures> has"
7322 + " no count at " + parser.getPositionDescription());
7323 XmlUtils.skipCurrentTag(parser);
7324 }
7325 final int count = Integer.parseInt(countStr);
7326 mSignatures = new Signature[count];
7327 int pos = 0;
7328
7329 int outerDepth = parser.getDepth();
7330 int type;
7331 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7332 && (type != XmlPullParser.END_TAG
7333 || parser.getDepth() > outerDepth)) {
7334 if (type == XmlPullParser.END_TAG
7335 || type == XmlPullParser.TEXT) {
7336 continue;
7337 }
7338
7339 String tagName = parser.getName();
7340 if (tagName.equals("cert")) {
7341 if (pos < count) {
7342 String index = parser.getAttributeValue(null, "index");
7343 if (index != null) {
7344 try {
7345 int idx = Integer.parseInt(index);
7346 String key = parser.getAttributeValue(null, "key");
7347 if (key == null) {
7348 if (idx >= 0 && idx < pastSignatures.size()) {
7349 Signature sig = pastSignatures.get(idx);
7350 if (sig != null) {
7351 mSignatures[pos] = pastSignatures.get(idx);
7352 pos++;
7353 } else {
7354 reportSettingsProblem(Log.WARN,
7355 "Error in package manager settings: <cert> "
7356 + "index " + index + " is not defined at "
7357 + parser.getPositionDescription());
7358 }
7359 } else {
7360 reportSettingsProblem(Log.WARN,
7361 "Error in package manager settings: <cert> "
7362 + "index " + index + " is out of bounds at "
7363 + parser.getPositionDescription());
7364 }
7365 } else {
7366 while (pastSignatures.size() <= idx) {
7367 pastSignatures.add(null);
7368 }
7369 Signature sig = new Signature(key);
7370 pastSignatures.set(idx, sig);
7371 mSignatures[pos] = sig;
7372 pos++;
7373 }
7374 } catch (NumberFormatException e) {
7375 reportSettingsProblem(Log.WARN,
7376 "Error in package manager settings: <cert> "
7377 + "index " + index + " is not a number at "
7378 + parser.getPositionDescription());
7379 }
7380 } else {
7381 reportSettingsProblem(Log.WARN,
7382 "Error in package manager settings: <cert> has"
7383 + " no index at " + parser.getPositionDescription());
7384 }
7385 } else {
7386 reportSettingsProblem(Log.WARN,
7387 "Error in package manager settings: too "
7388 + "many <cert> tags, expected " + count
7389 + " at " + parser.getPositionDescription());
7390 }
7391 } else {
7392 reportSettingsProblem(Log.WARN,
7393 "Unknown element under <cert>: "
7394 + parser.getName());
7395 }
7396 XmlUtils.skipCurrentTag(parser);
7397 }
7398
7399 if (pos < count) {
7400 // Should never happen -- there is an error in the written
7401 // settings -- but if it does we don't want to generate
7402 // a bad array.
7403 Signature[] newSigs = new Signature[pos];
7404 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7405 mSignatures = newSigs;
7406 }
7407 }
7408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007409 private void assignSignatures(Signature[] sigs) {
7410 if (sigs == null) {
7411 mSignatures = null;
7412 return;
7413 }
7414 mSignatures = new Signature[sigs.length];
7415 for (int i=0; i<sigs.length; i++) {
7416 mSignatures[i] = sigs[i];
7417 }
7418 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007420 @Override
7421 public String toString() {
7422 StringBuffer buf = new StringBuffer(128);
7423 buf.append("PackageSignatures{");
7424 buf.append(Integer.toHexString(System.identityHashCode(this)));
7425 buf.append(" [");
7426 if (mSignatures != null) {
7427 for (int i=0; i<mSignatures.length; i++) {
7428 if (i > 0) buf.append(", ");
7429 buf.append(Integer.toHexString(
7430 System.identityHashCode(mSignatures[i])));
7431 }
7432 }
7433 buf.append("]}");
7434 return buf.toString();
7435 }
7436 }
7437
7438 static class PreferredActivity extends IntentFilter {
7439 final int mMatch;
7440 final String[] mSetPackages;
7441 final String[] mSetClasses;
7442 final String[] mSetComponents;
7443 final ComponentName mActivity;
7444 final String mShortActivity;
7445 String mParseError;
7446
7447 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7448 ComponentName activity) {
7449 super(filter);
7450 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7451 mActivity = activity;
7452 mShortActivity = activity.flattenToShortString();
7453 mParseError = null;
7454 if (set != null) {
7455 final int N = set.length;
7456 String[] myPackages = new String[N];
7457 String[] myClasses = new String[N];
7458 String[] myComponents = new String[N];
7459 for (int i=0; i<N; i++) {
7460 ComponentName cn = set[i];
7461 if (cn == null) {
7462 mSetPackages = null;
7463 mSetClasses = null;
7464 mSetComponents = null;
7465 return;
7466 }
7467 myPackages[i] = cn.getPackageName().intern();
7468 myClasses[i] = cn.getClassName().intern();
7469 myComponents[i] = cn.flattenToShortString().intern();
7470 }
7471 mSetPackages = myPackages;
7472 mSetClasses = myClasses;
7473 mSetComponents = myComponents;
7474 } else {
7475 mSetPackages = null;
7476 mSetClasses = null;
7477 mSetComponents = null;
7478 }
7479 }
7480
7481 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7482 IOException {
7483 mShortActivity = parser.getAttributeValue(null, "name");
7484 mActivity = ComponentName.unflattenFromString(mShortActivity);
7485 if (mActivity == null) {
7486 mParseError = "Bad activity name " + mShortActivity;
7487 }
7488 String matchStr = parser.getAttributeValue(null, "match");
7489 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7490 String setCountStr = parser.getAttributeValue(null, "set");
7491 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7492
7493 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7494 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7495 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7496
7497 int setPos = 0;
7498
7499 int outerDepth = parser.getDepth();
7500 int type;
7501 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7502 && (type != XmlPullParser.END_TAG
7503 || parser.getDepth() > outerDepth)) {
7504 if (type == XmlPullParser.END_TAG
7505 || type == XmlPullParser.TEXT) {
7506 continue;
7507 }
7508
7509 String tagName = parser.getName();
7510 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7511 // + parser.getDepth() + " tag=" + tagName);
7512 if (tagName.equals("set")) {
7513 String name = parser.getAttributeValue(null, "name");
7514 if (name == null) {
7515 if (mParseError == null) {
7516 mParseError = "No name in set tag in preferred activity "
7517 + mShortActivity;
7518 }
7519 } else if (setPos >= setCount) {
7520 if (mParseError == null) {
7521 mParseError = "Too many set tags in preferred activity "
7522 + mShortActivity;
7523 }
7524 } else {
7525 ComponentName cn = ComponentName.unflattenFromString(name);
7526 if (cn == null) {
7527 if (mParseError == null) {
7528 mParseError = "Bad set name " + name + " in preferred activity "
7529 + mShortActivity;
7530 }
7531 } else {
7532 myPackages[setPos] = cn.getPackageName();
7533 myClasses[setPos] = cn.getClassName();
7534 myComponents[setPos] = name;
7535 setPos++;
7536 }
7537 }
7538 XmlUtils.skipCurrentTag(parser);
7539 } else if (tagName.equals("filter")) {
7540 //Log.i(TAG, "Starting to parse filter...");
7541 readFromXml(parser);
7542 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7543 // + parser.getDepth() + " tag=" + parser.getName());
7544 } else {
7545 reportSettingsProblem(Log.WARN,
7546 "Unknown element under <preferred-activities>: "
7547 + parser.getName());
7548 XmlUtils.skipCurrentTag(parser);
7549 }
7550 }
7551
7552 if (setPos != setCount) {
7553 if (mParseError == null) {
7554 mParseError = "Not enough set tags (expected " + setCount
7555 + " but found " + setPos + ") in " + mShortActivity;
7556 }
7557 }
7558
7559 mSetPackages = myPackages;
7560 mSetClasses = myClasses;
7561 mSetComponents = myComponents;
7562 }
7563
7564 public void writeToXml(XmlSerializer serializer) throws IOException {
7565 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7566 serializer.attribute(null, "name", mShortActivity);
7567 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7568 serializer.attribute(null, "set", Integer.toString(NS));
7569 for (int s=0; s<NS; s++) {
7570 serializer.startTag(null, "set");
7571 serializer.attribute(null, "name", mSetComponents[s]);
7572 serializer.endTag(null, "set");
7573 }
7574 serializer.startTag(null, "filter");
7575 super.writeToXml(serializer);
7576 serializer.endTag(null, "filter");
7577 }
7578
7579 boolean sameSet(List<ResolveInfo> query, int priority) {
7580 if (mSetPackages == null) return false;
7581 final int NQ = query.size();
7582 final int NS = mSetPackages.length;
7583 int numMatch = 0;
7584 for (int i=0; i<NQ; i++) {
7585 ResolveInfo ri = query.get(i);
7586 if (ri.priority != priority) continue;
7587 ActivityInfo ai = ri.activityInfo;
7588 boolean good = false;
7589 for (int j=0; j<NS; j++) {
7590 if (mSetPackages[j].equals(ai.packageName)
7591 && mSetClasses[j].equals(ai.name)) {
7592 numMatch++;
7593 good = true;
7594 break;
7595 }
7596 }
7597 if (!good) return false;
7598 }
7599 return numMatch == NS;
7600 }
7601 }
7602
7603 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007604 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007606 HashSet<String> grantedPermissions = new HashSet<String>();
7607 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007609 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007610 setFlags(pkgFlags);
7611 }
7612
7613 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007614 this.pkgFlags = pkgFlags & (
7615 ApplicationInfo.FLAG_SYSTEM |
7616 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007617 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007618 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007619 }
7620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007622 /**
7623 * Settings base class for pending and resolved classes.
7624 */
7625 static class PackageSettingBase extends GrantedPermissions {
7626 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007627 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007628 File codePath;
7629 String codePathString;
7630 File resourcePath;
7631 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007632 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007633 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007634 long timeStamp;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007635 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007637 boolean uidError;
7638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007639 PackageSignatures signatures = new PackageSignatures();
7640
7641 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007642 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007644 /* Explicitly disabled components */
7645 HashSet<String> disabledComponents = new HashSet<String>(0);
7646 /* Explicitly enabled components */
7647 HashSet<String> enabledComponents = new HashSet<String>(0);
7648 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7649 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007650
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007651 PackageSettingBase origPackage;
7652
Jacek Surazski65e13172009-04-28 15:26:38 +02007653 /* package name of the app that installed this package */
7654 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007655
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007656 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007657 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007658 super(pkgFlags);
7659 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007660 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007661 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007662 }
7663
Kenny Root806cc132010-09-12 08:34:19 -07007664 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7665 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007666 this.codePath = codePath;
7667 this.codePathString = codePath.toString();
7668 this.resourcePath = resourcePath;
7669 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007670 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007671 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007672 }
Kenny Root85387d72010-08-26 10:13:11 -07007673
Jacek Surazski65e13172009-04-28 15:26:38 +02007674 public void setInstallerPackageName(String packageName) {
7675 installerPackageName = packageName;
7676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007677
Jacek Surazski65e13172009-04-28 15:26:38 +02007678 String getInstallerPackageName() {
7679 return installerPackageName;
7680 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682 public void setInstallStatus(int newStatus) {
7683 installStatus = newStatus;
7684 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007686 public int getInstallStatus() {
7687 return installStatus;
7688 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007691 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 }
7693
7694 public void copyFrom(PackageSettingBase base) {
7695 grantedPermissions = base.grantedPermissions;
7696 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007698 timeStamp = base.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007699 signatures = base.signatures;
7700 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007701 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007702 disabledComponents = base.disabledComponents;
7703 enabledComponents = base.enabledComponents;
7704 enabled = base.enabled;
7705 installStatus = base.installStatus;
7706 }
7707
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007708 boolean enableComponentLP(String componentClassName) {
7709 boolean changed = disabledComponents.remove(componentClassName);
7710 changed |= enabledComponents.add(componentClassName);
7711 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 }
7713
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007714 boolean disableComponentLP(String componentClassName) {
7715 boolean changed = enabledComponents.remove(componentClassName);
7716 changed |= disabledComponents.add(componentClassName);
7717 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 }
7719
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007720 boolean restoreComponentLP(String componentClassName) {
7721 boolean changed = enabledComponents.remove(componentClassName);
7722 changed |= disabledComponents.remove(componentClassName);
7723 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007724 }
7725
7726 int currentEnabledStateLP(String componentName) {
7727 if (enabledComponents.contains(componentName)) {
7728 return COMPONENT_ENABLED_STATE_ENABLED;
7729 } else if (disabledComponents.contains(componentName)) {
7730 return COMPONENT_ENABLED_STATE_DISABLED;
7731 } else {
7732 return COMPONENT_ENABLED_STATE_DEFAULT;
7733 }
7734 }
7735 }
7736
7737 /**
7738 * Settings data for a particular package we know about.
7739 */
7740 static final class PackageSetting extends PackageSettingBase {
7741 int userId;
7742 PackageParser.Package pkg;
7743 SharedUserSetting sharedUser;
7744
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007745 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007746 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7747 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7748 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007749 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007751 @Override
7752 public String toString() {
7753 return "PackageSetting{"
7754 + Integer.toHexString(System.identityHashCode(this))
7755 + " " + name + "/" + userId + "}";
7756 }
7757 }
7758
7759 /**
7760 * Settings data for a particular shared user ID we know about.
7761 */
7762 static final class SharedUserSetting extends GrantedPermissions {
7763 final String name;
7764 int userId;
7765 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7766 final PackageSignatures signatures = new PackageSignatures();
7767
7768 SharedUserSetting(String _name, int _pkgFlags) {
7769 super(_pkgFlags);
7770 name = _name;
7771 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 @Override
7774 public String toString() {
7775 return "SharedUserSetting{"
7776 + Integer.toHexString(System.identityHashCode(this))
7777 + " " + name + "/" + userId + "}";
7778 }
7779 }
7780
7781 /**
7782 * Holds information about dynamic settings.
7783 */
7784 private static final class Settings {
7785 private final File mSettingsFilename;
7786 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007787 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 private final HashMap<String, PackageSetting> mPackages =
7789 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007790 // List of replaced system applications
7791 final HashMap<String, PackageSetting> mDisabledSysPackages =
7792 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007793
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007794 // These are the last platform API version we were using for
7795 // the apps installed on internal and external storage. It is
7796 // used to grant newer permissions one time during a system upgrade.
7797 int mInternalSdkPlatform;
7798 int mExternalSdkPlatform;
7799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 // The user's preferred activities associated with particular intent
7801 // filters.
7802 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7803 new IntentResolver<PreferredActivity, PreferredActivity>() {
7804 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007805 protected String packageForFilter(PreferredActivity filter) {
7806 return filter.mActivity.getPackageName();
7807 }
7808 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007809 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007810 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007811 out.print(prefix); out.print(
7812 Integer.toHexString(System.identityHashCode(filter)));
7813 out.print(' ');
7814 out.print(filter.mActivity.flattenToShortString());
7815 out.print(" match=0x");
7816 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007818 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007819 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007820 out.print(prefix); out.print(" ");
7821 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007822 }
7823 }
7824 }
7825 };
7826 private final HashMap<String, SharedUserSetting> mSharedUsers =
7827 new HashMap<String, SharedUserSetting>();
7828 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7829 private final SparseArray<Object> mOtherUserIds =
7830 new SparseArray<Object>();
7831
7832 // For reading/writing settings file.
7833 private final ArrayList<Signature> mPastSignatures =
7834 new ArrayList<Signature>();
7835
7836 // Mapping from permission names to info about them.
7837 final HashMap<String, BasePermission> mPermissions =
7838 new HashMap<String, BasePermission>();
7839
7840 // Mapping from permission tree names to info about them.
7841 final HashMap<String, BasePermission> mPermissionTrees =
7842 new HashMap<String, BasePermission>();
7843
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007844 // Packages that have been uninstalled and still need their external
7845 // storage data deleted.
7846 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7847
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007848 // Packages that have been renamed since they were first installed.
7849 // Keys are the new names of the packages, values are the original
7850 // names. The packages appear everwhere else under their original
7851 // names.
7852 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007854 private final StringBuilder mReadMessages = new StringBuilder();
7855
7856 private static final class PendingPackage extends PackageSettingBase {
7857 final int sharedId;
7858
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007859 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007860 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7861 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7862 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007863 this.sharedId = sharedId;
7864 }
7865 }
7866 private final ArrayList<PendingPackage> mPendingPackages
7867 = new ArrayList<PendingPackage>();
7868
7869 Settings() {
7870 File dataDir = Environment.getDataDirectory();
7871 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007872 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7873 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007875 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007876 FileUtils.setPermissions(systemDir.toString(),
7877 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7878 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7879 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007880 FileUtils.setPermissions(systemSecureDir.toString(),
7881 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7882 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7883 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 mSettingsFilename = new File(systemDir, "packages.xml");
7885 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007886 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 }
7888
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007889 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007890 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007891 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007893 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007894 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007895 return p;
7896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007897
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007898 PackageSetting peekPackageLP(String name) {
7899 return mPackages.get(name);
7900 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007901 PackageSetting p = mPackages.get(name);
7902 if (p != null && p.codePath.getPath().equals(codePath)) {
7903 return p;
7904 }
7905 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007906 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 void setInstallStatus(String pkgName, int status) {
7910 PackageSetting p = mPackages.get(pkgName);
7911 if(p != null) {
7912 if(p.getInstallStatus() != status) {
7913 p.setInstallStatus(status);
7914 }
7915 }
7916 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007917
Jacek Surazski65e13172009-04-28 15:26:38 +02007918 void setInstallerPackageName(String pkgName,
7919 String installerPkgName) {
7920 PackageSetting p = mPackages.get(pkgName);
7921 if(p != null) {
7922 p.setInstallerPackageName(installerPkgName);
7923 }
7924 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007925
Jacek Surazski65e13172009-04-28 15:26:38 +02007926 String getInstallerPackageName(String pkgName) {
7927 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007928 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007929 }
7930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007931 int getInstallStatus(String pkgName) {
7932 PackageSetting p = mPackages.get(pkgName);
7933 if(p != null) {
7934 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 return -1;
7937 }
7938
7939 SharedUserSetting getSharedUserLP(String name,
7940 int pkgFlags, boolean create) {
7941 SharedUserSetting s = mSharedUsers.get(name);
7942 if (s == null) {
7943 if (!create) {
7944 return null;
7945 }
7946 s = new SharedUserSetting(name, pkgFlags);
7947 if (MULTIPLE_APPLICATION_UIDS) {
7948 s.userId = newUserIdLP(s);
7949 } else {
7950 s.userId = FIRST_APPLICATION_UID;
7951 }
7952 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7953 // < 0 means we couldn't assign a userid; fall out and return
7954 // s, which is currently null
7955 if (s.userId >= 0) {
7956 mSharedUsers.put(name, s);
7957 }
7958 }
7959
7960 return s;
7961 }
7962
7963 int disableSystemPackageLP(String name) {
7964 PackageSetting p = mPackages.get(name);
7965 if(p == null) {
7966 Log.w(TAG, "Package:"+name+" is not an installed package");
7967 return -1;
7968 }
7969 PackageSetting dp = mDisabledSysPackages.get(name);
7970 // always make sure the system package code and resource paths dont change
7971 if(dp == null) {
7972 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7973 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7974 }
7975 mDisabledSysPackages.put(name, p);
7976 }
7977 return removePackageLP(name);
7978 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 PackageSetting enableSystemPackageLP(String name) {
7981 PackageSetting p = mDisabledSysPackages.get(name);
7982 if(p == null) {
7983 Log.w(TAG, "Package:"+name+" is not disabled");
7984 return null;
7985 }
7986 // Reset flag in ApplicationInfo object
7987 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7988 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7989 }
Kenny Root806cc132010-09-12 08:34:19 -07007990 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
7991 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992 mDisabledSysPackages.remove(name);
7993 return ret;
7994 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007995
Kenny Root806cc132010-09-12 08:34:19 -07007996 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
7997 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 PackageSetting p = mPackages.get(name);
7999 if (p != null) {
8000 if (p.userId == uid) {
8001 return p;
8002 }
8003 reportSettingsProblem(Log.ERROR,
8004 "Adding duplicate package, keeping first: " + name);
8005 return null;
8006 }
Kenny Root806cc132010-09-12 08:34:19 -07008007 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8008 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008009 p.userId = uid;
8010 if (addUserIdLP(uid, p, name)) {
8011 mPackages.put(name, p);
8012 return p;
8013 }
8014 return null;
8015 }
8016
8017 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8018 SharedUserSetting s = mSharedUsers.get(name);
8019 if (s != null) {
8020 if (s.userId == uid) {
8021 return s;
8022 }
8023 reportSettingsProblem(Log.ERROR,
8024 "Adding duplicate shared user, keeping first: " + name);
8025 return null;
8026 }
8027 s = new SharedUserSetting(name, pkgFlags);
8028 s.userId = uid;
8029 if (addUserIdLP(uid, s, name)) {
8030 mSharedUsers.put(name, s);
8031 return s;
8032 }
8033 return null;
8034 }
8035
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008036 // Transfer ownership of permissions from one package to another.
8037 private void transferPermissions(String origPkg, String newPkg) {
8038 // Transfer ownership of permissions to the new package.
8039 for (int i=0; i<2; i++) {
8040 HashMap<String, BasePermission> permissions =
8041 i == 0 ? mPermissionTrees : mPermissions;
8042 for (BasePermission bp : permissions.values()) {
8043 if (origPkg.equals(bp.sourcePackage)) {
8044 if (DEBUG_UPGRADE) Log.v(TAG,
8045 "Moving permission " + bp.name
8046 + " from pkg " + bp.sourcePackage
8047 + " to " + newPkg);
8048 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008049 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008050 bp.perm = null;
8051 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008052 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008053 }
8054 bp.uid = 0;
8055 bp.gids = null;
8056 }
8057 }
8058 }
8059 }
8060
8061 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008062 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008063 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 PackageSetting p = mPackages.get(name);
8065 if (p != null) {
8066 if (!p.codePath.equals(codePath)) {
8067 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008068 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008069 // This is an updated system app with versions in both system
8070 // and data partition. Just let the most recent version
8071 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008072 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008073 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008074 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008075 // Just a change in the code path is not an issue, but
8076 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008077 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008078 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008079 /*
8080 * Since we've changed paths, we need to prefer the new
8081 * native library path over the one stored in the
8082 * package settings since we might have moved from
8083 * internal to external storage or vice versa.
8084 */
8085 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008086 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008087 }
8088 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 reportSettingsProblem(Log.WARN,
8090 "Package " + name + " shared user changed from "
8091 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8092 + " to "
8093 + (sharedUser != null ? sharedUser.name : "<nothing>")
8094 + "; replacing with new");
8095 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008096 } else {
8097 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8098 // If what we are scanning is a system package, then
8099 // make it so, regardless of whether it was previously
8100 // installed only in the data partition.
8101 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008103 }
8104 }
8105 if (p == null) {
8106 // Create a new PackageSettings entry. this can end up here because
8107 // of code path mismatch or user id mismatch of an updated system partition
8108 if (!create) {
8109 return null;
8110 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008111 if (origPackage != null) {
8112 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008113 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8114 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008115 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8116 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008117 // Note that we will retain the new package's signature so
8118 // that we can keep its data.
8119 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008120 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008121 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008122 p.sharedUser = origPackage.sharedUser;
8123 p.userId = origPackage.userId;
8124 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008125 mRenamedPackages.put(name, origPackage.name);
8126 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008127 // Update new package state.
8128 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008129 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008130 p = new PackageSetting(name, realName, codePath, resourcePath,
8131 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008132 p.setTimeStamp(codePath.lastModified());
8133 p.sharedUser = sharedUser;
8134 if (sharedUser != null) {
8135 p.userId = sharedUser.userId;
8136 } else if (MULTIPLE_APPLICATION_UIDS) {
8137 // Clone the setting here for disabled system packages
8138 PackageSetting dis = mDisabledSysPackages.get(name);
8139 if (dis != null) {
8140 // For disabled packages a new setting is created
8141 // from the existing user id. This still has to be
8142 // added to list of user id's
8143 // Copy signatures from previous setting
8144 if (dis.signatures.mSignatures != null) {
8145 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8146 }
8147 p.userId = dis.userId;
8148 // Clone permissions
8149 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008150 // Clone component info
8151 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8152 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8153 // Add new setting to list of user ids
8154 addUserIdLP(p.userId, p, name);
8155 } else {
8156 // Assign new user id
8157 p.userId = newUserIdLP(p);
8158 }
8159 } else {
8160 p.userId = FIRST_APPLICATION_UID;
8161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008162 }
8163 if (p.userId < 0) {
8164 reportSettingsProblem(Log.WARN,
8165 "Package " + name + " could not be assigned a valid uid");
8166 return null;
8167 }
8168 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008169 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008170 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008171 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008172 }
8173 }
8174 return p;
8175 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008176
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008177 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008178 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008179 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008180 final String codePath = pkg.applicationInfo.sourceDir;
8181 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008182 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008183 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008184 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008185 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008186 p.codePath = new File(codePath);
8187 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008188 }
8189 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008190 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008191 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008192 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008193 p.resourcePath = new File(resourcePath);
8194 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008195 }
Kenny Root85387d72010-08-26 10:13:11 -07008196 // Update the native library path if needed
8197 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8198 if (nativeLibraryPath != null
8199 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8200 p.nativeLibraryPathString = nativeLibraryPath;
8201 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008202 // Update version code if needed
8203 if (pkg.mVersionCode != p.versionCode) {
8204 p.versionCode = pkg.mVersionCode;
8205 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008206 // Update signatures if needed.
8207 if (p.signatures.mSignatures == null) {
8208 p.signatures.assignSignatures(pkg.mSignatures);
8209 }
8210 // If this app defines a shared user id initialize
8211 // the shared user signatures as well.
8212 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8213 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8214 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008215 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8216 }
8217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008218 // Utility method that adds a PackageSetting to mPackages and
8219 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008220 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008221 SharedUserSetting sharedUser) {
8222 mPackages.put(name, p);
8223 if (sharedUser != null) {
8224 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8225 reportSettingsProblem(Log.ERROR,
8226 "Package " + p.name + " was user "
8227 + p.sharedUser + " but is now " + sharedUser
8228 + "; I am not changing its files so it will probably fail!");
8229 p.sharedUser.packages.remove(p);
8230 } else if (p.userId != sharedUser.userId) {
8231 reportSettingsProblem(Log.ERROR,
8232 "Package " + p.name + " was user id " + p.userId
8233 + " but is now user " + sharedUser
8234 + " with id " + sharedUser.userId
8235 + "; I am not changing its files so it will probably fail!");
8236 }
8237
8238 sharedUser.packages.add(p);
8239 p.sharedUser = sharedUser;
8240 p.userId = sharedUser.userId;
8241 }
8242 }
8243
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008244 /*
8245 * Update the shared user setting when a package using
8246 * specifying the shared user id is removed. The gids
8247 * associated with each permission of the deleted package
8248 * are removed from the shared user's gid list only if its
8249 * not in use by other permissions of packages in the
8250 * shared user setting.
8251 */
8252 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008253 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008254 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008255 return;
8256 }
8257 // No sharedUserId
8258 if (deletedPs.sharedUser == null) {
8259 return;
8260 }
8261 SharedUserSetting sus = deletedPs.sharedUser;
8262 // Update permissions
8263 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8264 boolean used = false;
8265 if (!sus.grantedPermissions.contains (eachPerm)) {
8266 continue;
8267 }
8268 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008269 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008270 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008271 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008272 used = true;
8273 break;
8274 }
8275 }
8276 if (!used) {
8277 // can safely delete this permission from list
8278 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008279 }
8280 }
8281 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008282 int newGids[] = globalGids;
8283 for (String eachPerm : sus.grantedPermissions) {
8284 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008285 if (bp != null) {
8286 newGids = appendInts(newGids, bp.gids);
8287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008288 }
8289 sus.gids = newGids;
8290 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008292 private int removePackageLP(String name) {
8293 PackageSetting p = mPackages.get(name);
8294 if (p != null) {
8295 mPackages.remove(name);
8296 if (p.sharedUser != null) {
8297 p.sharedUser.packages.remove(p);
8298 if (p.sharedUser.packages.size() == 0) {
8299 mSharedUsers.remove(p.sharedUser.name);
8300 removeUserIdLP(p.sharedUser.userId);
8301 return p.sharedUser.userId;
8302 }
8303 } else {
8304 removeUserIdLP(p.userId);
8305 return p.userId;
8306 }
8307 }
8308 return -1;
8309 }
8310
8311 private boolean addUserIdLP(int uid, Object obj, Object name) {
8312 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8313 return false;
8314 }
8315
8316 if (uid >= FIRST_APPLICATION_UID) {
8317 int N = mUserIds.size();
8318 final int index = uid - FIRST_APPLICATION_UID;
8319 while (index >= N) {
8320 mUserIds.add(null);
8321 N++;
8322 }
8323 if (mUserIds.get(index) != null) {
8324 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008325 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008326 + " name=" + name);
8327 return false;
8328 }
8329 mUserIds.set(index, obj);
8330 } else {
8331 if (mOtherUserIds.get(uid) != null) {
8332 reportSettingsProblem(Log.ERROR,
8333 "Adding duplicate shared id: " + uid
8334 + " name=" + name);
8335 return false;
8336 }
8337 mOtherUserIds.put(uid, obj);
8338 }
8339 return true;
8340 }
8341
8342 public Object getUserIdLP(int uid) {
8343 if (uid >= FIRST_APPLICATION_UID) {
8344 int N = mUserIds.size();
8345 final int index = uid - FIRST_APPLICATION_UID;
8346 return index < N ? mUserIds.get(index) : null;
8347 } else {
8348 return mOtherUserIds.get(uid);
8349 }
8350 }
8351
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008352 private Set<String> findPackagesWithFlag(int flag) {
8353 Set<String> ret = new HashSet<String>();
8354 for (PackageSetting ps : mPackages.values()) {
8355 // Has to match atleast all the flag bits set on flag
8356 if ((ps.pkgFlags & flag) == flag) {
8357 ret.add(ps.name);
8358 }
8359 }
8360 return ret;
8361 }
8362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008363 private void removeUserIdLP(int uid) {
8364 if (uid >= FIRST_APPLICATION_UID) {
8365 int N = mUserIds.size();
8366 final int index = uid - FIRST_APPLICATION_UID;
8367 if (index < N) mUserIds.set(index, null);
8368 } else {
8369 mOtherUserIds.remove(uid);
8370 }
8371 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008373 void writeLP() {
8374 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8375
8376 // Keep the old settings around until we know the new ones have
8377 // been successfully written.
8378 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008379 // Presence of backup settings file indicates that we failed
8380 // to persist settings earlier. So preserve the older
8381 // backup for future reference since the current settings
8382 // might have been corrupted.
8383 if (!mBackupSettingsFilename.exists()) {
8384 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008385 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008386 return;
8387 }
8388 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008389 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008390 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008392 }
8393
8394 mPastSignatures.clear();
8395
8396 try {
Kenny Root9f306d72010-09-26 11:19:47 -07008397 BufferedOutputStream str = new BufferedOutputStream(new FileOutputStream(
8398 mSettingsFilename));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008399
8400 //XmlSerializer serializer = XmlUtils.serializerInstance();
8401 XmlSerializer serializer = new FastXmlSerializer();
8402 serializer.setOutput(str, "utf-8");
8403 serializer.startDocument(null, true);
8404 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8405
8406 serializer.startTag(null, "packages");
8407
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008408 serializer.startTag(null, "last-platform-version");
8409 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8410 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8411 serializer.endTag(null, "last-platform-version");
8412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008413 serializer.startTag(null, "permission-trees");
8414 for (BasePermission bp : mPermissionTrees.values()) {
8415 writePermission(serializer, bp);
8416 }
8417 serializer.endTag(null, "permission-trees");
8418
8419 serializer.startTag(null, "permissions");
8420 for (BasePermission bp : mPermissions.values()) {
8421 writePermission(serializer, bp);
8422 }
8423 serializer.endTag(null, "permissions");
8424
8425 for (PackageSetting pkg : mPackages.values()) {
8426 writePackage(serializer, pkg);
8427 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008429 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8430 writeDisabledSysPackage(serializer, pkg);
8431 }
8432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008433 serializer.startTag(null, "preferred-activities");
8434 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8435 serializer.startTag(null, "item");
8436 pa.writeToXml(serializer);
8437 serializer.endTag(null, "item");
8438 }
8439 serializer.endTag(null, "preferred-activities");
8440
8441 for (SharedUserSetting usr : mSharedUsers.values()) {
8442 serializer.startTag(null, "shared-user");
8443 serializer.attribute(null, "name", usr.name);
8444 serializer.attribute(null, "userId",
8445 Integer.toString(usr.userId));
8446 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8447 serializer.startTag(null, "perms");
8448 for (String name : usr.grantedPermissions) {
8449 serializer.startTag(null, "item");
8450 serializer.attribute(null, "name", name);
8451 serializer.endTag(null, "item");
8452 }
8453 serializer.endTag(null, "perms");
8454 serializer.endTag(null, "shared-user");
8455 }
8456
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008457 if (mPackagesToBeCleaned.size() > 0) {
8458 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8459 serializer.startTag(null, "cleaning-package");
8460 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8461 serializer.endTag(null, "cleaning-package");
8462 }
8463 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008464
8465 if (mRenamedPackages.size() > 0) {
8466 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8467 serializer.startTag(null, "renamed-package");
8468 serializer.attribute(null, "new", e.getKey());
8469 serializer.attribute(null, "old", e.getValue());
8470 serializer.endTag(null, "renamed-package");
8471 }
8472 }
8473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008474 serializer.endTag(null, "packages");
8475
8476 serializer.endDocument();
8477
8478 str.flush();
8479 str.close();
8480
8481 // New settings successfully written, old ones are no longer
8482 // needed.
8483 mBackupSettingsFilename.delete();
8484 FileUtils.setPermissions(mSettingsFilename.toString(),
8485 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8486 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8487 |FileUtils.S_IROTH,
8488 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008489
8490 // Write package list file now, use a JournaledFile.
8491 //
8492 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8493 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8494
Kenny Root9f306d72010-09-26 11:19:47 -07008495 str = new BufferedOutputStream(new FileOutputStream(journal.chooseForWrite()));
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008496 try {
8497 StringBuilder sb = new StringBuilder();
8498 for (PackageSetting pkg : mPackages.values()) {
8499 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008500 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008501 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8502
8503 // Avoid any application that has a space in its path
8504 // or that is handled by the system.
8505 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8506 continue;
8507
8508 // we store on each line the following information for now:
8509 //
8510 // pkgName - package name
8511 // userId - application-specific user id
8512 // debugFlag - 0 or 1 if the package is debuggable.
8513 // dataPath - path to package's data path
8514 //
8515 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8516 //
8517 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8518 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8519 // system/core/run-as/run-as.c
8520 //
8521 sb.setLength(0);
8522 sb.append(ai.packageName);
8523 sb.append(" ");
8524 sb.append((int)ai.uid);
8525 sb.append(isDebug ? " 1 " : " 0 ");
8526 sb.append(dataPath);
8527 sb.append("\n");
8528 str.write(sb.toString().getBytes());
8529 }
8530 str.flush();
8531 str.close();
8532 journal.commit();
8533 }
8534 catch (Exception e) {
8535 journal.rollback();
8536 }
8537
8538 FileUtils.setPermissions(mPackageListFilename.toString(),
8539 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8540 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8541 |FileUtils.S_IROTH,
8542 -1, -1);
8543
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008544 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008545
8546 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008547 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 -08008548 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008549 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 -08008550 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008551 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008552 if (mSettingsFilename.exists()) {
8553 if (!mSettingsFilename.delete()) {
8554 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8555 }
8556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008557 //Debug.stopMethodTracing();
8558 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008559
8560 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008561 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008562 serializer.startTag(null, "updated-package");
8563 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008564 if (pkg.realName != null) {
8565 serializer.attribute(null, "realName", pkg.realName);
8566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008567 serializer.attribute(null, "codePath", pkg.codePathString);
Kenny Root7d794fb2010-09-13 16:29:49 -07008568 serializer.attribute(null, "ts", String.valueOf(pkg.timeStamp));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008569 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008570 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8571 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8572 }
Kenny Root85387d72010-08-26 10:13:11 -07008573 if (pkg.nativeLibraryPathString != null) {
8574 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008576 if (pkg.sharedUser == null) {
8577 serializer.attribute(null, "userId",
8578 Integer.toString(pkg.userId));
8579 } else {
8580 serializer.attribute(null, "sharedUserId",
8581 Integer.toString(pkg.userId));
8582 }
8583 serializer.startTag(null, "perms");
8584 if (pkg.sharedUser == null) {
8585 // If this is a shared user, the permissions will
8586 // be written there. We still need to write an
8587 // empty permissions list so permissionsFixed will
8588 // be set.
8589 for (final String name : pkg.grantedPermissions) {
8590 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008591 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 // We only need to write signature or system permissions but this wont
8593 // match the semantics of grantedPermissions. So write all permissions.
8594 serializer.startTag(null, "item");
8595 serializer.attribute(null, "name", name);
8596 serializer.endTag(null, "item");
8597 }
8598 }
8599 }
8600 serializer.endTag(null, "perms");
8601 serializer.endTag(null, "updated-package");
8602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008603
8604 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008605 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008606 serializer.startTag(null, "package");
8607 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008608 if (pkg.realName != null) {
8609 serializer.attribute(null, "realName", pkg.realName);
8610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 serializer.attribute(null, "codePath", pkg.codePathString);
8612 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8613 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8614 }
Kenny Root85387d72010-08-26 10:13:11 -07008615 if (pkg.nativeLibraryPathString != null) {
8616 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8617 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008618 serializer.attribute(null, "flags",
8619 Integer.toString(pkg.pkgFlags));
Kenny Root7d794fb2010-09-13 16:29:49 -07008620 serializer.attribute(null, "ts", String.valueOf(pkg.timeStamp));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008621 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 if (pkg.sharedUser == null) {
8623 serializer.attribute(null, "userId",
8624 Integer.toString(pkg.userId));
8625 } else {
8626 serializer.attribute(null, "sharedUserId",
8627 Integer.toString(pkg.userId));
8628 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008629 if (pkg.uidError) {
8630 serializer.attribute(null, "uidError", "true");
8631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008632 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8633 serializer.attribute(null, "enabled",
8634 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8635 ? "true" : "false");
8636 }
8637 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8638 serializer.attribute(null, "installStatus", "false");
8639 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008640 if (pkg.installerPackageName != null) {
8641 serializer.attribute(null, "installer", pkg.installerPackageName);
8642 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008643 if (pkg.obbPathString != null) {
8644 serializer.attribute(null, "obbPath", pkg.obbPathString);
8645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8647 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8648 serializer.startTag(null, "perms");
8649 if (pkg.sharedUser == null) {
8650 // If this is a shared user, the permissions will
8651 // be written there. We still need to write an
8652 // empty permissions list so permissionsFixed will
8653 // be set.
8654 for (final String name : pkg.grantedPermissions) {
8655 serializer.startTag(null, "item");
8656 serializer.attribute(null, "name", name);
8657 serializer.endTag(null, "item");
8658 }
8659 }
8660 serializer.endTag(null, "perms");
8661 }
8662 if (pkg.disabledComponents.size() > 0) {
8663 serializer.startTag(null, "disabled-components");
8664 for (final String name : pkg.disabledComponents) {
8665 serializer.startTag(null, "item");
8666 serializer.attribute(null, "name", name);
8667 serializer.endTag(null, "item");
8668 }
8669 serializer.endTag(null, "disabled-components");
8670 }
8671 if (pkg.enabledComponents.size() > 0) {
8672 serializer.startTag(null, "enabled-components");
8673 for (final String name : pkg.enabledComponents) {
8674 serializer.startTag(null, "item");
8675 serializer.attribute(null, "name", name);
8676 serializer.endTag(null, "item");
8677 }
8678 serializer.endTag(null, "enabled-components");
8679 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008681 serializer.endTag(null, "package");
8682 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684 void writePermission(XmlSerializer serializer, BasePermission bp)
8685 throws XmlPullParserException, java.io.IOException {
8686 if (bp.type != BasePermission.TYPE_BUILTIN
8687 && bp.sourcePackage != null) {
8688 serializer.startTag(null, "item");
8689 serializer.attribute(null, "name", bp.name);
8690 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008691 if (bp.protectionLevel !=
8692 PermissionInfo.PROTECTION_NORMAL) {
8693 serializer.attribute(null, "protection",
8694 Integer.toString(bp.protectionLevel));
8695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 if (DEBUG_SETTINGS) Log.v(TAG,
8697 "Writing perm: name=" + bp.name + " type=" + bp.type);
8698 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8699 PermissionInfo pi = bp.perm != null ? bp.perm.info
8700 : bp.pendingInfo;
8701 if (pi != null) {
8702 serializer.attribute(null, "type", "dynamic");
8703 if (pi.icon != 0) {
8704 serializer.attribute(null, "icon",
8705 Integer.toString(pi.icon));
8706 }
8707 if (pi.nonLocalizedLabel != null) {
8708 serializer.attribute(null, "label",
8709 pi.nonLocalizedLabel.toString());
8710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008711 }
8712 }
8713 serializer.endTag(null, "item");
8714 }
8715 }
8716
8717 String getReadMessagesLP() {
8718 return mReadMessages.toString();
8719 }
8720
Oscar Montemayora8529f62009-11-18 10:14:20 -08008721 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008722 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8723 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008724 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008725 while(its.hasNext()) {
8726 String key = its.next();
8727 PackageSetting ps = mPackages.get(key);
8728 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008729 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008730 }
8731 }
8732 return ret;
8733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008735 boolean readLP() {
8736 FileInputStream str = null;
8737 if (mBackupSettingsFilename.exists()) {
8738 try {
8739 str = new FileInputStream(mBackupSettingsFilename);
8740 mReadMessages.append("Reading from backup settings file\n");
8741 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008742 if (mSettingsFilename.exists()) {
8743 // If both the backup and settings file exist, we
8744 // ignore the settings since it might have been
8745 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008746 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008747 mSettingsFilename.delete();
8748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008749 } catch (java.io.IOException e) {
8750 // We'll try for the normal settings file.
8751 }
8752 }
8753
8754 mPastSignatures.clear();
8755
8756 try {
8757 if (str == null) {
8758 if (!mSettingsFilename.exists()) {
8759 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008760 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008761 return false;
8762 }
8763 str = new FileInputStream(mSettingsFilename);
8764 }
8765 XmlPullParser parser = Xml.newPullParser();
8766 parser.setInput(str, null);
8767
8768 int type;
8769 while ((type=parser.next()) != XmlPullParser.START_TAG
8770 && type != XmlPullParser.END_DOCUMENT) {
8771 ;
8772 }
8773
8774 if (type != XmlPullParser.START_TAG) {
8775 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008776 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008777 return false;
8778 }
8779
8780 int outerDepth = parser.getDepth();
8781 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8782 && (type != XmlPullParser.END_TAG
8783 || parser.getDepth() > outerDepth)) {
8784 if (type == XmlPullParser.END_TAG
8785 || type == XmlPullParser.TEXT) {
8786 continue;
8787 }
8788
8789 String tagName = parser.getName();
8790 if (tagName.equals("package")) {
8791 readPackageLP(parser);
8792 } else if (tagName.equals("permissions")) {
8793 readPermissionsLP(mPermissions, parser);
8794 } else if (tagName.equals("permission-trees")) {
8795 readPermissionsLP(mPermissionTrees, parser);
8796 } else if (tagName.equals("shared-user")) {
8797 readSharedUserLP(parser);
8798 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008799 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008800 } else if (tagName.equals("preferred-activities")) {
8801 readPreferredActivitiesLP(parser);
8802 } else if(tagName.equals("updated-package")) {
8803 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008804 } else if (tagName.equals("cleaning-package")) {
8805 String name = parser.getAttributeValue(null, "name");
8806 if (name != null) {
8807 mPackagesToBeCleaned.add(name);
8808 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008809 } else if (tagName.equals("renamed-package")) {
8810 String nname = parser.getAttributeValue(null, "new");
8811 String oname = parser.getAttributeValue(null, "old");
8812 if (nname != null && oname != null) {
8813 mRenamedPackages.put(nname, oname);
8814 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008815 } else if (tagName.equals("last-platform-version")) {
8816 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8817 try {
8818 String internal = parser.getAttributeValue(null, "internal");
8819 if (internal != null) {
8820 mInternalSdkPlatform = Integer.parseInt(internal);
8821 }
8822 String external = parser.getAttributeValue(null, "external");
8823 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008824 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008825 }
8826 } catch (NumberFormatException e) {
8827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008828 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008829 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008830 + parser.getName());
8831 XmlUtils.skipCurrentTag(parser);
8832 }
8833 }
8834
8835 str.close();
8836
8837 } catch(XmlPullParserException e) {
8838 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008839 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008840
8841 } catch(java.io.IOException e) {
8842 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008843 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008844
8845 }
8846
8847 int N = mPendingPackages.size();
8848 for (int i=0; i<N; i++) {
8849 final PendingPackage pp = mPendingPackages.get(i);
8850 Object idObj = getUserIdLP(pp.sharedId);
8851 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008852 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008853 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8854 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008855 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008856 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008857 + pp.name);
8858 continue;
8859 }
8860 p.copyFrom(pp);
8861 } else if (idObj != null) {
8862 String msg = "Bad package setting: package " + pp.name
8863 + " has shared uid " + pp.sharedId
8864 + " that is not a shared uid\n";
8865 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008866 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008867 } else {
8868 String msg = "Bad package setting: package " + pp.name
8869 + " has shared uid " + pp.sharedId
8870 + " that is not defined\n";
8871 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008872 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008873 }
8874 }
8875 mPendingPackages.clear();
8876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008877 mReadMessages.append("Read completed successfully: "
8878 + mPackages.size() + " packages, "
8879 + mSharedUsers.size() + " shared uids\n");
8880
8881 return true;
8882 }
8883
8884 private int readInt(XmlPullParser parser, String ns, String name,
8885 int defValue) {
8886 String v = parser.getAttributeValue(ns, name);
8887 try {
8888 if (v == null) {
8889 return defValue;
8890 }
8891 return Integer.parseInt(v);
8892 } catch (NumberFormatException e) {
8893 reportSettingsProblem(Log.WARN,
8894 "Error in package manager settings: attribute " +
8895 name + " has bad integer value " + v + " at "
8896 + parser.getPositionDescription());
8897 }
8898 return defValue;
8899 }
8900
8901 private void readPermissionsLP(HashMap<String, BasePermission> out,
8902 XmlPullParser parser)
8903 throws IOException, XmlPullParserException {
8904 int outerDepth = parser.getDepth();
8905 int type;
8906 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8907 && (type != XmlPullParser.END_TAG
8908 || parser.getDepth() > outerDepth)) {
8909 if (type == XmlPullParser.END_TAG
8910 || type == XmlPullParser.TEXT) {
8911 continue;
8912 }
8913
8914 String tagName = parser.getName();
8915 if (tagName.equals("item")) {
8916 String name = parser.getAttributeValue(null, "name");
8917 String sourcePackage = parser.getAttributeValue(null, "package");
8918 String ptype = parser.getAttributeValue(null, "type");
8919 if (name != null && sourcePackage != null) {
8920 boolean dynamic = "dynamic".equals(ptype);
8921 BasePermission bp = new BasePermission(name, sourcePackage,
8922 dynamic
8923 ? BasePermission.TYPE_DYNAMIC
8924 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008925 bp.protectionLevel = readInt(parser, null, "protection",
8926 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927 if (dynamic) {
8928 PermissionInfo pi = new PermissionInfo();
8929 pi.packageName = sourcePackage.intern();
8930 pi.name = name.intern();
8931 pi.icon = readInt(parser, null, "icon", 0);
8932 pi.nonLocalizedLabel = parser.getAttributeValue(
8933 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008934 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935 bp.pendingInfo = pi;
8936 }
8937 out.put(bp.name, bp);
8938 } else {
8939 reportSettingsProblem(Log.WARN,
8940 "Error in package manager settings: permissions has"
8941 + " no name at " + parser.getPositionDescription());
8942 }
8943 } else {
8944 reportSettingsProblem(Log.WARN,
8945 "Unknown element reading permissions: "
8946 + parser.getName() + " at "
8947 + parser.getPositionDescription());
8948 }
8949 XmlUtils.skipCurrentTag(parser);
8950 }
8951 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008953 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008954 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008956 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 String codePathStr = parser.getAttributeValue(null, "codePath");
8958 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07008959 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008960 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008961 resourcePathStr = codePathStr;
8962 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008963 String version = parser.getAttributeValue(null, "version");
8964 int versionCode = 0;
8965 if (version != null) {
8966 try {
8967 versionCode = Integer.parseInt(version);
8968 } catch (NumberFormatException e) {
8969 }
8970 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008972 int pkgFlags = 0;
8973 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07008974 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
8975 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008976 String timeStampStr = parser.getAttributeValue(null, "ts");
8977 if (timeStampStr != null) {
8978 try {
8979 long timeStamp = Long.parseLong(timeStampStr);
Kenny Root7d794fb2010-09-13 16:29:49 -07008980 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008981 } catch (NumberFormatException e) {
8982 }
8983 }
8984 String idStr = parser.getAttributeValue(null, "userId");
8985 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8986 if(ps.userId <= 0) {
8987 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8988 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8989 }
8990 int outerDepth = parser.getDepth();
8991 int type;
8992 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8993 && (type != XmlPullParser.END_TAG
8994 || parser.getDepth() > outerDepth)) {
8995 if (type == XmlPullParser.END_TAG
8996 || type == XmlPullParser.TEXT) {
8997 continue;
8998 }
8999
9000 String tagName = parser.getName();
9001 if (tagName.equals("perms")) {
9002 readGrantedPermissionsLP(parser,
9003 ps.grantedPermissions);
9004 } else {
9005 reportSettingsProblem(Log.WARN,
9006 "Unknown element under <updated-package>: "
9007 + parser.getName());
9008 XmlUtils.skipCurrentTag(parser);
9009 }
9010 }
9011 mDisabledSysPackages.put(name, ps);
9012 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009014 private void readPackageLP(XmlPullParser parser)
9015 throws XmlPullParserException, IOException {
9016 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009017 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009018 String idStr = null;
9019 String sharedIdStr = null;
9020 String codePathStr = null;
9021 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009022 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009023 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009024 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009025 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009026 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 long timeStamp = 0;
9029 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009030 String version = null;
9031 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009032 try {
9033 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009034 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009036 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009037 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9038 codePathStr = parser.getAttributeValue(null, "codePath");
9039 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009040 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009041 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009042 version = parser.getAttributeValue(null, "version");
9043 if (version != null) {
9044 try {
9045 versionCode = Integer.parseInt(version);
9046 } catch (NumberFormatException e) {
9047 }
9048 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009049 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009050
9051 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009052 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009053 try {
9054 pkgFlags = Integer.parseInt(systemStr);
9055 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009056 }
9057 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009058 // For backward compatibility
9059 systemStr = parser.getAttributeValue(null, "system");
9060 if (systemStr != null) {
9061 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9062 } else {
9063 // Old settings that don't specify system... just treat
9064 // them as system, good enough.
9065 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009067 }
Kenny Root7d794fb2010-09-13 16:29:49 -07009068 final String timeStampStr = parser.getAttributeValue(null, "ts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009069 if (timeStampStr != null) {
9070 try {
9071 timeStamp = Long.parseLong(timeStampStr);
9072 } catch (NumberFormatException e) {
9073 }
9074 }
9075 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9076 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9077 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9078 if (resourcePathStr == null) {
9079 resourcePathStr = codePathStr;
9080 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009081 if (realName != null) {
9082 realName = realName.intern();
9083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 if (name == null) {
9085 reportSettingsProblem(Log.WARN,
9086 "Error in package manager settings: <package> has no name at "
9087 + parser.getPositionDescription());
9088 } else if (codePathStr == null) {
9089 reportSettingsProblem(Log.WARN,
9090 "Error in package manager settings: <package> has no codePath at "
9091 + parser.getPositionDescription());
9092 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009093 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9094 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9095 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009096 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9097 + ": userId=" + userId + " pkg=" + packageSetting);
9098 if (packageSetting == null) {
9099 reportSettingsProblem(Log.ERROR,
9100 "Failure adding uid " + userId
9101 + " while parsing settings at "
9102 + parser.getPositionDescription());
9103 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009104 packageSetting.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009105 }
9106 } else if (sharedIdStr != null) {
9107 userId = sharedIdStr != null
9108 ? Integer.parseInt(sharedIdStr) : 0;
9109 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009110 packageSetting = new PendingPackage(name.intern(), realName,
9111 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009112 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009113 packageSetting.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009114 mPendingPackages.add((PendingPackage) packageSetting);
9115 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9116 + ": sharedUserId=" + userId + " pkg="
9117 + packageSetting);
9118 } else {
9119 reportSettingsProblem(Log.WARN,
9120 "Error in package manager settings: package "
9121 + name + " has bad sharedId " + sharedIdStr
9122 + " at " + parser.getPositionDescription());
9123 }
9124 } else {
9125 reportSettingsProblem(Log.WARN,
9126 "Error in package manager settings: package "
9127 + name + " has bad userId " + idStr + " at "
9128 + parser.getPositionDescription());
9129 }
9130 } catch (NumberFormatException e) {
9131 reportSettingsProblem(Log.WARN,
9132 "Error in package manager settings: package "
9133 + name + " has bad userId " + idStr + " at "
9134 + parser.getPositionDescription());
9135 }
9136 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009137 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009138 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009139 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009140 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009141 final String enabledStr = parser.getAttributeValue(null, "enabled");
9142 if (enabledStr != null) {
9143 if (enabledStr.equalsIgnoreCase("true")) {
9144 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9145 } else if (enabledStr.equalsIgnoreCase("false")) {
9146 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9147 } else if (enabledStr.equalsIgnoreCase("default")) {
9148 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9149 } else {
9150 reportSettingsProblem(Log.WARN,
9151 "Error in package manager settings: package "
9152 + name + " has bad enabled value: " + idStr
9153 + " at " + parser.getPositionDescription());
9154 }
9155 } else {
9156 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9157 }
9158 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9159 if (installStatusStr != null) {
9160 if (installStatusStr.equalsIgnoreCase("false")) {
9161 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9162 } else {
9163 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9164 }
9165 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009167 int outerDepth = parser.getDepth();
9168 int type;
9169 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9170 && (type != XmlPullParser.END_TAG
9171 || parser.getDepth() > outerDepth)) {
9172 if (type == XmlPullParser.END_TAG
9173 || type == XmlPullParser.TEXT) {
9174 continue;
9175 }
9176
9177 String tagName = parser.getName();
9178 if (tagName.equals("disabled-components")) {
9179 readDisabledComponentsLP(packageSetting, parser);
9180 } else if (tagName.equals("enabled-components")) {
9181 readEnabledComponentsLP(packageSetting, parser);
9182 } else if (tagName.equals("sigs")) {
9183 packageSetting.signatures.readXml(parser, mPastSignatures);
9184 } else if (tagName.equals("perms")) {
9185 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009186 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009187 packageSetting.permissionsFixed = true;
9188 } else {
9189 reportSettingsProblem(Log.WARN,
9190 "Unknown element under <package>: "
9191 + parser.getName());
9192 XmlUtils.skipCurrentTag(parser);
9193 }
9194 }
9195 } else {
9196 XmlUtils.skipCurrentTag(parser);
9197 }
9198 }
9199
9200 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9201 XmlPullParser parser)
9202 throws IOException, XmlPullParserException {
9203 int outerDepth = parser.getDepth();
9204 int type;
9205 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9206 && (type != XmlPullParser.END_TAG
9207 || parser.getDepth() > outerDepth)) {
9208 if (type == XmlPullParser.END_TAG
9209 || type == XmlPullParser.TEXT) {
9210 continue;
9211 }
9212
9213 String tagName = parser.getName();
9214 if (tagName.equals("item")) {
9215 String name = parser.getAttributeValue(null, "name");
9216 if (name != null) {
9217 packageSetting.disabledComponents.add(name.intern());
9218 } else {
9219 reportSettingsProblem(Log.WARN,
9220 "Error in package manager settings: <disabled-components> has"
9221 + " no name at " + parser.getPositionDescription());
9222 }
9223 } else {
9224 reportSettingsProblem(Log.WARN,
9225 "Unknown element under <disabled-components>: "
9226 + parser.getName());
9227 }
9228 XmlUtils.skipCurrentTag(parser);
9229 }
9230 }
9231
9232 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9233 XmlPullParser parser)
9234 throws IOException, XmlPullParserException {
9235 int outerDepth = parser.getDepth();
9236 int type;
9237 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9238 && (type != XmlPullParser.END_TAG
9239 || parser.getDepth() > outerDepth)) {
9240 if (type == XmlPullParser.END_TAG
9241 || type == XmlPullParser.TEXT) {
9242 continue;
9243 }
9244
9245 String tagName = parser.getName();
9246 if (tagName.equals("item")) {
9247 String name = parser.getAttributeValue(null, "name");
9248 if (name != null) {
9249 packageSetting.enabledComponents.add(name.intern());
9250 } else {
9251 reportSettingsProblem(Log.WARN,
9252 "Error in package manager settings: <enabled-components> has"
9253 + " no name at " + parser.getPositionDescription());
9254 }
9255 } else {
9256 reportSettingsProblem(Log.WARN,
9257 "Unknown element under <enabled-components>: "
9258 + parser.getName());
9259 }
9260 XmlUtils.skipCurrentTag(parser);
9261 }
9262 }
9263
9264 private void readSharedUserLP(XmlPullParser parser)
9265 throws XmlPullParserException, IOException {
9266 String name = null;
9267 String idStr = null;
9268 int pkgFlags = 0;
9269 SharedUserSetting su = null;
9270 try {
9271 name = parser.getAttributeValue(null, "name");
9272 idStr = parser.getAttributeValue(null, "userId");
9273 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9274 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9275 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9276 }
9277 if (name == null) {
9278 reportSettingsProblem(Log.WARN,
9279 "Error in package manager settings: <shared-user> has no name at "
9280 + parser.getPositionDescription());
9281 } else if (userId == 0) {
9282 reportSettingsProblem(Log.WARN,
9283 "Error in package manager settings: shared-user "
9284 + name + " has bad userId " + idStr + " at "
9285 + parser.getPositionDescription());
9286 } else {
9287 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9288 reportSettingsProblem(Log.ERROR,
9289 "Occurred while parsing settings at "
9290 + parser.getPositionDescription());
9291 }
9292 }
9293 } catch (NumberFormatException e) {
9294 reportSettingsProblem(Log.WARN,
9295 "Error in package manager settings: package "
9296 + name + " has bad userId " + idStr + " at "
9297 + parser.getPositionDescription());
9298 };
9299
9300 if (su != null) {
9301 int outerDepth = parser.getDepth();
9302 int type;
9303 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9304 && (type != XmlPullParser.END_TAG
9305 || parser.getDepth() > outerDepth)) {
9306 if (type == XmlPullParser.END_TAG
9307 || type == XmlPullParser.TEXT) {
9308 continue;
9309 }
9310
9311 String tagName = parser.getName();
9312 if (tagName.equals("sigs")) {
9313 su.signatures.readXml(parser, mPastSignatures);
9314 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009315 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009316 } else {
9317 reportSettingsProblem(Log.WARN,
9318 "Unknown element under <shared-user>: "
9319 + parser.getName());
9320 XmlUtils.skipCurrentTag(parser);
9321 }
9322 }
9323
9324 } else {
9325 XmlUtils.skipCurrentTag(parser);
9326 }
9327 }
9328
9329 private void readGrantedPermissionsLP(XmlPullParser parser,
9330 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9331 int outerDepth = parser.getDepth();
9332 int type;
9333 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9334 && (type != XmlPullParser.END_TAG
9335 || parser.getDepth() > outerDepth)) {
9336 if (type == XmlPullParser.END_TAG
9337 || type == XmlPullParser.TEXT) {
9338 continue;
9339 }
9340
9341 String tagName = parser.getName();
9342 if (tagName.equals("item")) {
9343 String name = parser.getAttributeValue(null, "name");
9344 if (name != null) {
9345 outPerms.add(name.intern());
9346 } else {
9347 reportSettingsProblem(Log.WARN,
9348 "Error in package manager settings: <perms> has"
9349 + " no name at " + parser.getPositionDescription());
9350 }
9351 } else {
9352 reportSettingsProblem(Log.WARN,
9353 "Unknown element under <perms>: "
9354 + parser.getName());
9355 }
9356 XmlUtils.skipCurrentTag(parser);
9357 }
9358 }
9359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009360 private void readPreferredActivitiesLP(XmlPullParser parser)
9361 throws XmlPullParserException, IOException {
9362 int outerDepth = parser.getDepth();
9363 int type;
9364 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9365 && (type != XmlPullParser.END_TAG
9366 || parser.getDepth() > outerDepth)) {
9367 if (type == XmlPullParser.END_TAG
9368 || type == XmlPullParser.TEXT) {
9369 continue;
9370 }
9371
9372 String tagName = parser.getName();
9373 if (tagName.equals("item")) {
9374 PreferredActivity pa = new PreferredActivity(parser);
9375 if (pa.mParseError == null) {
9376 mPreferredActivities.addFilter(pa);
9377 } else {
9378 reportSettingsProblem(Log.WARN,
9379 "Error in package manager settings: <preferred-activity> "
9380 + pa.mParseError + " at "
9381 + parser.getPositionDescription());
9382 }
9383 } else {
9384 reportSettingsProblem(Log.WARN,
9385 "Unknown element under <preferred-activities>: "
9386 + parser.getName());
9387 XmlUtils.skipCurrentTag(parser);
9388 }
9389 }
9390 }
9391
9392 // Returns -1 if we could not find an available UserId to assign
9393 private int newUserIdLP(Object obj) {
9394 // Let's be stupidly inefficient for now...
9395 final int N = mUserIds.size();
9396 for (int i=0; i<N; i++) {
9397 if (mUserIds.get(i) == null) {
9398 mUserIds.set(i, obj);
9399 return FIRST_APPLICATION_UID + i;
9400 }
9401 }
9402
9403 // None left?
9404 if (N >= MAX_APPLICATION_UIDS) {
9405 return -1;
9406 }
9407
9408 mUserIds.add(obj);
9409 return FIRST_APPLICATION_UID + N;
9410 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009412 public PackageSetting getDisabledSystemPkg(String name) {
9413 synchronized(mPackages) {
9414 PackageSetting ps = mDisabledSysPackages.get(name);
9415 return ps;
9416 }
9417 }
9418
9419 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009420 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9421 return true;
9422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009423 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9424 if (Config.LOGV) {
9425 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9426 + " componentName = " + componentInfo.name);
9427 Log.v(TAG, "enabledComponents: "
9428 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9429 Log.v(TAG, "disabledComponents: "
9430 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9431 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009432 if (packageSettings == null) {
9433 if (false) {
9434 Log.w(TAG, "WAITING FOR DEBUGGER");
9435 Debug.waitForDebugger();
9436 Log.i(TAG, "We will crash!");
9437 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009438 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009439 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009440 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9441 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9442 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9443 return false;
9444 }
9445 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9446 return true;
9447 }
9448 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9449 return false;
9450 }
9451 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009452 }
9453 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009454
9455 // ------- apps on sdcard specific code -------
9456 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009457 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9458 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9459 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009460 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009461
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009462 private String getEncryptKey() {
9463 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009464 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9465 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009466 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009467 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9468 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009469 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009470 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009471 return null;
9472 }
9473 }
9474 return sdEncKey;
9475 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009476 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009477 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009478 } catch (IOException ioe) {
9479 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9480 + ioe);
9481 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009482 }
Rich Cannings8d578832010-09-09 15:12:40 -07009483
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009484 }
9485
Kenny Rootc78a8072010-07-27 15:18:38 -07009486 /* package */ static String getTempContainerId() {
9487 int tmpIdx = 1;
9488 String list[] = PackageHelper.getSecureContainerList();
9489 if (list != null) {
9490 for (final String name : list) {
9491 // Ignore null and non-temporary container entries
9492 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9493 continue;
9494 }
9495
9496 String subStr = name.substring(mTempContainerPrefix.length());
9497 try {
9498 int cid = Integer.parseInt(subStr);
9499 if (cid >= tmpIdx) {
9500 tmpIdx = cid + 1;
9501 }
9502 } catch (NumberFormatException e) {
9503 }
9504 }
9505 }
9506 return mTempContainerPrefix + tmpIdx;
9507 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009508
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009509 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009510 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009511 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009512 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9513 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9514 throw new SecurityException("Media status can only be updated by the system");
9515 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009516 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009517 Log.i(TAG, "Updating external media status from " +
9518 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9519 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009520 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9521 mediaStatus+", mMediaMounted=" + mMediaMounted);
9522 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009523 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9524 reportStatus ? 1 : 0, -1);
9525 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009526 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009527 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009528 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009529 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009530 // Queue up an async operation since the package installation may take a little while.
9531 mHandler.post(new Runnable() {
9532 public void run() {
9533 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009534 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009535 }
9536 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009537 }
9538
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009539 /*
9540 * Collect information of applications on external media, map them
9541 * against existing containers and update information based on current
9542 * mount status. Please note that we always have to report status
9543 * if reportStatus has been set to true especially when unloading packages.
9544 */
9545 private void updateExternalMediaStatusInner(boolean mediaStatus,
9546 boolean reportStatus) {
9547 // Collection of uids
9548 int uidArr[] = null;
9549 // Collection of stale containers
9550 HashSet<String> removeCids = new HashSet<String>();
9551 // Collection of packages on external media with valid containers.
9552 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9553 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009554 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009555 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009556 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009557 } else {
9558 // Process list of secure containers and categorize them
9559 // as active or stale based on their package internal state.
9560 int uidList[] = new int[list.length];
9561 int num = 0;
9562 synchronized (mPackages) {
9563 for (String cid : list) {
9564 SdInstallArgs args = new SdInstallArgs(cid);
9565 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009566 String pkgName = args.getPackageName();
9567 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009568 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9569 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009570 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009571 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009572 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9573 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009574 // The package status is changed only if the code path
9575 // matches between settings and the container id.
9576 if (ps != null && ps.codePathString != null &&
9577 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009578 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9579 " corresponds to pkg : " + pkgName +
9580 " at code path: " + ps.codePathString);
9581 // We do have a valid package installed on sdcard
9582 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009583 int uid = ps.userId;
9584 if (uid != -1) {
9585 uidList[num++] = uid;
9586 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009587 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009588 // Stale container on sdcard. Just delete
9589 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9590 removeCids.add(cid);
9591 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009592 }
9593 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009594
9595 if (num > 0) {
9596 // Sort uid list
9597 Arrays.sort(uidList, 0, num);
9598 // Throw away duplicates
9599 uidArr = new int[num];
9600 uidArr[0] = uidList[0];
9601 int di = 0;
9602 for (int i = 1; i < num; i++) {
9603 if (uidList[i-1] != uidList[i]) {
9604 uidArr[di++] = uidList[i];
9605 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009606 }
9607 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009608 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009609 // Process packages with valid entries.
9610 if (mediaStatus) {
9611 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009612 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009613 startCleaningPackages();
9614 } else {
9615 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009616 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009617 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009618 }
9619
9620 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009621 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009622 int size = pkgList.size();
9623 if (size > 0) {
9624 // Send broadcasts here
9625 Bundle extras = new Bundle();
9626 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9627 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009628 if (uidArr != null) {
9629 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9630 }
9631 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9632 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009633 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009634 }
9635 }
9636
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009637 /*
9638 * Look at potentially valid container ids from processCids
9639 * If package information doesn't match the one on record
9640 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009641 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009642 */
9643 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009644 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009645 ArrayList<String> pkgList = new ArrayList<String>();
9646 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009647 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009648 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009649 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009650 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9651 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009652 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009653 try {
9654 // Make sure there are no container errors first.
9655 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9656 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009657 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009658 " when installing from sdcard");
9659 continue;
9660 }
9661 // Check code path here.
9662 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009663 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009664 " does not match one in settings " + codePath);
9665 continue;
9666 }
9667 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009668 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009669 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009670 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009671 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9672 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009673 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009674 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009675 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009676 retCode = PackageManager.INSTALL_SUCCEEDED;
9677 pkgList.add(pkg.packageName);
9678 // Post process args
9679 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9680 }
9681 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009682 Slog.i(TAG, "Failed to install pkg from " +
9683 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009684 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009685 }
9686
9687 } finally {
9688 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9689 // Don't destroy container here. Wait till gc clears things up.
9690 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009691 }
9692 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009693 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009694 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009695 // If the platform SDK has changed since the last time we booted,
9696 // we need to re-grant app permission to catch any new ones that
9697 // appear. This is really a hack, and means that apps can in some
9698 // cases get permissions that the user didn't initially explicitly
9699 // allow... it would be nice to have some better way to handle
9700 // this situation.
9701 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9702 != mSdkVersion;
9703 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9704 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9705 + "; regranting permissions for external storage");
9706 mSettings.mExternalSdkPlatform = mSdkVersion;
9707
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009708 // Make sure group IDs have been assigned, and any permission
9709 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009710 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009711 // Persist settings
9712 mSettings.writeLP();
9713 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009714 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009715 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009716 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009717 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009718 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009719 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009720 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009721 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009722 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009723 if (removeCids != null) {
9724 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009725 if (cid.startsWith(mTempContainerPrefix)) {
9726 Log.i(TAG, "Destroying stale temporary container " + cid);
9727 PackageHelper.destroySdDir(cid);
9728 } else {
9729 Log.w(TAG, "Container " + cid + " is stale");
9730 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009731 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009732 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009733 }
9734
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009735 /*
9736 * Utility method to unload a list of specified containers
9737 */
9738 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9739 // Just unmount all valid containers.
9740 for (SdInstallArgs arg : cidArgs) {
9741 synchronized (mInstallLock) {
9742 arg.doPostDeleteLI(false);
9743 }
9744 }
9745 }
9746
9747 /*
9748 * Unload packages mounted on external media. This involves deleting
9749 * package data from internal structures, sending broadcasts about
9750 * diabled packages, gc'ing to free up references, unmounting all
9751 * secure containers corresponding to packages on external media, and
9752 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9753 * Please note that we always have to post this message if status has
9754 * been requested no matter what.
9755 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009756 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009757 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009758 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009759 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009760 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009761 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009762 for (SdInstallArgs args : keys) {
9763 String cid = args.cid;
9764 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009765 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009766 // Delete package internally
9767 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9768 synchronized (mInstallLock) {
9769 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009770 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009771 if (res) {
9772 pkgList.add(pkgName);
9773 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009774 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009775 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009776 }
9777 }
9778 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009779
9780 synchronized (mPackages) {
9781 // We didn't update the settings after removing each package;
9782 // write them now for all packages.
9783 mSettings.writeLP();
9784 }
9785
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009786 // We have to absolutely send UPDATED_MEDIA_STATUS only
9787 // after confirming that all the receivers processed the ordered
9788 // broadcast when packages get disabled, force a gc to clean things up.
9789 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009790 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009791 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9792 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9793 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009794 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9795 reportStatus ? 1 : 0, 1, keys);
9796 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009797 }
9798 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009799 } else {
9800 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9801 reportStatus ? 1 : 0, -1, keys);
9802 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009803 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009804 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009805
9806 public void movePackage(final String packageName,
9807 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009808 mContext.enforceCallingOrSelfPermission(
9809 android.Manifest.permission.MOVE_PACKAGE, null);
9810 int returnCode = PackageManager.MOVE_SUCCEEDED;
9811 int currFlags = 0;
9812 int newFlags = 0;
9813 synchronized (mPackages) {
9814 PackageParser.Package pkg = mPackages.get(packageName);
9815 if (pkg == null) {
9816 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009817 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009818 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009819 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009820 Slog.w(TAG, "Cannot move system application");
9821 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009822 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009823 Slog.w(TAG, "Cannot move forward locked app.");
9824 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009825 } else if (pkg.mOperationPending) {
9826 Slog.w(TAG, "Attempt to move package which has pending operations");
9827 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009828 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009829 // Find install location first
9830 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9831 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9832 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009833 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009834 } else {
9835 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9836 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009837 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9838 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009839 if (newFlags == currFlags) {
9840 Slog.w(TAG, "No move required. Trying to move to same location");
9841 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9842 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009843 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009844 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9845 pkg.mOperationPending = true;
9846 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009847 }
9848 }
9849 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009850 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009851 } else {
9852 Message msg = mHandler.obtainMessage(INIT_COPY);
9853 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009854 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9855 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9856 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009857 msg.obj = mp;
9858 mHandler.sendMessage(msg);
9859 }
9860 }
9861 }
9862
9863 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9864 // Queue up an async operation since the package deletion may take a little while.
9865 mHandler.post(new Runnable() {
9866 public void run() {
9867 mHandler.removeCallbacks(this);
9868 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009869 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9870 int uidArr[] = null;
9871 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009872 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009873 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009874 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009875 Slog.w(TAG, " Package " + mp.packageName +
9876 " doesn't exist. Aborting move");
9877 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9878 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9879 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9880 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9881 " Aborting move and returning error");
9882 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9883 } else {
9884 uidArr = new int[] { pkg.applicationInfo.uid };
9885 pkgList = new ArrayList<String>();
9886 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009887 }
9888 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009889 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9890 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009891 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009892 // Update package code and resource paths
9893 synchronized (mInstallLock) {
9894 synchronized (mPackages) {
9895 PackageParser.Package pkg = mPackages.get(mp.packageName);
9896 // Recheck for package again.
9897 if (pkg == null ) {
9898 Slog.w(TAG, " Package " + mp.packageName +
9899 " doesn't exist. Aborting move");
9900 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9901 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9902 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9903 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9904 " Aborting move and returning error");
9905 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9906 } else {
Kenny Root85387d72010-08-26 10:13:11 -07009907 final String oldCodePath = pkg.mPath;
9908 final String newCodePath = mp.targetArgs.getCodePath();
9909 final String newResPath = mp.targetArgs.getResourcePath();
9910 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009911 pkg.mPath = newCodePath;
9912 // Move dex files around
9913 if (moveDexFilesLI(pkg)
9914 != PackageManager.INSTALL_SUCCEEDED) {
9915 // Moving of dex files failed. Set
9916 // error code and abort move.
9917 pkg.mPath = pkg.mScanPath;
9918 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9919 } else {
9920 pkg.mScanPath = newCodePath;
9921 pkg.applicationInfo.sourceDir = newCodePath;
9922 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -07009923 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009924 PackageSetting ps = (PackageSetting) pkg.mExtras;
9925 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9926 ps.codePathString = ps.codePath.getPath();
9927 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9928 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -07009929 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009930 // Set the application info flag correctly.
9931 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9932 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9933 } else {
9934 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9935 }
9936 ps.setFlags(pkg.applicationInfo.flags);
9937 mAppDirs.remove(oldCodePath);
9938 mAppDirs.put(newCodePath, pkg);
9939 // Persist settings
9940 mSettings.writeLP();
9941 }
9942 }
9943 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009944 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009945 // Send resources available broadcast
9946 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009947 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009948 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009949 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009950 // Clean up failed installation
9951 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009952 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009953 }
9954 } else {
9955 // Force a gc to clear things up.
9956 Runtime.getRuntime().gc();
9957 // Delete older code
9958 synchronized (mInstallLock) {
9959 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009960 }
9961 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009962
9963 // Allow more operations on this file if we didn't fail because
9964 // an operation was already pending for this package.
9965 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9966 synchronized (mPackages) {
9967 PackageParser.Package pkg = mPackages.get(mp.packageName);
9968 if (pkg != null) {
9969 pkg.mOperationPending = false;
9970 }
9971 }
9972 }
9973
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009974 IPackageMoveObserver observer = mp.observer;
9975 if (observer != null) {
9976 try {
9977 observer.packageMoved(mp.packageName, returnCode);
9978 } catch (RemoteException e) {
9979 Log.i(TAG, "Observer no longer exists.");
9980 }
9981 }
9982 }
9983 });
9984 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009985
9986 public boolean setInstallLocation(int loc) {
9987 mContext.enforceCallingOrSelfPermission(
9988 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9989 if (getInstallLocation() == loc) {
9990 return true;
9991 }
9992 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9993 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9994 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9995 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9996 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9997 return true;
9998 }
9999 return false;
10000 }
10001
10002 public int getInstallLocation() {
10003 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10004 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010006}