blob: 87a744e69cac46e28b7f384680430e54a54d4f75 [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;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080021import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080022import com.android.internal.util.FastXmlSerializer;
23import com.android.internal.util.XmlUtils;
David 'Digit' Turneradd13762010-02-03 17:34:58 -080024import com.android.server.JournaledFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080032import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080033import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070038import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080039import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.pm.ActivityInfo;
42import android.content.pm.ApplicationInfo;
43import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070044import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.IPackageDataObserver;
46import android.content.pm.IPackageDeleteObserver;
47import android.content.pm.IPackageInstallObserver;
48import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080049import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.content.pm.IPackageStatsObserver;
51import android.content.pm.InstrumentationInfo;
52import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080053import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.content.pm.PackageManager;
55import android.content.pm.PackageStats;
56import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.pm.PackageParser;
60import android.content.pm.PermissionInfo;
61import android.content.pm.PermissionGroupInfo;
62import android.content.pm.ProviderInfo;
63import android.content.pm.ResolveInfo;
64import android.content.pm.ServiceInfo;
65import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.Uri;
67import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070068import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080070import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080072import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070073import android.os.Looper;
74import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Parcel;
76import android.os.RemoteException;
77import android.os.Environment;
78import android.os.FileObserver;
79import android.os.FileUtils;
80import android.os.Handler;
81import android.os.ParcelFileDescriptor;
82import android.os.Process;
83import android.os.ServiceManager;
84import android.os.SystemClock;
85import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080086import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.util.*;
88import android.view.Display;
89import android.view.WindowManager;
90
91import java.io.File;
92import java.io.FileDescriptor;
93import java.io.FileInputStream;
94import java.io.FileNotFoundException;
95import java.io.FileOutputStream;
96import java.io.FileReader;
97import java.io.FilenameFilter;
98import java.io.IOException;
99import java.io.InputStream;
100import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800101import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800102import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.util.ArrayList;
104import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700105import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.Collections;
107import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800108import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.Enumeration;
110import java.util.HashMap;
111import java.util.HashSet;
112import java.util.Iterator;
113import java.util.List;
114import java.util.Map;
115import java.util.Set;
116import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800117import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.zip.ZipFile;
119import java.util.zip.ZipOutputStream;
120
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700121/**
122 * Keep track of all those .apks everywhere.
123 *
124 * This is very central to the platform's security; please run the unit
125 * tests whenever making modifications here:
126 *
127mmm frameworks/base/tests/AndroidTests
128adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
129adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
130 *
131 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132class PackageManagerService extends IPackageManager.Stub {
133 private static final String TAG = "PackageManager";
134 private static final boolean DEBUG_SETTINGS = false;
135 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800136 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800137 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
139 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
140 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400141 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 private static final int FIRST_APPLICATION_UID =
143 Process.FIRST_APPLICATION_UID;
144 private static final int MAX_APPLICATION_UIDS = 1000;
145
146 private static final boolean SHOW_INFO = false;
147
148 private static final boolean GET_CERTIFICATES = true;
149
Oscar Montemayora8529f62009-11-18 10:14:20 -0800150 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 private static final int REMOVE_EVENTS =
153 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
154 private static final int ADD_EVENTS =
155 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
156
157 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800158 // Suffix used during package installation when copying/moving
159 // package apks to install directory.
160 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800162 /**
163 * Indicates the state of installation. Used by PackageManager to
164 * figure out incomplete installations. Say a package is being installed
165 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
166 * the package installation is successful or unsuccesful lin which case
167 * the PackageManager will no longer maintain state information associated
168 * with the package. If some exception(like device freeze or battery being
169 * pulled out) occurs during installation of a package, the PackageManager
170 * needs this information to clean up the previously failed installation.
171 */
172 private static final int PKG_INSTALL_INCOMPLETE = 0;
173 private static final int PKG_INSTALL_COMPLETE = 1;
174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final int SCAN_MONITOR = 1<<0;
176 static final int SCAN_NO_DEX = 1<<1;
177 static final int SCAN_FORCE_DEX = 1<<2;
178 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800179 static final int SCAN_NEW_INSTALL = 1<<4;
180 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800182 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
183 "com.android.defcontainer",
184 "com.android.defcontainer.DefaultContainerService");
185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
187 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700188 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
Dianne Hackborn851a5412009-05-08 12:06:44 -0700190 final int mSdkVersion = Build.VERSION.SDK_INT;
191 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
192 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 final Context mContext;
195 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700196 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 final DisplayMetrics mMetrics;
198 final int mDefParseFlags;
199 final String[] mSeparateProcesses;
200
201 // This is where all application persistent data goes.
202 final File mAppDataDir;
203
Oscar Montemayora8529f62009-11-18 10:14:20 -0800204 // If Encrypted File System feature is enabled, all application persistent data
205 // should go here instead.
206 final File mSecureAppDataDir;
207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 // This is the object monitoring the framework dir.
209 final FileObserver mFrameworkInstallObserver;
210
211 // This is the object monitoring the system app dir.
212 final FileObserver mSystemInstallObserver;
213
214 // This is the object monitoring mAppInstallDir.
215 final FileObserver mAppInstallObserver;
216
217 // This is the object monitoring mDrmAppPrivateInstallDir.
218 final FileObserver mDrmAppInstallObserver;
219
220 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
221 // LOCK HELD. Can be called with mInstallLock held.
222 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 final File mFrameworkDir;
225 final File mSystemAppDir;
226 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700227 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228
229 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
230 // apps.
231 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 // Lock for state used when installing and doing other long running
236 // operations. Methods that must be called with this lock held have
237 // the prefix "LI".
238 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // These are the directories in the 3rd party applications installed dir
241 // that we have currently loaded packages from. Keys are the application's
242 // installed zip file (absolute codePath), and values are Package.
243 final HashMap<String, PackageParser.Package> mAppDirs =
244 new HashMap<String, PackageParser.Package>();
245
246 // Information for the parser to write more useful error messages.
247 File mScanningPath;
248 int mLastScanError;
249
250 final int[] mOutPermissions = new int[3];
251
252 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 // Keys are String (package name), values are Package. This also serves
255 // as the lock for the global state. Methods that must be called with
256 // this lock held have the prefix "LP".
257 final HashMap<String, PackageParser.Package> mPackages =
258 new HashMap<String, PackageParser.Package>();
259
260 final Settings mSettings;
261 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262
263 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
264 int[] mGlobalGids;
265
266 // These are the built-in uid -> permission mappings that were read from the
267 // etc/permissions.xml file.
268 final SparseArray<HashSet<String>> mSystemPermissions =
269 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 // These are the built-in shared libraries that were read from the
272 // etc/permissions.xml file.
273 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800274
Dianne Hackborn49237342009-08-27 20:08:01 -0700275 // Temporary for building the final shared libraries for an .apk.
276 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800277
Dianne Hackborn49237342009-08-27 20:08:01 -0700278 // These are the features this devices supports that were read from the
279 // etc/permissions.xml file.
280 final HashMap<String, FeatureInfo> mAvailableFeatures =
281 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 // All available activities, for your resolving pleasure.
284 final ActivityIntentResolver mActivities =
285 new ActivityIntentResolver();
286
287 // All available receivers, for your resolving pleasure.
288 final ActivityIntentResolver mReceivers =
289 new ActivityIntentResolver();
290
291 // All available services, for your resolving pleasure.
292 final ServiceIntentResolver mServices = new ServiceIntentResolver();
293
294 // Keys are String (provider class name), values are Provider.
295 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
296 new HashMap<ComponentName, PackageParser.Provider>();
297
298 // Mapping from provider base names (first directory in content URI codePath)
299 // to the provider information.
300 final HashMap<String, PackageParser.Provider> mProviders =
301 new HashMap<String, PackageParser.Provider>();
302
303 // Mapping from instrumentation class names to info about them.
304 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
305 new HashMap<ComponentName, PackageParser.Instrumentation>();
306
307 // Mapping from permission names to info about them.
308 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
309 new HashMap<String, PackageParser.PermissionGroup>();
310
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800311 // Packages whose data we have transfered into another package, thus
312 // should no longer exist.
313 final HashSet<String> mTransferedPackages = new HashSet<String>();
314
Dianne Hackborn854060af2009-07-09 18:14:31 -0700315 // Broadcast actions that are only available to the system.
316 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 boolean mSystemReady;
319 boolean mSafeMode;
320 boolean mHasSystemUidErrors;
321
322 ApplicationInfo mAndroidApplication;
323 final ActivityInfo mResolveActivity = new ActivityInfo();
324 final ResolveInfo mResolveInfo = new ResolveInfo();
325 ComponentName mResolveComponentName;
326 PackageParser.Package mPlatformPackage;
327
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700328 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800329 final HashMap<String, ArrayList<String>> mPendingBroadcasts
330 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800331 // Service Connection to remote media container service to copy
332 // package uri's from external media onto secure containers
333 // or internal storage.
334 private IMediaContainerService mContainerService = null;
335
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700336 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800337 static final int MCS_BOUND = 3;
338 static final int END_COPY = 4;
339 static final int INIT_COPY = 5;
340 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800341 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800342 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800343 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800344 static final int MCS_RECONNECT = 10;
345 static final int MCS_GIVE_UP = 11;
346
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700347 // Delay time in millisecs
348 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800349 final private DefaultContainerConnection mDefContainerConn =
350 new DefaultContainerConnection();
351 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800352 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800353 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800354 IMediaContainerService imcs =
355 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800356 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800357 }
358
359 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800360 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800361 }
362 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700363
Christopher Tate1bb69062010-02-19 17:02:12 -0800364 // Recordkeeping of restore-after-install operations that are currently in flight
365 // between the Package Manager and the Backup Manager
366 class PostInstallData {
367 public InstallArgs args;
368 public PackageInstalledInfo res;
369
370 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
371 args = _a;
372 res = _r;
373 }
374 };
375 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
376 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
377
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800379 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800380 final ArrayList<HandlerParams> mPendingInstalls =
381 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800382
383 private boolean connectToService() {
384 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
385 " DefaultContainerService");
386 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
387 if (mContext.bindService(service, mDefContainerConn,
388 Context.BIND_AUTO_CREATE)) {
389 mBound = true;
390 return true;
391 }
392 return false;
393 }
394
395 private void disconnectService() {
396 mContainerService = null;
397 mBound = false;
398 mContext.unbindService(mDefContainerConn);
399 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800400
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700401 PackageHandler(Looper looper) {
402 super(looper);
403 }
404 public void handleMessage(Message msg) {
405 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800406 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800407 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800408 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800409 int idx = mPendingInstalls.size();
410 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
411 // If a bind was already initiated we dont really
412 // need to do anything. The pending install
413 // will be processed later on.
414 if (!mBound) {
415 // If this is the only one pending we might
416 // have to bind to the service again.
417 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800418 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800419 params.serviceError();
420 return;
421 } else {
422 // Once we bind to the service, the first
423 // pending request will be processed.
424 mPendingInstalls.add(idx, params);
425 }
426 } else {
427 mPendingInstalls.add(idx, params);
428 // Already bound to the service. Just make
429 // sure we trigger off processing the first request.
430 if (idx == 0) {
431 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800432 }
433 }
434 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800435 }
436 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800437 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800438 if (msg.obj != null) {
439 mContainerService = (IMediaContainerService) msg.obj;
440 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800441 if (mContainerService == null) {
442 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800443 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800444 for (HandlerParams params : mPendingInstalls) {
445 mPendingInstalls.remove(0);
446 // Indicate service bind error
447 params.serviceError();
448 }
449 mPendingInstalls.clear();
450 } else if (mPendingInstalls.size() > 0) {
451 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800452 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800453 params.startCopy();
454 }
455 } else {
456 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800457 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800458 }
459 break;
460 }
461 case MCS_RECONNECT : {
462 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
463 if (mPendingInstalls.size() > 0) {
464 if (mBound) {
465 disconnectService();
466 }
467 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800468 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800469 for (HandlerParams params : mPendingInstalls) {
470 mPendingInstalls.remove(0);
471 // Indicate service bind error
472 params.serviceError();
473 }
474 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800475 }
476 }
477 break;
478 }
479 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800480 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
481 // Delete pending install
482 if (mPendingInstalls.size() > 0) {
483 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800484 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800485 if (mPendingInstalls.size() == 0) {
486 if (mBound) {
487 disconnectService();
488 }
489 } else {
490 // There are more pending requests in queue.
491 // Just post MCS_BOUND message to trigger processing
492 // of next pending install.
493 mHandler.sendEmptyMessage(MCS_BOUND);
494 }
495 break;
496 }
497 case MCS_GIVE_UP: {
498 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
499 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800500 break;
501 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700502 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800503 String packages[];
504 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700505 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700506 int uids[];
507 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800508 if (mPendingBroadcasts == null) {
509 return;
510 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700511 size = mPendingBroadcasts.size();
512 if (size <= 0) {
513 // Nothing to be done. Just return
514 return;
515 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800516 packages = new String[size];
517 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700518 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800519 Iterator<HashMap.Entry<String, ArrayList<String>>>
520 it = mPendingBroadcasts.entrySet().iterator();
521 int i = 0;
522 while (it.hasNext() && i < size) {
523 HashMap.Entry<String, ArrayList<String>> ent = it.next();
524 packages[i] = ent.getKey();
525 components[i] = ent.getValue();
526 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700527 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800528 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700529 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800530 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 mPendingBroadcasts.clear();
532 }
533 // Send broadcasts
534 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800535 sendPackageChangedBroadcast(packages[i], true,
536 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700537 }
538 break;
539 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800540 case START_CLEANING_PACKAGE: {
541 String packageName = (String)msg.obj;
542 synchronized (mPackages) {
543 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
544 mSettings.mPackagesToBeCleaned.add(packageName);
545 }
546 }
547 startCleaningPackages();
548 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800549 case POST_INSTALL: {
550 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
551 PostInstallData data = mRunningInstalls.get(msg.arg1);
552 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800553 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800554
555 if (data != null) {
556 InstallArgs args = data.args;
557 PackageInstalledInfo res = data.res;
558
559 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
560 res.removedInfo.sendBroadcast(false, true);
561 Bundle extras = new Bundle(1);
562 extras.putInt(Intent.EXTRA_UID, res.uid);
563 final boolean update = res.removedInfo.removedPackage != null;
564 if (update) {
565 extras.putBoolean(Intent.EXTRA_REPLACING, true);
566 }
567 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
568 res.pkg.applicationInfo.packageName,
569 extras);
570 if (update) {
571 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
572 res.pkg.applicationInfo.packageName,
573 extras);
574 }
575 if (res.removedInfo.args != null) {
576 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800577 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800578 }
579 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800580 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800581 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800582 // We delete after a gc for applications on sdcard.
583 if (deleteOld) {
584 synchronized (mInstallLock) {
585 res.removedInfo.args.doPostDeleteLI(true);
586 }
587 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800588 if (args.observer != null) {
589 try {
590 args.observer.packageInstalled(res.name, res.returnCode);
591 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800592 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800593 }
594 }
595 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800596 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800597 }
598 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700599 }
600 }
601 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800602
603 static boolean installOnSd(int flags) {
604 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700605 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800606 return false;
607 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700608 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
609 return true;
610 }
611 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800612 }
613
614 static boolean isFwdLocked(int flags) {
615 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
616 return true;
617 }
618 return false;
619 }
620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 public static final IPackageManager main(Context context, boolean factoryTest) {
622 PackageManagerService m = new PackageManagerService(context, factoryTest);
623 ServiceManager.addService("package", m);
624 return m;
625 }
626
627 static String[] splitString(String str, char sep) {
628 int count = 1;
629 int i = 0;
630 while ((i=str.indexOf(sep, i)) >= 0) {
631 count++;
632 i++;
633 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 String[] res = new String[count];
636 i=0;
637 count = 0;
638 int lastI=0;
639 while ((i=str.indexOf(sep, i)) >= 0) {
640 res[count] = str.substring(lastI, i);
641 count++;
642 i++;
643 lastI = i;
644 }
645 res[count] = str.substring(lastI, str.length());
646 return res;
647 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800650 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800654 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 mContext = context;
658 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700659 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 mMetrics = new DisplayMetrics();
661 mSettings = new Settings();
662 mSettings.addSharedUserLP("android.uid.system",
663 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
664 mSettings.addSharedUserLP("android.uid.phone",
665 MULTIPLE_APPLICATION_UIDS
666 ? RADIO_UID : FIRST_APPLICATION_UID,
667 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400668 mSettings.addSharedUserLP("android.uid.log",
669 MULTIPLE_APPLICATION_UIDS
670 ? LOG_UID : FIRST_APPLICATION_UID,
671 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672
673 String separateProcesses = SystemProperties.get("debug.separate_processes");
674 if (separateProcesses != null && separateProcesses.length() > 0) {
675 if ("*".equals(separateProcesses)) {
676 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
677 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800678 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 } else {
680 mDefParseFlags = 0;
681 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800682 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 + separateProcesses);
684 }
685 } else {
686 mDefParseFlags = 0;
687 mSeparateProcesses = null;
688 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 Installer installer = new Installer();
691 // Little hacky thing to check if installd is here, to determine
692 // whether we are running on the simulator and thus need to take
693 // care of building the /data file structure ourself.
694 // (apparently the sim now has a working installer)
695 if (installer.ping() && Process.supportsProcesses()) {
696 mInstaller = installer;
697 } else {
698 mInstaller = null;
699 }
700
701 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
702 Display d = wm.getDefaultDisplay();
703 d.getMetrics(mMetrics);
704
705 synchronized (mInstallLock) {
706 synchronized (mPackages) {
707 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700708 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 File dataDir = Environment.getDataDirectory();
711 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800712 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
714
715 if (mInstaller == null) {
716 // Make sure these dirs exist, when we are running in
717 // the simulator.
718 // Make a wide-open directory for random misc stuff.
719 File miscDir = new File(dataDir, "misc");
720 miscDir.mkdirs();
721 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800722 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 mDrmAppPrivateInstallDir.mkdirs();
724 }
725
726 readPermissions();
727
728 mRestoredSettings = mSettings.readLP();
729 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800730
731 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800733
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800734 // Set flag to monitor and not change apk file paths when
735 // scanning install directories.
736 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700737 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800738 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800739 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700745 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700748 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 /**
751 * Out of paranoia, ensure that everything in the boot class
752 * path has been dexed.
753 */
754 String bootClassPath = System.getProperty("java.boot.class.path");
755 if (bootClassPath != null) {
756 String[] paths = splitString(bootClassPath, ':');
757 for (int i=0; i<paths.length; i++) {
758 try {
759 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
760 libFiles.add(paths[i]);
761 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700762 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 }
764 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800765 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800767 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 }
769 }
770 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800771 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 /**
775 * Also ensure all external libraries have had dexopt run on them.
776 */
777 if (mSharedLibraries.size() > 0) {
778 Iterator<String> libs = mSharedLibraries.values().iterator();
779 while (libs.hasNext()) {
780 String lib = libs.next();
781 try {
782 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
783 libFiles.add(lib);
784 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700785 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 }
787 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800788 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800790 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 }
792 }
793 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 // Gross hack for now: we know this file doesn't contain any
796 // code, so don't dexopt it to avoid the resulting log spew.
797 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 /**
800 * And there are a number of commands implemented in Java, which
801 * we currently need to do the dexopt on so that they can be
802 * run from a non-root shell.
803 */
804 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700805 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 for (int i=0; i<frameworkFiles.length; i++) {
807 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
808 String path = libPath.getPath();
809 // Skip the file if we alrady did it.
810 if (libFiles.contains(path)) {
811 continue;
812 }
813 // Skip the file if it is not a type we want to dexopt.
814 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
815 continue;
816 }
817 try {
818 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
819 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700820 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 }
822 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800823 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800825 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 }
827 }
828 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800829
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700830 if (didDexOpt) {
831 // If we had to do a dexopt of one of the previous
832 // things, then something on the system has changed.
833 // Consider this significant, and wipe away all other
834 // existing dexopt files to ensure we don't leave any
835 // dangling around.
836 String[] files = mDalvikCacheDir.list();
837 if (files != null) {
838 for (int i=0; i<files.length; i++) {
839 String fn = files[i];
840 if (fn.startsWith("data@app@")
841 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800842 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700843 (new File(mDalvikCacheDir, fn)).delete();
844 }
845 }
846 }
847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800849
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800850 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 mFrameworkInstallObserver = new AppDirObserver(
852 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
853 mFrameworkInstallObserver.startWatching();
854 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800855 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800856
857 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
859 mSystemInstallObserver = new AppDirObserver(
860 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
861 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800862 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800863
864 if (mInstaller != null) {
865 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
866 mInstaller.moveFiles();
867 }
868
869 // Prune any system packages that no longer exist.
870 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
871 while (psit.hasNext()) {
872 PackageSetting ps = psit.next();
873 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800874 && !mPackages.containsKey(ps.name)
875 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800876 psit.remove();
877 String msg = "System package " + ps.name
878 + " no longer exists; wiping its data";
879 reportSettingsProblem(Log.WARN, msg);
880 if (mInstaller != null) {
881 // XXX how to set useEncryptedFSDir for packages that
882 // are not encrypted?
883 mInstaller.remove(ps.name, true);
884 }
885 }
886 }
887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 mAppInstallDir = new File(dataDir, "app");
889 if (mInstaller == null) {
890 // Make sure these dirs exist, when we are running in
891 // the simulator.
892 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
893 }
894 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800895 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 //clean up list
897 for(int i = 0; i < deletePkgsList.size(); i++) {
898 //clean up here
899 cleanupInstallFailedPackage(deletePkgsList.get(i));
900 }
901 //delete tmp files
902 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800903
904 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 SystemClock.uptimeMillis());
906 mAppInstallObserver = new AppDirObserver(
907 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
908 mAppInstallObserver.startWatching();
909 scanDirLI(mAppInstallDir, 0, scanMode);
910
911 mDrmAppInstallObserver = new AppDirObserver(
912 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
913 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800914 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800916 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800918 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 + ((SystemClock.uptimeMillis()-startTime)/1000f)
920 + " seconds");
921
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700922 updatePermissionsLP(null, null, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923
924 mSettings.writeLP();
925
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800926 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 // Now after opening every single application zip, make sure they
930 // are all flushed. Not really needed, but keeps things nice and
931 // tidy.
932 Runtime.getRuntime().gc();
933 } // synchronized (mPackages)
934 } // synchronized (mInstallLock)
935 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 @Override
938 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
939 throws RemoteException {
940 try {
941 return super.onTransact(code, data, reply, flags);
942 } catch (RuntimeException e) {
943 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800944 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 }
946 throw e;
947 }
948 }
949
Dianne Hackborne6620b22010-01-22 14:46:21 -0800950 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800951 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800953 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
954 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800956 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800957 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 }
959 } else {
960 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800961 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 File dataDir = new File(pkg.applicationInfo.dataDir);
963 dataDir.delete();
964 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800965 if (ps.codePath != null) {
966 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800967 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800968 }
969 }
970 if (ps.resourcePath != null) {
971 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800972 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800973 }
974 }
975 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 }
977
978 void readPermissions() {
979 // Read permissions from .../etc/permission directory.
980 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
981 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800982 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 return;
984 }
985 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800986 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 return;
988 }
989
990 // Iterate over the files in the directory and scan .xml files
991 for (File f : libraryDir.listFiles()) {
992 // We'll read platform.xml last
993 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
994 continue;
995 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800998 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 continue;
1000 }
1001 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001002 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 continue;
1004 }
1005
1006 readPermissionsFromXml(f);
1007 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1010 final File permFile = new File(Environment.getRootDirectory(),
1011 "etc/permissions/platform.xml");
1012 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001013
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001014 StringBuilder sb = new StringBuilder(128);
1015 sb.append("Libs:");
1016 Iterator<String> it = mSharedLibraries.keySet().iterator();
1017 while (it.hasNext()) {
1018 sb.append(' ');
1019 String name = it.next();
1020 sb.append(name);
1021 sb.append(':');
1022 sb.append(mSharedLibraries.get(name));
1023 }
1024 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001025
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001026 sb.setLength(0);
1027 sb.append("Features:");
1028 it = mAvailableFeatures.keySet().iterator();
1029 while (it.hasNext()) {
1030 sb.append(' ');
1031 sb.append(it.next());
1032 }
1033 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001035
1036 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 FileReader permReader = null;
1038 try {
1039 permReader = new FileReader(permFile);
1040 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001041 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 return;
1043 }
1044
1045 try {
1046 XmlPullParser parser = Xml.newPullParser();
1047 parser.setInput(permReader);
1048
1049 XmlUtils.beginDocument(parser, "permissions");
1050
1051 while (true) {
1052 XmlUtils.nextElement(parser);
1053 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1054 break;
1055 }
1056
1057 String name = parser.getName();
1058 if ("group".equals(name)) {
1059 String gidStr = parser.getAttributeValue(null, "gid");
1060 if (gidStr != null) {
1061 int gid = Integer.parseInt(gidStr);
1062 mGlobalGids = appendInt(mGlobalGids, gid);
1063 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001064 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 + parser.getPositionDescription());
1066 }
1067
1068 XmlUtils.skipCurrentTag(parser);
1069 continue;
1070 } else if ("permission".equals(name)) {
1071 String perm = parser.getAttributeValue(null, "name");
1072 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001073 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 + parser.getPositionDescription());
1075 XmlUtils.skipCurrentTag(parser);
1076 continue;
1077 }
1078 perm = perm.intern();
1079 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 } else if ("assign-permission".equals(name)) {
1082 String perm = parser.getAttributeValue(null, "name");
1083 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001084 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 + parser.getPositionDescription());
1086 XmlUtils.skipCurrentTag(parser);
1087 continue;
1088 }
1089 String uidStr = parser.getAttributeValue(null, "uid");
1090 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001091 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 + parser.getPositionDescription());
1093 XmlUtils.skipCurrentTag(parser);
1094 continue;
1095 }
1096 int uid = Process.getUidForName(uidStr);
1097 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001098 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 + uidStr + "\" at "
1100 + parser.getPositionDescription());
1101 XmlUtils.skipCurrentTag(parser);
1102 continue;
1103 }
1104 perm = perm.intern();
1105 HashSet<String> perms = mSystemPermissions.get(uid);
1106 if (perms == null) {
1107 perms = new HashSet<String>();
1108 mSystemPermissions.put(uid, perms);
1109 }
1110 perms.add(perm);
1111 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 } else if ("library".equals(name)) {
1114 String lname = parser.getAttributeValue(null, "name");
1115 String lfile = parser.getAttributeValue(null, "file");
1116 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001117 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 + parser.getPositionDescription());
1119 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001120 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 + parser.getPositionDescription());
1122 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001123 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001124 mSharedLibraries.put(lname, lfile);
1125 }
1126 XmlUtils.skipCurrentTag(parser);
1127 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001128
Dianne Hackborn49237342009-08-27 20:08:01 -07001129 } else if ("feature".equals(name)) {
1130 String fname = parser.getAttributeValue(null, "name");
1131 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001132 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001133 + parser.getPositionDescription());
1134 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001135 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001136 FeatureInfo fi = new FeatureInfo();
1137 fi.name = fname;
1138 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 }
1140 XmlUtils.skipCurrentTag(parser);
1141 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 } else {
1144 XmlUtils.skipCurrentTag(parser);
1145 continue;
1146 }
1147
1148 }
1149 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001150 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001152 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 }
1154 }
1155
1156 void readPermission(XmlPullParser parser, String name)
1157 throws IOException, XmlPullParserException {
1158
1159 name = name.intern();
1160
1161 BasePermission bp = mSettings.mPermissions.get(name);
1162 if (bp == null) {
1163 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1164 mSettings.mPermissions.put(name, bp);
1165 }
1166 int outerDepth = parser.getDepth();
1167 int type;
1168 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1169 && (type != XmlPullParser.END_TAG
1170 || parser.getDepth() > outerDepth)) {
1171 if (type == XmlPullParser.END_TAG
1172 || type == XmlPullParser.TEXT) {
1173 continue;
1174 }
1175
1176 String tagName = parser.getName();
1177 if ("group".equals(tagName)) {
1178 String gidStr = parser.getAttributeValue(null, "gid");
1179 if (gidStr != null) {
1180 int gid = Process.getGidForName(gidStr);
1181 bp.gids = appendInt(bp.gids, gid);
1182 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001183 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 + parser.getPositionDescription());
1185 }
1186 }
1187 XmlUtils.skipCurrentTag(parser);
1188 }
1189 }
1190
1191 static int[] appendInt(int[] cur, int val) {
1192 if (cur == null) {
1193 return new int[] { val };
1194 }
1195 final int N = cur.length;
1196 for (int i=0; i<N; i++) {
1197 if (cur[i] == val) {
1198 return cur;
1199 }
1200 }
1201 int[] ret = new int[N+1];
1202 System.arraycopy(cur, 0, ret, 0, N);
1203 ret[N] = val;
1204 return ret;
1205 }
1206
1207 static int[] appendInts(int[] cur, int[] add) {
1208 if (add == null) return cur;
1209 if (cur == null) return add;
1210 final int N = add.length;
1211 for (int i=0; i<N; i++) {
1212 cur = appendInt(cur, add[i]);
1213 }
1214 return cur;
1215 }
1216
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001217 static int[] removeInt(int[] cur, int val) {
1218 if (cur == null) {
1219 return null;
1220 }
1221 final int N = cur.length;
1222 for (int i=0; i<N; i++) {
1223 if (cur[i] == val) {
1224 int[] ret = new int[N-1];
1225 if (i > 0) {
1226 System.arraycopy(cur, 0, ret, 0, i);
1227 }
1228 if (i < (N-1)) {
1229 System.arraycopy(cur, i, ret, i+1, N-i-1);
1230 }
1231 return ret;
1232 }
1233 }
1234 return cur;
1235 }
1236
1237 static int[] removeInts(int[] cur, int[] rem) {
1238 if (rem == null) return cur;
1239 if (cur == null) return cur;
1240 final int N = rem.length;
1241 for (int i=0; i<N; i++) {
1242 cur = removeInt(cur, rem[i]);
1243 }
1244 return cur;
1245 }
1246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001248 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1249 // The package has been uninstalled but has retained data and resources.
1250 return PackageParser.generatePackageInfo(p, null, flags);
1251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 final PackageSetting ps = (PackageSetting)p.mExtras;
1253 if (ps == null) {
1254 return null;
1255 }
1256 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1257 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1258 }
1259
1260 public PackageInfo getPackageInfo(String packageName, int flags) {
1261 synchronized (mPackages) {
1262 PackageParser.Package p = mPackages.get(packageName);
1263 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001264 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 + ": " + p);
1266 if (p != null) {
1267 return generatePackageInfo(p, flags);
1268 }
1269 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1270 return generatePackageInfoFromSettingsLP(packageName, flags);
1271 }
1272 }
1273 return null;
1274 }
1275
Dianne Hackborn47096932010-02-11 15:57:09 -08001276 public String[] currentToCanonicalPackageNames(String[] names) {
1277 String[] out = new String[names.length];
1278 synchronized (mPackages) {
1279 for (int i=names.length-1; i>=0; i--) {
1280 PackageSetting ps = mSettings.mPackages.get(names[i]);
1281 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1282 }
1283 }
1284 return out;
1285 }
1286
1287 public String[] canonicalToCurrentPackageNames(String[] names) {
1288 String[] out = new String[names.length];
1289 synchronized (mPackages) {
1290 for (int i=names.length-1; i>=0; i--) {
1291 String cur = mSettings.mRenamedPackages.get(names[i]);
1292 out[i] = cur != null ? cur : names[i];
1293 }
1294 }
1295 return out;
1296 }
1297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 public int getPackageUid(String packageName) {
1299 synchronized (mPackages) {
1300 PackageParser.Package p = mPackages.get(packageName);
1301 if(p != null) {
1302 return p.applicationInfo.uid;
1303 }
1304 PackageSetting ps = mSettings.mPackages.get(packageName);
1305 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1306 return -1;
1307 }
1308 p = ps.pkg;
1309 return p != null ? p.applicationInfo.uid : -1;
1310 }
1311 }
1312
1313 public int[] getPackageGids(String packageName) {
1314 synchronized (mPackages) {
1315 PackageParser.Package p = mPackages.get(packageName);
1316 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001317 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 + ": " + p);
1319 if (p != null) {
1320 final PackageSetting ps = (PackageSetting)p.mExtras;
1321 final SharedUserSetting suid = ps.sharedUser;
1322 return suid != null ? suid.gids : ps.gids;
1323 }
1324 }
1325 // stupid thing to indicate an error.
1326 return new int[0];
1327 }
1328
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001329 static final PermissionInfo generatePermissionInfo(
1330 BasePermission bp, int flags) {
1331 if (bp.perm != null) {
1332 return PackageParser.generatePermissionInfo(bp.perm, flags);
1333 }
1334 PermissionInfo pi = new PermissionInfo();
1335 pi.name = bp.name;
1336 pi.packageName = bp.sourcePackage;
1337 pi.nonLocalizedLabel = bp.name;
1338 pi.protectionLevel = bp.protectionLevel;
1339 return pi;
1340 }
1341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 public PermissionInfo getPermissionInfo(String name, int flags) {
1343 synchronized (mPackages) {
1344 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001345 if (p != null) {
1346 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 }
1348 return null;
1349 }
1350 }
1351
1352 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1353 synchronized (mPackages) {
1354 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1355 for (BasePermission p : mSettings.mPermissions.values()) {
1356 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001357 if (p.perm == null || p.perm.info.group == null) {
1358 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 }
1360 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001361 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1363 }
1364 }
1365 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 if (out.size() > 0) {
1368 return out;
1369 }
1370 return mPermissionGroups.containsKey(group) ? out : null;
1371 }
1372 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1375 synchronized (mPackages) {
1376 return PackageParser.generatePermissionGroupInfo(
1377 mPermissionGroups.get(name), flags);
1378 }
1379 }
1380
1381 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1382 synchronized (mPackages) {
1383 final int N = mPermissionGroups.size();
1384 ArrayList<PermissionGroupInfo> out
1385 = new ArrayList<PermissionGroupInfo>(N);
1386 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1387 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1388 }
1389 return out;
1390 }
1391 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1394 PackageSetting ps = mSettings.mPackages.get(packageName);
1395 if(ps != null) {
1396 if(ps.pkg == null) {
1397 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1398 if(pInfo != null) {
1399 return pInfo.applicationInfo;
1400 }
1401 return null;
1402 }
1403 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1404 }
1405 return null;
1406 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1409 PackageSetting ps = mSettings.mPackages.get(packageName);
1410 if(ps != null) {
1411 if(ps.pkg == null) {
1412 ps.pkg = new PackageParser.Package(packageName);
1413 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001414 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1415 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1416 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1417 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419 return generatePackageInfo(ps.pkg, flags);
1420 }
1421 return null;
1422 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1425 synchronized (mPackages) {
1426 PackageParser.Package p = mPackages.get(packageName);
1427 if (Config.LOGV) Log.v(
1428 TAG, "getApplicationInfo " + packageName
1429 + ": " + p);
1430 if (p != null) {
1431 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001432 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 }
1434 if ("android".equals(packageName)||"system".equals(packageName)) {
1435 return mAndroidApplication;
1436 }
1437 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1438 return generateApplicationInfoFromSettingsLP(packageName, flags);
1439 }
1440 }
1441 return null;
1442 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001443
1444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1446 mContext.enforceCallingOrSelfPermission(
1447 android.Manifest.permission.CLEAR_APP_CACHE, null);
1448 // Queue up an async operation since clearing cache may take a little while.
1449 mHandler.post(new Runnable() {
1450 public void run() {
1451 mHandler.removeCallbacks(this);
1452 int retCode = -1;
1453 if (mInstaller != null) {
1454 retCode = mInstaller.freeCache(freeStorageSize);
1455 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001456 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 }
1458 } //end if mInstaller
1459 if (observer != null) {
1460 try {
1461 observer.onRemoveCompleted(null, (retCode >= 0));
1462 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001463 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 }
1465 }
1466 }
1467 });
1468 }
1469
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001470 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001471 mContext.enforceCallingOrSelfPermission(
1472 android.Manifest.permission.CLEAR_APP_CACHE, null);
1473 // Queue up an async operation since clearing cache may take a little while.
1474 mHandler.post(new Runnable() {
1475 public void run() {
1476 mHandler.removeCallbacks(this);
1477 int retCode = -1;
1478 if (mInstaller != null) {
1479 retCode = mInstaller.freeCache(freeStorageSize);
1480 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001481 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001482 }
1483 }
1484 if(pi != null) {
1485 try {
1486 // Callback via pending intent
1487 int code = (retCode >= 0) ? 1 : 0;
1488 pi.sendIntent(null, code, null,
1489 null, null);
1490 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001491 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001492 }
1493 }
1494 }
1495 });
1496 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1499 synchronized (mPackages) {
1500 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001501
1502 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001504 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 }
1506 if (mResolveComponentName.equals(component)) {
1507 return mResolveActivity;
1508 }
1509 }
1510 return null;
1511 }
1512
1513 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1514 synchronized (mPackages) {
1515 PackageParser.Activity a = mReceivers.mActivities.get(component);
1516 if (Config.LOGV) Log.v(
1517 TAG, "getReceiverInfo " + component + ": " + a);
1518 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1519 return PackageParser.generateActivityInfo(a, flags);
1520 }
1521 }
1522 return null;
1523 }
1524
1525 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1526 synchronized (mPackages) {
1527 PackageParser.Service s = mServices.mServices.get(component);
1528 if (Config.LOGV) Log.v(
1529 TAG, "getServiceInfo " + component + ": " + s);
1530 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1531 return PackageParser.generateServiceInfo(s, flags);
1532 }
1533 }
1534 return null;
1535 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 public String[] getSystemSharedLibraryNames() {
1538 Set<String> libSet;
1539 synchronized (mPackages) {
1540 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001541 int size = libSet.size();
1542 if (size > 0) {
1543 String[] libs = new String[size];
1544 libSet.toArray(libs);
1545 return libs;
1546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001548 return null;
1549 }
1550
1551 public FeatureInfo[] getSystemAvailableFeatures() {
1552 Collection<FeatureInfo> featSet;
1553 synchronized (mPackages) {
1554 featSet = mAvailableFeatures.values();
1555 int size = featSet.size();
1556 if (size > 0) {
1557 FeatureInfo[] features = new FeatureInfo[size+1];
1558 featSet.toArray(features);
1559 FeatureInfo fi = new FeatureInfo();
1560 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1561 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1562 features[size] = fi;
1563 return features;
1564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 }
1566 return null;
1567 }
1568
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001569 public boolean hasSystemFeature(String name) {
1570 synchronized (mPackages) {
1571 return mAvailableFeatures.containsKey(name);
1572 }
1573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 public int checkPermission(String permName, String pkgName) {
1576 synchronized (mPackages) {
1577 PackageParser.Package p = mPackages.get(pkgName);
1578 if (p != null && p.mExtras != null) {
1579 PackageSetting ps = (PackageSetting)p.mExtras;
1580 if (ps.sharedUser != null) {
1581 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1582 return PackageManager.PERMISSION_GRANTED;
1583 }
1584 } else if (ps.grantedPermissions.contains(permName)) {
1585 return PackageManager.PERMISSION_GRANTED;
1586 }
1587 }
1588 }
1589 return PackageManager.PERMISSION_DENIED;
1590 }
1591
1592 public int checkUidPermission(String permName, int uid) {
1593 synchronized (mPackages) {
1594 Object obj = mSettings.getUserIdLP(uid);
1595 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001596 GrantedPermissions gp = (GrantedPermissions)obj;
1597 if (gp.grantedPermissions.contains(permName)) {
1598 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
1600 } else {
1601 HashSet<String> perms = mSystemPermissions.get(uid);
1602 if (perms != null && perms.contains(permName)) {
1603 return PackageManager.PERMISSION_GRANTED;
1604 }
1605 }
1606 }
1607 return PackageManager.PERMISSION_DENIED;
1608 }
1609
1610 private BasePermission findPermissionTreeLP(String permName) {
1611 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1612 if (permName.startsWith(bp.name) &&
1613 permName.length() > bp.name.length() &&
1614 permName.charAt(bp.name.length()) == '.') {
1615 return bp;
1616 }
1617 }
1618 return null;
1619 }
1620
1621 private BasePermission checkPermissionTreeLP(String permName) {
1622 if (permName != null) {
1623 BasePermission bp = findPermissionTreeLP(permName);
1624 if (bp != null) {
1625 if (bp.uid == Binder.getCallingUid()) {
1626 return bp;
1627 }
1628 throw new SecurityException("Calling uid "
1629 + Binder.getCallingUid()
1630 + " is not allowed to add to permission tree "
1631 + bp.name + " owned by uid " + bp.uid);
1632 }
1633 }
1634 throw new SecurityException("No permission tree found for " + permName);
1635 }
1636
1637 public boolean addPermission(PermissionInfo info) {
1638 synchronized (mPackages) {
1639 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1640 throw new SecurityException("Label must be specified in permission");
1641 }
1642 BasePermission tree = checkPermissionTreeLP(info.name);
1643 BasePermission bp = mSettings.mPermissions.get(info.name);
1644 boolean added = bp == null;
1645 if (added) {
1646 bp = new BasePermission(info.name, tree.sourcePackage,
1647 BasePermission.TYPE_DYNAMIC);
1648 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1649 throw new SecurityException(
1650 "Not allowed to modify non-dynamic permission "
1651 + info.name);
1652 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001653 bp.protectionLevel = info.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 bp.perm = new PackageParser.Permission(tree.perm.owner,
1655 new PermissionInfo(info));
1656 bp.perm.info.packageName = tree.perm.info.packageName;
1657 bp.uid = tree.uid;
1658 if (added) {
1659 mSettings.mPermissions.put(info.name, bp);
1660 }
1661 mSettings.writeLP();
1662 return added;
1663 }
1664 }
1665
1666 public void removePermission(String name) {
1667 synchronized (mPackages) {
1668 checkPermissionTreeLP(name);
1669 BasePermission bp = mSettings.mPermissions.get(name);
1670 if (bp != null) {
1671 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1672 throw new SecurityException(
1673 "Not allowed to modify non-dynamic permission "
1674 + name);
1675 }
1676 mSettings.mPermissions.remove(name);
1677 mSettings.writeLP();
1678 }
1679 }
1680 }
1681
Dianne Hackborn854060af2009-07-09 18:14:31 -07001682 public boolean isProtectedBroadcast(String actionName) {
1683 synchronized (mPackages) {
1684 return mProtectedBroadcasts.contains(actionName);
1685 }
1686 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 public int checkSignatures(String pkg1, String pkg2) {
1689 synchronized (mPackages) {
1690 PackageParser.Package p1 = mPackages.get(pkg1);
1691 PackageParser.Package p2 = mPackages.get(pkg2);
1692 if (p1 == null || p1.mExtras == null
1693 || p2 == null || p2.mExtras == null) {
1694 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1695 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001696 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 }
1698 }
1699
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001700 public int checkUidSignatures(int uid1, int uid2) {
1701 synchronized (mPackages) {
1702 Signature[] s1;
1703 Signature[] s2;
1704 Object obj = mSettings.getUserIdLP(uid1);
1705 if (obj != null) {
1706 if (obj instanceof SharedUserSetting) {
1707 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1708 } else if (obj instanceof PackageSetting) {
1709 s1 = ((PackageSetting)obj).signatures.mSignatures;
1710 } else {
1711 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1712 }
1713 } else {
1714 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1715 }
1716 obj = mSettings.getUserIdLP(uid2);
1717 if (obj != null) {
1718 if (obj instanceof SharedUserSetting) {
1719 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1720 } else if (obj instanceof PackageSetting) {
1721 s2 = ((PackageSetting)obj).signatures.mSignatures;
1722 } else {
1723 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1724 }
1725 } else {
1726 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1727 }
1728 return checkSignaturesLP(s1, s2);
1729 }
1730 }
1731
1732 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1733 if (s1 == null) {
1734 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1736 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1737 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001738 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1740 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001741 final int N1 = s1.length;
1742 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 for (int i=0; i<N1; i++) {
1744 boolean match = false;
1745 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001746 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 match = true;
1748 break;
1749 }
1750 }
1751 if (!match) {
1752 return PackageManager.SIGNATURE_NO_MATCH;
1753 }
1754 }
1755 return PackageManager.SIGNATURE_MATCH;
1756 }
1757
1758 public String[] getPackagesForUid(int uid) {
1759 synchronized (mPackages) {
1760 Object obj = mSettings.getUserIdLP(uid);
1761 if (obj instanceof SharedUserSetting) {
1762 SharedUserSetting sus = (SharedUserSetting)obj;
1763 final int N = sus.packages.size();
1764 String[] res = new String[N];
1765 Iterator<PackageSetting> it = sus.packages.iterator();
1766 int i=0;
1767 while (it.hasNext()) {
1768 res[i++] = it.next().name;
1769 }
1770 return res;
1771 } else if (obj instanceof PackageSetting) {
1772 PackageSetting ps = (PackageSetting)obj;
1773 return new String[] { ps.name };
1774 }
1775 }
1776 return null;
1777 }
1778
1779 public String getNameForUid(int uid) {
1780 synchronized (mPackages) {
1781 Object obj = mSettings.getUserIdLP(uid);
1782 if (obj instanceof SharedUserSetting) {
1783 SharedUserSetting sus = (SharedUserSetting)obj;
1784 return sus.name + ":" + sus.userId;
1785 } else if (obj instanceof PackageSetting) {
1786 PackageSetting ps = (PackageSetting)obj;
1787 return ps.name;
1788 }
1789 }
1790 return null;
1791 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 public int getUidForSharedUser(String sharedUserName) {
1794 if(sharedUserName == null) {
1795 return -1;
1796 }
1797 synchronized (mPackages) {
1798 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1799 if(suid == null) {
1800 return -1;
1801 }
1802 return suid.userId;
1803 }
1804 }
1805
1806 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1807 int flags) {
1808 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001809 return chooseBestActivity(intent, resolvedType, flags, query);
1810 }
1811
Mihai Predaeae850c2009-05-13 10:13:48 +02001812 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1813 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 if (query != null) {
1815 final int N = query.size();
1816 if (N == 1) {
1817 return query.get(0);
1818 } else if (N > 1) {
1819 // If there is more than one activity with the same priority,
1820 // then let the user decide between them.
1821 ResolveInfo r0 = query.get(0);
1822 ResolveInfo r1 = query.get(1);
1823 if (false) {
1824 System.out.println(r0.activityInfo.name +
1825 "=" + r0.priority + " vs " +
1826 r1.activityInfo.name +
1827 "=" + r1.priority);
1828 }
1829 // If the first activity has a higher priority, or a different
1830 // default, then it is always desireable to pick it.
1831 if (r0.priority != r1.priority
1832 || r0.preferredOrder != r1.preferredOrder
1833 || r0.isDefault != r1.isDefault) {
1834 return query.get(0);
1835 }
1836 // If we have saved a preference for a preferred activity for
1837 // this Intent, use that.
1838 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1839 flags, query, r0.priority);
1840 if (ri != null) {
1841 return ri;
1842 }
1843 return mResolveInfo;
1844 }
1845 }
1846 return null;
1847 }
1848
1849 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1850 int flags, List<ResolveInfo> query, int priority) {
1851 synchronized (mPackages) {
1852 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1853 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001854 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1856 if (prefs != null && prefs.size() > 0) {
1857 // First figure out how good the original match set is.
1858 // We will only allow preferred activities that came
1859 // from the same match quality.
1860 int match = 0;
1861 final int N = query.size();
1862 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1863 for (int j=0; j<N; j++) {
1864 ResolveInfo ri = query.get(j);
1865 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1866 + ": 0x" + Integer.toHexString(match));
1867 if (ri.match > match) match = ri.match;
1868 }
1869 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1870 + Integer.toHexString(match));
1871 match &= IntentFilter.MATCH_CATEGORY_MASK;
1872 final int M = prefs.size();
1873 for (int i=0; i<M; i++) {
1874 PreferredActivity pa = prefs.get(i);
1875 if (pa.mMatch != match) {
1876 continue;
1877 }
1878 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1879 if (DEBUG_PREFERRED) {
1880 Log.v(TAG, "Got preferred activity:");
1881 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1882 }
1883 if (ai != null) {
1884 for (int j=0; j<N; j++) {
1885 ResolveInfo ri = query.get(j);
1886 if (!ri.activityInfo.applicationInfo.packageName
1887 .equals(ai.applicationInfo.packageName)) {
1888 continue;
1889 }
1890 if (!ri.activityInfo.name.equals(ai.name)) {
1891 continue;
1892 }
1893
1894 // Okay we found a previously set preferred app.
1895 // If the result set is different from when this
1896 // was created, we need to clear it and re-ask the
1897 // user their preference.
1898 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001899 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 + intent + " type " + resolvedType);
1901 mSettings.mPreferredActivities.removeFilter(pa);
1902 return null;
1903 }
1904
1905 // Yay!
1906 return ri;
1907 }
1908 }
1909 }
1910 }
1911 }
1912 return null;
1913 }
1914
1915 public List<ResolveInfo> queryIntentActivities(Intent intent,
1916 String resolvedType, int flags) {
1917 ComponentName comp = intent.getComponent();
1918 if (comp != null) {
1919 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1920 ActivityInfo ai = getActivityInfo(comp, flags);
1921 if (ai != null) {
1922 ResolveInfo ri = new ResolveInfo();
1923 ri.activityInfo = ai;
1924 list.add(ri);
1925 }
1926 return list;
1927 }
1928
1929 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001930 String pkgName = intent.getPackage();
1931 if (pkgName == null) {
1932 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1933 resolvedType, flags);
1934 }
1935 PackageParser.Package pkg = mPackages.get(pkgName);
1936 if (pkg != null) {
1937 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1938 resolvedType, flags, pkg.activities);
1939 }
1940 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 }
1942 }
1943
1944 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1945 Intent[] specifics, String[] specificTypes, Intent intent,
1946 String resolvedType, int flags) {
1947 final String resultsAction = intent.getAction();
1948
1949 List<ResolveInfo> results = queryIntentActivities(
1950 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1951 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1952
1953 int specificsPos = 0;
1954 int N;
1955
1956 // todo: note that the algorithm used here is O(N^2). This
1957 // isn't a problem in our current environment, but if we start running
1958 // into situations where we have more than 5 or 10 matches then this
1959 // should probably be changed to something smarter...
1960
1961 // First we go through and resolve each of the specific items
1962 // that were supplied, taking care of removing any corresponding
1963 // duplicate items in the generic resolve list.
1964 if (specifics != null) {
1965 for (int i=0; i<specifics.length; i++) {
1966 final Intent sintent = specifics[i];
1967 if (sintent == null) {
1968 continue;
1969 }
1970
1971 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1972 String action = sintent.getAction();
1973 if (resultsAction != null && resultsAction.equals(action)) {
1974 // If this action was explicitly requested, then don't
1975 // remove things that have it.
1976 action = null;
1977 }
1978 ComponentName comp = sintent.getComponent();
1979 ResolveInfo ri = null;
1980 ActivityInfo ai = null;
1981 if (comp == null) {
1982 ri = resolveIntent(
1983 sintent,
1984 specificTypes != null ? specificTypes[i] : null,
1985 flags);
1986 if (ri == null) {
1987 continue;
1988 }
1989 if (ri == mResolveInfo) {
1990 // ACK! Must do something better with this.
1991 }
1992 ai = ri.activityInfo;
1993 comp = new ComponentName(ai.applicationInfo.packageName,
1994 ai.name);
1995 } else {
1996 ai = getActivityInfo(comp, flags);
1997 if (ai == null) {
1998 continue;
1999 }
2000 }
2001
2002 // Look for any generic query activities that are duplicates
2003 // of this specific one, and remove them from the results.
2004 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2005 N = results.size();
2006 int j;
2007 for (j=specificsPos; j<N; j++) {
2008 ResolveInfo sri = results.get(j);
2009 if ((sri.activityInfo.name.equals(comp.getClassName())
2010 && sri.activityInfo.applicationInfo.packageName.equals(
2011 comp.getPackageName()))
2012 || (action != null && sri.filter.matchAction(action))) {
2013 results.remove(j);
2014 if (Config.LOGV) Log.v(
2015 TAG, "Removing duplicate item from " + j
2016 + " due to specific " + specificsPos);
2017 if (ri == null) {
2018 ri = sri;
2019 }
2020 j--;
2021 N--;
2022 }
2023 }
2024
2025 // Add this specific item to its proper place.
2026 if (ri == null) {
2027 ri = new ResolveInfo();
2028 ri.activityInfo = ai;
2029 }
2030 results.add(specificsPos, ri);
2031 ri.specificIndex = i;
2032 specificsPos++;
2033 }
2034 }
2035
2036 // Now we go through the remaining generic results and remove any
2037 // duplicate actions that are found here.
2038 N = results.size();
2039 for (int i=specificsPos; i<N-1; i++) {
2040 final ResolveInfo rii = results.get(i);
2041 if (rii.filter == null) {
2042 continue;
2043 }
2044
2045 // Iterate over all of the actions of this result's intent
2046 // filter... typically this should be just one.
2047 final Iterator<String> it = rii.filter.actionsIterator();
2048 if (it == null) {
2049 continue;
2050 }
2051 while (it.hasNext()) {
2052 final String action = it.next();
2053 if (resultsAction != null && resultsAction.equals(action)) {
2054 // If this action was explicitly requested, then don't
2055 // remove things that have it.
2056 continue;
2057 }
2058 for (int j=i+1; j<N; j++) {
2059 final ResolveInfo rij = results.get(j);
2060 if (rij.filter != null && rij.filter.hasAction(action)) {
2061 results.remove(j);
2062 if (Config.LOGV) Log.v(
2063 TAG, "Removing duplicate item from " + j
2064 + " due to action " + action + " at " + i);
2065 j--;
2066 N--;
2067 }
2068 }
2069 }
2070
2071 // If the caller didn't request filter information, drop it now
2072 // so we don't have to marshall/unmarshall it.
2073 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2074 rii.filter = null;
2075 }
2076 }
2077
2078 // Filter out the caller activity if so requested.
2079 if (caller != null) {
2080 N = results.size();
2081 for (int i=0; i<N; i++) {
2082 ActivityInfo ainfo = results.get(i).activityInfo;
2083 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2084 && caller.getClassName().equals(ainfo.name)) {
2085 results.remove(i);
2086 break;
2087 }
2088 }
2089 }
2090
2091 // If the caller didn't request filter information,
2092 // drop them now so we don't have to
2093 // marshall/unmarshall it.
2094 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2095 N = results.size();
2096 for (int i=0; i<N; i++) {
2097 results.get(i).filter = null;
2098 }
2099 }
2100
2101 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2102 return results;
2103 }
2104
2105 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2106 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002107 ComponentName comp = intent.getComponent();
2108 if (comp != null) {
2109 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2110 ActivityInfo ai = getReceiverInfo(comp, flags);
2111 if (ai != null) {
2112 ResolveInfo ri = new ResolveInfo();
2113 ri.activityInfo = ai;
2114 list.add(ri);
2115 }
2116 return list;
2117 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002120 String pkgName = intent.getPackage();
2121 if (pkgName == null) {
2122 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2123 resolvedType, flags);
2124 }
2125 PackageParser.Package pkg = mPackages.get(pkgName);
2126 if (pkg != null) {
2127 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2128 resolvedType, flags, pkg.receivers);
2129 }
2130 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 }
2132 }
2133
2134 public ResolveInfo resolveService(Intent intent, String resolvedType,
2135 int flags) {
2136 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2137 flags);
2138 if (query != null) {
2139 if (query.size() >= 1) {
2140 // If there is more than one service with the same priority,
2141 // just arbitrarily pick the first one.
2142 return query.get(0);
2143 }
2144 }
2145 return null;
2146 }
2147
2148 public List<ResolveInfo> queryIntentServices(Intent intent,
2149 String resolvedType, int flags) {
2150 ComponentName comp = intent.getComponent();
2151 if (comp != null) {
2152 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2153 ServiceInfo si = getServiceInfo(comp, flags);
2154 if (si != null) {
2155 ResolveInfo ri = new ResolveInfo();
2156 ri.serviceInfo = si;
2157 list.add(ri);
2158 }
2159 return list;
2160 }
2161
2162 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002163 String pkgName = intent.getPackage();
2164 if (pkgName == null) {
2165 return (List<ResolveInfo>)mServices.queryIntent(intent,
2166 resolvedType, flags);
2167 }
2168 PackageParser.Package pkg = mPackages.get(pkgName);
2169 if (pkg != null) {
2170 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2171 resolvedType, flags, pkg.services);
2172 }
2173 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 }
2175 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 public List<PackageInfo> getInstalledPackages(int flags) {
2178 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2179
2180 synchronized (mPackages) {
2181 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2182 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2183 while (i.hasNext()) {
2184 final PackageSetting ps = i.next();
2185 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2186 if(psPkg != null) {
2187 finalList.add(psPkg);
2188 }
2189 }
2190 }
2191 else {
2192 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2193 while (i.hasNext()) {
2194 final PackageParser.Package p = i.next();
2195 if (p.applicationInfo != null) {
2196 PackageInfo pi = generatePackageInfo(p, flags);
2197 if(pi != null) {
2198 finalList.add(pi);
2199 }
2200 }
2201 }
2202 }
2203 }
2204 return finalList;
2205 }
2206
2207 public List<ApplicationInfo> getInstalledApplications(int flags) {
2208 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2209 synchronized(mPackages) {
2210 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2211 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2212 while (i.hasNext()) {
2213 final PackageSetting ps = i.next();
2214 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2215 if(ai != null) {
2216 finalList.add(ai);
2217 }
2218 }
2219 }
2220 else {
2221 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2222 while (i.hasNext()) {
2223 final PackageParser.Package p = i.next();
2224 if (p.applicationInfo != null) {
2225 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2226 if(ai != null) {
2227 finalList.add(ai);
2228 }
2229 }
2230 }
2231 }
2232 }
2233 return finalList;
2234 }
2235
2236 public List<ApplicationInfo> getPersistentApplications(int flags) {
2237 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2238
2239 synchronized (mPackages) {
2240 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2241 while (i.hasNext()) {
2242 PackageParser.Package p = i.next();
2243 if (p.applicationInfo != null
2244 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2245 && (!mSafeMode || (p.applicationInfo.flags
2246 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2247 finalList.add(p.applicationInfo);
2248 }
2249 }
2250 }
2251
2252 return finalList;
2253 }
2254
2255 public ProviderInfo resolveContentProvider(String name, int flags) {
2256 synchronized (mPackages) {
2257 final PackageParser.Provider provider = mProviders.get(name);
2258 return provider != null
2259 && mSettings.isEnabledLP(provider.info, flags)
2260 && (!mSafeMode || (provider.info.applicationInfo.flags
2261 &ApplicationInfo.FLAG_SYSTEM) != 0)
2262 ? PackageParser.generateProviderInfo(provider, flags)
2263 : null;
2264 }
2265 }
2266
Fred Quintana718d8a22009-04-29 17:53:20 -07002267 /**
2268 * @deprecated
2269 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002270 public void querySyncProviders(List outNames, List outInfo) {
2271 synchronized (mPackages) {
2272 Iterator<Map.Entry<String, PackageParser.Provider>> i
2273 = mProviders.entrySet().iterator();
2274
2275 while (i.hasNext()) {
2276 Map.Entry<String, PackageParser.Provider> entry = i.next();
2277 PackageParser.Provider p = entry.getValue();
2278
2279 if (p.syncable
2280 && (!mSafeMode || (p.info.applicationInfo.flags
2281 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2282 outNames.add(entry.getKey());
2283 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2284 }
2285 }
2286 }
2287 }
2288
2289 public List<ProviderInfo> queryContentProviders(String processName,
2290 int uid, int flags) {
2291 ArrayList<ProviderInfo> finalList = null;
2292
2293 synchronized (mPackages) {
2294 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2295 while (i.hasNext()) {
2296 PackageParser.Provider p = i.next();
2297 if (p.info.authority != null
2298 && (processName == null ||
2299 (p.info.processName.equals(processName)
2300 && p.info.applicationInfo.uid == uid))
2301 && mSettings.isEnabledLP(p.info, flags)
2302 && (!mSafeMode || (p.info.applicationInfo.flags
2303 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2304 if (finalList == null) {
2305 finalList = new ArrayList<ProviderInfo>(3);
2306 }
2307 finalList.add(PackageParser.generateProviderInfo(p,
2308 flags));
2309 }
2310 }
2311 }
2312
2313 if (finalList != null) {
2314 Collections.sort(finalList, mProviderInitOrderSorter);
2315 }
2316
2317 return finalList;
2318 }
2319
2320 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2321 int flags) {
2322 synchronized (mPackages) {
2323 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2324 return PackageParser.generateInstrumentationInfo(i, flags);
2325 }
2326 }
2327
2328 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2329 int flags) {
2330 ArrayList<InstrumentationInfo> finalList =
2331 new ArrayList<InstrumentationInfo>();
2332
2333 synchronized (mPackages) {
2334 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2335 while (i.hasNext()) {
2336 PackageParser.Instrumentation p = i.next();
2337 if (targetPackage == null
2338 || targetPackage.equals(p.info.targetPackage)) {
2339 finalList.add(PackageParser.generateInstrumentationInfo(p,
2340 flags));
2341 }
2342 }
2343 }
2344
2345 return finalList;
2346 }
2347
2348 private void scanDirLI(File dir, int flags, int scanMode) {
2349 Log.d(TAG, "Scanning app dir " + dir);
2350
2351 String[] files = dir.list();
2352
2353 int i;
2354 for (i=0; i<files.length; i++) {
2355 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002356 if (!isPackageFilename(files[i])) {
2357 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002358 continue;
2359 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002360 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002362 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002363 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2364 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002365 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002366 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002367 file.delete();
2368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 }
2370 }
2371
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002372 private static File getSettingsProblemFile() {
2373 File dataDir = Environment.getDataDirectory();
2374 File systemDir = new File(dataDir, "system");
2375 File fname = new File(systemDir, "uiderrors.txt");
2376 return fname;
2377 }
2378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 private static void reportSettingsProblem(int priority, String msg) {
2380 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002381 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 FileOutputStream out = new FileOutputStream(fname, true);
2383 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002384 SimpleDateFormat formatter = new SimpleDateFormat();
2385 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2386 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 pw.close();
2388 FileUtils.setPermissions(
2389 fname.toString(),
2390 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2391 -1, -1);
2392 } catch (java.io.IOException e) {
2393 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002394 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 }
2396
2397 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2398 PackageParser.Package pkg, File srcFile, int parseFlags) {
2399 if (GET_CERTIFICATES) {
2400 if (ps == null || !ps.codePath.equals(srcFile)
2401 || ps.getTimeStamp() != srcFile.lastModified()) {
2402 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2403 if (!pp.collectCertificates(pkg, parseFlags)) {
2404 mLastScanError = pp.getParseError();
2405 return false;
2406 }
2407 }
2408 }
2409 return true;
2410 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 /*
2413 * Scan a package and return the newly parsed package.
2414 * Returns null in case of errors and the error code is stored in mLastScanError
2415 */
2416 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002417 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002419 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002421 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002424 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 if (pkg == null) {
2426 mLastScanError = pp.getParseError();
2427 return null;
2428 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002429 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 PackageSetting updatedPkg;
2431 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002432 // Look to see if we already know about this package.
2433 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002434 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002435 // This package has been renamed to its original name. Let's
2436 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002437 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002438 }
2439 // If there was no original package, see one for the real package name.
2440 if (ps == null) {
2441 ps = mSettings.peekPackageLP(pkg.packageName);
2442 }
2443 // Check to see if this package could be hiding/updating a system
2444 // package. Must look for it either under the original or real
2445 // package name depending on our state.
2446 updatedPkg = mSettings.mDisabledSysPackages.get(
2447 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002449 // First check if this is a system package that may involve an update
2450 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2451 if (!ps.codePath.equals(scanFile)) {
2452 // The path has changed from what was last scanned... check the
2453 // version of the new path against what we have stored to determine
2454 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002455 if (pkg.mVersionCode < ps.versionCode) {
2456 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002457 // Ignore entry. Skip it.
2458 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2459 + "ignored: updated version " + ps.versionCode
2460 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002461 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2462 return null;
2463 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002464 // The current app on the system partion is better than
2465 // what we have updated to on the data partition; switch
2466 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002467 // At this point, its safely assumed that package installation for
2468 // apps in system partition will go through. If not there won't be a working
2469 // version of the app
2470 synchronized (mPackages) {
2471 // Just remove the loaded entries from package lists.
2472 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002473 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002474 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002475 + "reverting from " + ps.codePathString
2476 + ": new version " + pkg.mVersionCode
2477 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002478 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2479 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002480 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 }
2483 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002484 if (updatedPkg != null) {
2485 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2486 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2487 }
2488 // Verify certificates against what was last scanned
2489 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002490 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002491 return null;
2492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 // The apk is forward locked (not public) if its code and resources
2494 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002495 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002497 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002498 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002499
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002500 String codePath = null;
2501 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002502 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2503 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002504 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002505 } else {
2506 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002507 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002508 }
2509 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002510 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002511 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002512 codePath = pkg.mScanPath;
2513 // Set application objects path explicitly.
2514 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002516 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 }
2518
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002519 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2520 String destCodePath, String destResPath) {
2521 pkg.mPath = pkg.mScanPath = destCodePath;
2522 pkg.applicationInfo.sourceDir = destCodePath;
2523 pkg.applicationInfo.publicSourceDir = destResPath;
2524 }
2525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 private static String fixProcessName(String defProcessName,
2527 String processName, int uid) {
2528 if (processName == null) {
2529 return defProcessName;
2530 }
2531 return processName;
2532 }
2533
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002534 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2536 if (pkg.mSignatures != null) {
2537 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2538 updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002539 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 + " signatures do not match the previously installed version; ignoring!");
2541 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2542 return false;
2543 }
2544
2545 if (pkgSetting.sharedUser != null) {
2546 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2547 pkg.mSignatures, updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002548 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 + " has no signatures that match those in shared user "
2550 + pkgSetting.sharedUser.name + "; ignoring!");
2551 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2552 return false;
2553 }
2554 }
2555 } else {
2556 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2557 }
2558 return true;
2559 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002560
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002561 public boolean performDexOpt(String packageName) {
2562 if (!mNoDexOpt) {
2563 return false;
2564 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002565
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002566 PackageParser.Package p;
2567 synchronized (mPackages) {
2568 p = mPackages.get(packageName);
2569 if (p == null || p.mDidDexOpt) {
2570 return false;
2571 }
2572 }
2573 synchronized (mInstallLock) {
2574 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2575 }
2576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002577
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002578 static final int DEX_OPT_SKIPPED = 0;
2579 static final int DEX_OPT_PERFORMED = 1;
2580 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002581
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002582 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2583 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002584 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002585 String path = pkg.mScanPath;
2586 int ret = 0;
2587 try {
2588 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002589 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002590 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002591 pkg.mDidDexOpt = true;
2592 performed = true;
2593 }
2594 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002595 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002596 ret = -1;
2597 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002598 Slog.w(TAG, "Exception reading apk: " + path, e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002599 ret = -1;
2600 }
2601 if (ret < 0) {
2602 //error from installer
2603 return DEX_OPT_FAILED;
2604 }
2605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002606
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002607 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2608 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002609
2610 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2611 return Environment.isEncryptedFilesystemEnabled() &&
2612 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2613 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002614
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002615 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2616 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002617 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002618 + " to " + newPkg.packageName
2619 + ": old package not in system partition");
2620 return false;
2621 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002622 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002623 + " to " + newPkg.packageName
2624 + ": old package still exists");
2625 return false;
2626 }
2627 return true;
2628 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002629
2630 private File getDataPathForPackage(PackageParser.Package pkg) {
2631 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2632 File dataPath;
2633 if (useEncryptedFSDir) {
2634 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2635 } else {
2636 dataPath = new File(mAppDataDir, pkg.packageName);
2637 }
2638 return dataPath;
2639 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002640
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002641 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2642 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002643 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002644 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2645 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002646 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002647 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002648 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2649 return null;
2650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 mScanningPath = scanFile;
2652 if (pkg == null) {
2653 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2654 return null;
2655 }
2656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2658 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2659 }
2660
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002661 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 synchronized (mPackages) {
2663 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002664 Slog.w(TAG, "*************************************************");
2665 Slog.w(TAG, "Core android package being redefined. Skipping.");
2666 Slog.w(TAG, " file=" + mScanningPath);
2667 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2669 return null;
2670 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 // Set up information for our fall-back user intent resolution
2673 // activity.
2674 mPlatformPackage = pkg;
2675 pkg.mVersionCode = mSdkVersion;
2676 mAndroidApplication = pkg.applicationInfo;
2677 mResolveActivity.applicationInfo = mAndroidApplication;
2678 mResolveActivity.name = ResolverActivity.class.getName();
2679 mResolveActivity.packageName = mAndroidApplication.packageName;
2680 mResolveActivity.processName = mAndroidApplication.processName;
2681 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2682 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2683 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2684 mResolveActivity.exported = true;
2685 mResolveActivity.enabled = true;
2686 mResolveInfo.activityInfo = mResolveActivity;
2687 mResolveInfo.priority = 0;
2688 mResolveInfo.preferredOrder = 0;
2689 mResolveInfo.match = 0;
2690 mResolveComponentName = new ComponentName(
2691 mAndroidApplication.packageName, mResolveActivity.name);
2692 }
2693 }
2694
2695 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002696 TAG, "Scanning package " + pkg.packageName);
2697 if (mPackages.containsKey(pkg.packageName)
2698 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002699 Slog.w(TAG, "*************************************************");
2700 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002702 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2704 return null;
2705 }
2706
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002707 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002708 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2709 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 SharedUserSetting suid = null;
2712 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002715
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002716 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2717 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002718 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002719 pkg.mRealPackage = null;
2720 pkg.mAdoptPermissions = null;
2721 }
2722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 synchronized (mPackages) {
2724 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002725 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2726 if (mTmpSharedLibraries == null ||
2727 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2728 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2729 }
2730 int num = 0;
2731 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2732 for (int i=0; i<N; i++) {
2733 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002735 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002737 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2739 return null;
2740 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002741 mTmpSharedLibraries[num] = file;
2742 num++;
2743 }
2744 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2745 for (int i=0; i<N; i++) {
2746 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2747 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002748 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002749 + " desires unavailable shared library "
2750 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2751 } else {
2752 mTmpSharedLibraries[num] = file;
2753 num++;
2754 }
2755 }
2756 if (num > 0) {
2757 pkg.usesLibraryFiles = new String[num];
2758 System.arraycopy(mTmpSharedLibraries, 0,
2759 pkg.usesLibraryFiles, 0, num);
2760 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002761
Dianne Hackborn49237342009-08-27 20:08:01 -07002762 if (pkg.reqFeatures != null) {
2763 N = pkg.reqFeatures.size();
2764 for (int i=0; i<N; i++) {
2765 FeatureInfo fi = pkg.reqFeatures.get(i);
2766 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2767 // Don't care.
2768 continue;
2769 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002770
Dianne Hackborn49237342009-08-27 20:08:01 -07002771 if (fi.name != null) {
2772 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002773 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002774 + " requires unavailable feature "
2775 + fi.name + "; failing!");
2776 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2777 return null;
2778 }
2779 }
2780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 }
2782 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 if (pkg.mSharedUserId != null) {
2785 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2786 pkg.applicationInfo.flags, true);
2787 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002788 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 + " for shared user failed");
2790 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2791 return null;
2792 }
2793 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2794 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2795 + suid.userId + "): packages=" + suid.packages);
2796 }
2797 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002798
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002799 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002800 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002801 Log.w(TAG, "WAITING FOR DEBUGGER");
2802 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002803 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2804 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002805 }
2806 }
2807
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002808 // Check if we are renaming from an original package name.
2809 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002810 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002811 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002812 // This package may need to be renamed to a previously
2813 // installed name. Let's check on that...
2814 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002815 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002816 // This package had originally been installed as the
2817 // original name, and we have already taken care of
2818 // transitioning to the new one. Just update the new
2819 // one to continue using the old name.
2820 realName = pkg.mRealPackage;
2821 if (!pkg.packageName.equals(renamed)) {
2822 // Callers into this function may have already taken
2823 // care of renaming the package; only do it here if
2824 // it is not already done.
2825 pkg.setPackageName(renamed);
2826 }
2827
Dianne Hackbornc1552392010-03-03 16:19:01 -08002828 } else {
2829 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2830 if ((origPackage=mSettings.peekPackageLP(
2831 pkg.mOriginalPackages.get(i))) != null) {
2832 // We do have the package already installed under its
2833 // original name... should we use it?
2834 if (!verifyPackageUpdate(origPackage, pkg)) {
2835 // New package is not compatible with original.
2836 origPackage = null;
2837 continue;
2838 } else if (origPackage.sharedUser != null) {
2839 // Make sure uid is compatible between packages.
2840 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002841 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002842 + " to " + pkg.packageName + ": old uid "
2843 + origPackage.sharedUser.name
2844 + " differs from " + pkg.mSharedUserId);
2845 origPackage = null;
2846 continue;
2847 }
2848 } else {
2849 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2850 + pkg.packageName + " to old name " + origPackage.name);
2851 }
2852 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002853 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002854 }
2855 }
2856 }
2857
2858 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002859 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002860 + " was transferred to another, but its .apk remains");
2861 }
2862
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002863 // Just create the setting, don't add it yet. For already existing packages
2864 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002865 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 destResourceFile, pkg.applicationInfo.flags, true, false);
2867 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002868 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2870 return null;
2871 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002872
2873 if (pkgSetting.origPackage != null) {
2874 // If we are first transitioning from an original package,
2875 // fix up the new package's name now. We need to do this after
2876 // looking up the package under its new name, so getPackageLP
2877 // can take care of fiddling things correctly.
2878 pkg.setPackageName(origPackage.name);
2879
2880 // File a report about this.
2881 String msg = "New package " + pkgSetting.realName
2882 + " renamed to replace old package " + pkgSetting.name;
2883 reportSettingsProblem(Log.WARN, msg);
2884
2885 // Make a note of it.
2886 mTransferedPackages.add(origPackage.name);
2887
2888 // No longer need to retain this.
2889 pkgSetting.origPackage = null;
2890 }
2891
2892 if (realName != null) {
2893 // Make a note of it.
2894 mTransferedPackages.add(pkg.packageName);
2895 }
2896
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002897 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2899 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 pkg.applicationInfo.uid = pkgSetting.userId;
2902 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002903
2904 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2906 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2907 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2908 return null;
2909 }
2910 // The signature has changed, but this package is in the system
2911 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002912 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 // However... if this package is part of a shared user, but it
2914 // doesn't match the signature of the shared user, let's fail.
2915 // What this means is that you can't change the signatures
2916 // associated with an overall shared user, which doesn't seem all
2917 // that unreasonable.
2918 if (pkgSetting.sharedUser != null) {
2919 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2920 pkg.mSignatures, false)) {
2921 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2922 return null;
2923 }
2924 }
2925 removeExisting = true;
2926 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002927
The Android Open Source Project10592532009-03-18 17:39:46 -07002928 // Verify that this new package doesn't have any content providers
2929 // that conflict with existing packages. Only do this if the
2930 // package isn't already installed, since we don't want to break
2931 // things that are installed.
2932 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2933 int N = pkg.providers.size();
2934 int i;
2935 for (i=0; i<N; i++) {
2936 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002937 if (p.info.authority != null) {
2938 String names[] = p.info.authority.split(";");
2939 for (int j = 0; j < names.length; j++) {
2940 if (mProviders.containsKey(names[j])) {
2941 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002942 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002943 " (in package " + pkg.applicationInfo.packageName +
2944 ") is already used by "
2945 + ((other != null && other.getComponentName() != null)
2946 ? other.getComponentName().getPackageName() : "?"));
2947 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2948 return null;
2949 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002950 }
2951 }
2952 }
2953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 }
2955
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002956 final String pkgName = pkg.packageName;
2957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002959 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002961 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 if (ret != 0) {
2963 String msg = "System package " + pkg.packageName
2964 + " could not have data directory erased after signature change.";
2965 reportSettingsProblem(Log.WARN, msg);
2966 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2967 return null;
2968 }
2969 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002970 Slog.w(TAG, "System package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 + " signature changed: existing data removed.");
2972 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2973 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002974
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002975 if (pkg.mAdoptPermissions != null) {
2976 // This package wants to adopt ownership of permissions from
2977 // another package.
2978 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2979 String origName = pkg.mAdoptPermissions.get(i);
2980 PackageSetting orig = mSettings.peekPackageLP(origName);
2981 if (orig != null) {
2982 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002983 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002984 + origName + " to " + pkg.packageName);
2985 mSettings.transferPermissions(origName, pkg.packageName);
2986 }
2987 }
2988 }
2989 }
2990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 long scanFileTime = scanFile.lastModified();
2992 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2993 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2994 pkg.applicationInfo.processName = fixProcessName(
2995 pkg.applicationInfo.packageName,
2996 pkg.applicationInfo.processName,
2997 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998
2999 File dataPath;
3000 if (mPlatformPackage == pkg) {
3001 // The system package is special.
3002 dataPath = new File (Environment.getDataDirectory(), "system");
3003 pkg.applicationInfo.dataDir = dataPath.getPath();
3004 } else {
3005 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003006 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003007 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003008
3009 boolean uidError = false;
3010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 if (dataPath.exists()) {
3012 mOutPermissions[1] = 0;
3013 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3014 if (mOutPermissions[1] == pkg.applicationInfo.uid
3015 || !Process.supportsProcesses()) {
3016 pkg.applicationInfo.dataDir = dataPath.getPath();
3017 } else {
3018 boolean recovered = false;
3019 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3020 // If this is a system app, we can at least delete its
3021 // current data so the application will still work.
3022 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003023 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003024 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 // Old data gone!
3026 String msg = "System package " + pkg.packageName
3027 + " has changed from uid: "
3028 + mOutPermissions[1] + " to "
3029 + pkg.applicationInfo.uid + "; old data erased";
3030 reportSettingsProblem(Log.WARN, msg);
3031 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003034 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 pkg.applicationInfo.uid);
3036 if (ret == -1) {
3037 // Ack should not happen!
3038 msg = "System package " + pkg.packageName
3039 + " could not have data directory re-created after delete.";
3040 reportSettingsProblem(Log.WARN, msg);
3041 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3042 return null;
3043 }
3044 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 if (!recovered) {
3047 mHasSystemUidErrors = true;
3048 }
3049 }
3050 if (!recovered) {
3051 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3052 + pkg.applicationInfo.uid + "/fs_"
3053 + mOutPermissions[1];
3054 String msg = "Package " + pkg.packageName
3055 + " has mismatched uid: "
3056 + mOutPermissions[1] + " on disk, "
3057 + pkg.applicationInfo.uid + " in settings";
3058 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003059 mSettings.mReadMessages.append(msg);
3060 mSettings.mReadMessages.append('\n');
3061 uidError = true;
3062 if (!pkgSetting.uidError) {
3063 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 }
3066 }
3067 }
3068 pkg.applicationInfo.dataDir = dataPath.getPath();
3069 } else {
3070 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3071 Log.v(TAG, "Want this data dir: " + dataPath);
3072 //invoke installer to do the actual installation
3073 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003074 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 pkg.applicationInfo.uid);
3076 if(ret < 0) {
3077 // Error from installer
3078 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3079 return null;
3080 }
3081 } else {
3082 dataPath.mkdirs();
3083 if (dataPath.exists()) {
3084 FileUtils.setPermissions(
3085 dataPath.toString(),
3086 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3087 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3088 }
3089 }
3090 if (dataPath.exists()) {
3091 pkg.applicationInfo.dataDir = dataPath.getPath();
3092 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003093 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 pkg.applicationInfo.dataDir = null;
3095 }
3096 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003097
3098 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 }
3100
3101 // Perform shared library installation and dex validation and
3102 // optimization, if this is not a system app.
3103 if (mInstaller != null) {
3104 String path = scanFile.getPath();
3105 if (scanFileNewer) {
3106 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003107 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3108 if (err != PackageManager.INSTALL_SUCCEEDED) {
3109 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 return null;
3111 }
3112 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003113 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003114
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003115 if ((scanMode&SCAN_NO_DEX) == 0) {
3116 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3118 return null;
3119 }
3120 }
3121 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003123 if (mFactoryTest && pkg.requestedPermissions.contains(
3124 android.Manifest.permission.FACTORY_TEST)) {
3125 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3126 }
3127
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003128 // Request the ActivityManager to kill the process(only for existing packages)
3129 // so that we do not end up in a confused state while the user is still using the older
3130 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003131 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003132 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003133 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003134 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003137 // We don't expect installation to fail beyond this point,
3138 if ((scanMode&SCAN_MONITOR) != 0) {
3139 mAppDirs.put(pkg.mPath, pkg);
3140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003142 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003144 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003145 // Make sure we don't accidentally delete its data.
3146 mSettings.mPackagesToBeCleaned.remove(pkgName);
3147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148 int N = pkg.providers.size();
3149 StringBuilder r = null;
3150 int i;
3151 for (i=0; i<N; i++) {
3152 PackageParser.Provider p = pkg.providers.get(i);
3153 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3154 p.info.processName, pkg.applicationInfo.uid);
3155 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3156 p.info.name), p);
3157 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003158 if (p.info.authority != null) {
3159 String names[] = p.info.authority.split(";");
3160 p.info.authority = null;
3161 for (int j = 0; j < names.length; j++) {
3162 if (j == 1 && p.syncable) {
3163 // We only want the first authority for a provider to possibly be
3164 // syncable, so if we already added this provider using a different
3165 // authority clear the syncable flag. We copy the provider before
3166 // changing it because the mProviders object contains a reference
3167 // to a provider that we don't want to change.
3168 // Only do this for the second authority since the resulting provider
3169 // object can be the same for all future authorities for this provider.
3170 p = new PackageParser.Provider(p);
3171 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003173 if (!mProviders.containsKey(names[j])) {
3174 mProviders.put(names[j], p);
3175 if (p.info.authority == null) {
3176 p.info.authority = names[j];
3177 } else {
3178 p.info.authority = p.info.authority + ";" + names[j];
3179 }
3180 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3181 Log.d(TAG, "Registered content provider: " + names[j] +
3182 ", className = " + p.info.name +
3183 ", isSyncable = " + p.info.isSyncable);
3184 } else {
3185 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003186 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003187 " (in package " + pkg.applicationInfo.packageName +
3188 "): name already used by "
3189 + ((other != null && other.getComponentName() != null)
3190 ? other.getComponentName().getPackageName() : "?"));
3191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 }
3193 }
3194 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3195 if (r == null) {
3196 r = new StringBuilder(256);
3197 } else {
3198 r.append(' ');
3199 }
3200 r.append(p.info.name);
3201 }
3202 }
3203 if (r != null) {
3204 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3205 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003207 N = pkg.services.size();
3208 r = null;
3209 for (i=0; i<N; i++) {
3210 PackageParser.Service s = pkg.services.get(i);
3211 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3212 s.info.processName, pkg.applicationInfo.uid);
3213 mServices.addService(s);
3214 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3215 if (r == null) {
3216 r = new StringBuilder(256);
3217 } else {
3218 r.append(' ');
3219 }
3220 r.append(s.info.name);
3221 }
3222 }
3223 if (r != null) {
3224 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3225 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 N = pkg.receivers.size();
3228 r = null;
3229 for (i=0; i<N; i++) {
3230 PackageParser.Activity a = pkg.receivers.get(i);
3231 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3232 a.info.processName, pkg.applicationInfo.uid);
3233 mReceivers.addActivity(a, "receiver");
3234 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3235 if (r == null) {
3236 r = new StringBuilder(256);
3237 } else {
3238 r.append(' ');
3239 }
3240 r.append(a.info.name);
3241 }
3242 }
3243 if (r != null) {
3244 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3245 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 N = pkg.activities.size();
3248 r = null;
3249 for (i=0; i<N; i++) {
3250 PackageParser.Activity a = pkg.activities.get(i);
3251 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3252 a.info.processName, pkg.applicationInfo.uid);
3253 mActivities.addActivity(a, "activity");
3254 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3255 if (r == null) {
3256 r = new StringBuilder(256);
3257 } else {
3258 r.append(' ');
3259 }
3260 r.append(a.info.name);
3261 }
3262 }
3263 if (r != null) {
3264 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3265 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 N = pkg.permissionGroups.size();
3268 r = null;
3269 for (i=0; i<N; i++) {
3270 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3271 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3272 if (cur == null) {
3273 mPermissionGroups.put(pg.info.name, pg);
3274 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3275 if (r == null) {
3276 r = new StringBuilder(256);
3277 } else {
3278 r.append(' ');
3279 }
3280 r.append(pg.info.name);
3281 }
3282 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003283 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 + pg.info.packageName + " ignored: original from "
3285 + cur.info.packageName);
3286 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3287 if (r == null) {
3288 r = new StringBuilder(256);
3289 } else {
3290 r.append(' ');
3291 }
3292 r.append("DUP:");
3293 r.append(pg.info.name);
3294 }
3295 }
3296 }
3297 if (r != null) {
3298 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3299 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 N = pkg.permissions.size();
3302 r = null;
3303 for (i=0; i<N; i++) {
3304 PackageParser.Permission p = pkg.permissions.get(i);
3305 HashMap<String, BasePermission> permissionMap =
3306 p.tree ? mSettings.mPermissionTrees
3307 : mSettings.mPermissions;
3308 p.group = mPermissionGroups.get(p.info.group);
3309 if (p.info.group == null || p.group != null) {
3310 BasePermission bp = permissionMap.get(p.info.name);
3311 if (bp == null) {
3312 bp = new BasePermission(p.info.name, p.info.packageName,
3313 BasePermission.TYPE_NORMAL);
3314 permissionMap.put(p.info.name, bp);
3315 }
3316 if (bp.perm == null) {
3317 if (bp.sourcePackage == null
3318 || bp.sourcePackage.equals(p.info.packageName)) {
3319 BasePermission tree = findPermissionTreeLP(p.info.name);
3320 if (tree == null
3321 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003322 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003323 bp.perm = p;
3324 bp.uid = pkg.applicationInfo.uid;
3325 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3326 if (r == null) {
3327 r = new StringBuilder(256);
3328 } else {
3329 r.append(' ');
3330 }
3331 r.append(p.info.name);
3332 }
3333 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003334 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 + p.info.packageName + " ignored: base tree "
3336 + tree.name + " is from package "
3337 + tree.sourcePackage);
3338 }
3339 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003340 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 + p.info.packageName + " ignored: original from "
3342 + bp.sourcePackage);
3343 }
3344 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3345 if (r == null) {
3346 r = new StringBuilder(256);
3347 } else {
3348 r.append(' ');
3349 }
3350 r.append("DUP:");
3351 r.append(p.info.name);
3352 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003353 if (bp.perm == p) {
3354 bp.protectionLevel = p.info.protectionLevel;
3355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003357 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 + p.info.packageName + " ignored: no group "
3359 + p.group);
3360 }
3361 }
3362 if (r != null) {
3363 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3364 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 N = pkg.instrumentation.size();
3367 r = null;
3368 for (i=0; i<N; i++) {
3369 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3370 a.info.packageName = pkg.applicationInfo.packageName;
3371 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3372 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3373 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003374 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3376 if (r == null) {
3377 r = new StringBuilder(256);
3378 } else {
3379 r.append(' ');
3380 }
3381 r.append(a.info.name);
3382 }
3383 }
3384 if (r != null) {
3385 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3386 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003387
Dianne Hackborn854060af2009-07-09 18:14:31 -07003388 if (pkg.protectedBroadcasts != null) {
3389 N = pkg.protectedBroadcasts.size();
3390 for (i=0; i<N; i++) {
3391 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3392 }
3393 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 pkgSetting.setTimeStamp(scanFileTime);
3396 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 return pkg;
3399 }
3400
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003401 private void killApplication(String pkgName, int uid) {
3402 // Request the ActivityManager to kill the process(only for existing packages)
3403 // so that we do not end up in a confused state while the user is still using the older
3404 // version of the application while the new one gets installed.
3405 IActivityManager am = ActivityManagerNative.getDefault();
3406 if (am != null) {
3407 try {
3408 am.killApplicationWithUid(pkgName, uid);
3409 } catch (RemoteException e) {
3410 }
3411 }
3412 }
3413
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003414 // The following constants are returned by cachePackageSharedLibsForAbiLI
3415 // to indicate if native shared libraries were found in the package.
3416 // Values are:
3417 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3418 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3419 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3420 // in package (and not installed)
3421 //
3422 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3423 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3424 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003426 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3427 // and automatically copy them to /data/data/<appname>/lib if present.
3428 //
3429 // NOTE: this method may throw an IOException if the library cannot
3430 // be copied to its final destination, e.g. if there isn't enough
3431 // room left on the data partition, or a ZipException if the package
3432 // file is malformed.
3433 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003434 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3435 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003436 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3437 final String apkLib = "lib/";
3438 final int apkLibLen = apkLib.length();
3439 final int cpuAbiLen = cpuAbi.length();
3440 final String libPrefix = "lib";
3441 final int libPrefixLen = libPrefix.length();
3442 final String libSuffix = ".so";
3443 final int libSuffixLen = libSuffix.length();
3444 boolean hasNativeLibraries = false;
3445 boolean installedNativeLibraries = false;
3446
3447 // the minimum length of a valid native shared library of the form
3448 // lib/<something>/lib<name>.so.
3449 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3450
3451 ZipFile zipFile = new ZipFile(scanFile);
3452 Enumeration<ZipEntry> entries =
3453 (Enumeration<ZipEntry>) zipFile.entries();
3454
3455 while (entries.hasMoreElements()) {
3456 ZipEntry entry = entries.nextElement();
3457 // skip directories
3458 if (entry.isDirectory()) {
3459 continue;
3460 }
3461 String entryName = entry.getName();
3462
3463 // check that the entry looks like lib/<something>/lib<name>.so
3464 // here, but don't check the ABI just yet.
3465 //
3466 // - must be sufficiently long
3467 // - must end with libSuffix, i.e. ".so"
3468 // - must start with apkLib, i.e. "lib/"
3469 if (entryName.length() < minEntryLen ||
3470 !entryName.endsWith(libSuffix) ||
3471 !entryName.startsWith(apkLib) ) {
3472 continue;
3473 }
3474
3475 // file name must start with libPrefix, i.e. "lib"
3476 int lastSlash = entryName.lastIndexOf('/');
3477
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003478 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003479 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3480 continue;
3481 }
3482
3483 hasNativeLibraries = true;
3484
3485 // check the cpuAbi now, between lib/ and /lib<name>.so
3486 //
3487 if (lastSlash != apkLibLen + cpuAbiLen ||
3488 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3489 continue;
3490
3491 // extract the library file name, ensure it doesn't contain
3492 // weird characters. we're guaranteed here that it doesn't contain
3493 // a directory separator though.
3494 String libFileName = entryName.substring(lastSlash+1);
3495 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3496 continue;
3497 }
3498
3499 installedNativeLibraries = true;
3500
3501 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3502 File.separator + libFileName;
3503 File sharedLibraryFile = new File(sharedLibraryFilePath);
3504 if (! sharedLibraryFile.exists() ||
3505 sharedLibraryFile.length() != entry.getSize() ||
3506 sharedLibraryFile.lastModified() != entry.getTime()) {
3507 if (Config.LOGD) {
3508 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003510 if (mInstaller == null) {
3511 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003512 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003513 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003514 sharedLibraryFile);
3515 }
3516 }
3517 if (!hasNativeLibraries)
3518 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3519
3520 if (!installedNativeLibraries)
3521 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3522
3523 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3524 }
3525
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003526 // Find the gdbserver executable program in a package at
3527 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3528 //
3529 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3530 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3531 //
3532 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3533 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3534 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3535 final String GDBSERVER = "gdbserver";
3536 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3537
3538 ZipFile zipFile = new ZipFile(scanFile);
3539 Enumeration<ZipEntry> entries =
3540 (Enumeration<ZipEntry>) zipFile.entries();
3541
3542 while (entries.hasMoreElements()) {
3543 ZipEntry entry = entries.nextElement();
3544 // skip directories
3545 if (entry.isDirectory()) {
3546 continue;
3547 }
3548 String entryName = entry.getName();
3549
3550 if (!entryName.equals(apkGdbServerPath)) {
3551 continue;
3552 }
3553
3554 String installGdbServerPath = installGdbServerDir.getPath() +
3555 "/" + GDBSERVER;
3556 File installGdbServerFile = new File(installGdbServerPath);
3557 if (! installGdbServerFile.exists() ||
3558 installGdbServerFile.length() != entry.getSize() ||
3559 installGdbServerFile.lastModified() != entry.getTime()) {
3560 if (Config.LOGD) {
3561 Log.d(TAG, "Caching gdbserver " + entry.getName());
3562 }
3563 if (mInstaller == null) {
3564 installGdbServerDir.mkdir();
3565 }
3566 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3567 installGdbServerFile);
3568 }
3569 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3570 }
3571 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3572 }
3573
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003574 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3575 // and copy them to /data/data/<appname>/lib.
3576 //
3577 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3578 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3579 // one if ro.product.cpu.abi2 is defined.
3580 //
3581 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3582 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003583 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003584 try {
3585 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3586
3587 // some architectures are capable of supporting several CPU ABIs
3588 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3589 // this is indicated by the definition of the ro.product.cpu.abi2
3590 // system property.
3591 //
3592 // only scan the package twice in case of ABI mismatch
3593 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003594 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003595 if (cpuAbi2 != null) {
3596 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003597 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003598
3599 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003600 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003601 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003603
3604 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3605 cpuAbi = cpuAbi2;
3606 }
3607 }
3608
3609 // for debuggable packages, also extract gdbserver from lib/<abi>
3610 // into /data/data/<appname>/lib too.
3611 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3612 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3613 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3614 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3615 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003617 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003618 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003619 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003620 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003622 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003623 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003625 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 }
3627
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003628 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003630 File binaryDir,
3631 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 InputStream inputStream = zipFile.getInputStream(entry);
3633 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003634 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003636 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 // now need to be left as world readable and owned by the system.
3638 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3639 ! tempFile.setLastModified(entry.getTime()) ||
3640 FileUtils.setPermissions(tempFilePath,
3641 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003642 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003644 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 // Failed to properly write file.
3646 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003647 throw new IOException("Couldn't create cached binary "
3648 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 }
3650 } finally {
3651 inputStream.close();
3652 }
3653 }
3654
3655 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3656 if (chatty && Config.LOGD) Log.d(
3657 TAG, "Removing package " + pkg.applicationInfo.packageName );
3658
3659 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 mPackages.remove(pkg.applicationInfo.packageName);
3663 if (pkg.mPath != null) {
3664 mAppDirs.remove(pkg.mPath);
3665 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 PackageSetting ps = (PackageSetting)pkg.mExtras;
3668 if (ps != null && ps.sharedUser != null) {
3669 // XXX don't do this until the data is removed.
3670 if (false) {
3671 ps.sharedUser.packages.remove(ps);
3672 if (ps.sharedUser.packages.size() == 0) {
3673 // Remove.
3674 }
3675 }
3676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 int N = pkg.providers.size();
3679 StringBuilder r = null;
3680 int i;
3681 for (i=0; i<N; i++) {
3682 PackageParser.Provider p = pkg.providers.get(i);
3683 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3684 p.info.name));
3685 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 /* The is another ContentProvider with this authority when
3688 * this app was installed so this authority is null,
3689 * Ignore it as we don't have to unregister the provider.
3690 */
3691 continue;
3692 }
3693 String names[] = p.info.authority.split(";");
3694 for (int j = 0; j < names.length; j++) {
3695 if (mProviders.get(names[j]) == p) {
3696 mProviders.remove(names[j]);
3697 if (chatty && Config.LOGD) Log.d(
3698 TAG, "Unregistered content provider: " + names[j] +
3699 ", className = " + p.info.name +
3700 ", isSyncable = " + p.info.isSyncable);
3701 }
3702 }
3703 if (chatty) {
3704 if (r == null) {
3705 r = new StringBuilder(256);
3706 } else {
3707 r.append(' ');
3708 }
3709 r.append(p.info.name);
3710 }
3711 }
3712 if (r != null) {
3713 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 N = pkg.services.size();
3717 r = null;
3718 for (i=0; i<N; i++) {
3719 PackageParser.Service s = pkg.services.get(i);
3720 mServices.removeService(s);
3721 if (chatty) {
3722 if (r == null) {
3723 r = new StringBuilder(256);
3724 } else {
3725 r.append(' ');
3726 }
3727 r.append(s.info.name);
3728 }
3729 }
3730 if (r != null) {
3731 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3732 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734 N = pkg.receivers.size();
3735 r = null;
3736 for (i=0; i<N; i++) {
3737 PackageParser.Activity a = pkg.receivers.get(i);
3738 mReceivers.removeActivity(a, "receiver");
3739 if (chatty) {
3740 if (r == null) {
3741 r = new StringBuilder(256);
3742 } else {
3743 r.append(' ');
3744 }
3745 r.append(a.info.name);
3746 }
3747 }
3748 if (r != null) {
3749 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3750 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 N = pkg.activities.size();
3753 r = null;
3754 for (i=0; i<N; i++) {
3755 PackageParser.Activity a = pkg.activities.get(i);
3756 mActivities.removeActivity(a, "activity");
3757 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, " Activities: " + r);
3768 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 N = pkg.permissions.size();
3771 r = null;
3772 for (i=0; i<N; i++) {
3773 PackageParser.Permission p = pkg.permissions.get(i);
3774 boolean tree = false;
3775 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3776 if (bp == null) {
3777 tree = true;
3778 bp = mSettings.mPermissionTrees.get(p.info.name);
3779 }
3780 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003781 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 if (chatty) {
3783 if (r == null) {
3784 r = new StringBuilder(256);
3785 } else {
3786 r.append(' ');
3787 }
3788 r.append(p.info.name);
3789 }
3790 }
3791 }
3792 if (r != null) {
3793 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3794 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796 N = pkg.instrumentation.size();
3797 r = null;
3798 for (i=0; i<N; i++) {
3799 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003800 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 if (chatty) {
3802 if (r == null) {
3803 r = new StringBuilder(256);
3804 } else {
3805 r.append(' ');
3806 }
3807 r.append(a.info.name);
3808 }
3809 }
3810 if (r != null) {
3811 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3812 }
3813 }
3814 }
3815
3816 private static final boolean isPackageFilename(String name) {
3817 return name != null && name.endsWith(".apk");
3818 }
3819
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003820 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3821 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3822 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3823 return true;
3824 }
3825 }
3826 return false;
3827 }
3828
3829 private void updatePermissionsLP(String changingPkg,
3830 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831 // Make sure there are no dangling permission trees.
3832 Iterator<BasePermission> it = mSettings.mPermissionTrees
3833 .values().iterator();
3834 while (it.hasNext()) {
3835 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003836 if (bp.packageSetting == null) {
3837 // We may not yet have parsed the package, so just see if
3838 // we still know about its settings.
3839 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3840 }
3841 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003842 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 + " from package " + bp.sourcePackage);
3844 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003845 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3846 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3847 Slog.i(TAG, "Removing old permission tree: " + bp.name
3848 + " from package " + bp.sourcePackage);
3849 grantPermissions = true;
3850 it.remove();
3851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852 }
3853 }
3854
3855 // Make sure all dynamic permissions have been assigned to a package,
3856 // and make sure there are no dangling permissions.
3857 it = mSettings.mPermissions.values().iterator();
3858 while (it.hasNext()) {
3859 BasePermission bp = it.next();
3860 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3861 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3862 + bp.name + " pkg=" + bp.sourcePackage
3863 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003864 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 BasePermission tree = findPermissionTreeLP(bp.name);
3866 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003867 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 bp.perm = new PackageParser.Permission(tree.perm.owner,
3869 new PermissionInfo(bp.pendingInfo));
3870 bp.perm.info.packageName = tree.perm.info.packageName;
3871 bp.perm.info.name = bp.name;
3872 bp.uid = tree.uid;
3873 }
3874 }
3875 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003876 if (bp.packageSetting == null) {
3877 // We may not yet have parsed the package, so just see if
3878 // we still know about its settings.
3879 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3880 }
3881 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003882 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 + " from package " + bp.sourcePackage);
3884 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003885 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3886 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3887 Slog.i(TAG, "Removing old permission: " + bp.name
3888 + " from package " + bp.sourcePackage);
3889 grantPermissions = true;
3890 it.remove();
3891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 }
3893 }
3894
3895 // Now update the permissions for all packages, in particular
3896 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003897 if (grantPermissions) {
3898 for (PackageParser.Package pkg : mPackages.values()) {
3899 if (pkg != pkgInfo) {
3900 grantPermissionsLP(pkg, false);
3901 }
3902 }
3903 }
3904
3905 if (pkgInfo != null) {
3906 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 }
3908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3911 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3912 if (ps == null) {
3913 return;
3914 }
3915 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003916 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 if (replace) {
3919 ps.permissionsFixed = false;
3920 if (gp == ps) {
3921 gp.grantedPermissions.clear();
3922 gp.gids = mGlobalGids;
3923 }
3924 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 if (gp.gids == null) {
3927 gp.gids = mGlobalGids;
3928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 final int N = pkg.requestedPermissions.size();
3931 for (int i=0; i<N; i++) {
3932 String name = pkg.requestedPermissions.get(i);
3933 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 if (false) {
3935 if (gp != ps) {
3936 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003937 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 }
3939 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003940 if (bp != null && bp.packageSetting != null) {
3941 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003943 boolean allowedSig = false;
3944 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3945 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 allowed = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003947 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3948 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3949 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003951 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003953 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3955 // For updated system applications, the signatureOrSystem permission
3956 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003957 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3959 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3960 if(sysPs.grantedPermissions.contains(perm)) {
3961 allowed = true;
3962 } else {
3963 allowed = false;
3964 }
3965 } else {
3966 allowed = true;
3967 }
3968 }
3969 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003970 if (allowed) {
3971 allowedSig = true;
3972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 } else {
3974 allowed = false;
3975 }
3976 if (false) {
3977 if (gp != ps) {
3978 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3979 }
3980 }
3981 if (allowed) {
3982 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3983 && ps.permissionsFixed) {
3984 // If this is an existing, non-system package, then
3985 // we can't add any new permissions to it.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003986 if (!allowedSig && !gp.loadedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003988 // Except... if this is a permission that was added
3989 // to the platform (note: need to only do this when
3990 // updating the platform).
3991 final int NP = PackageParser.NEW_PERMISSIONS.length;
3992 for (int ip=0; ip<NP; ip++) {
3993 final PackageParser.NewPermissionInfo npi
3994 = PackageParser.NEW_PERMISSIONS[ip];
3995 if (npi.name.equals(perm)
3996 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3997 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003998 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003999 + pkg.packageName);
4000 break;
4001 }
4002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 }
4004 }
4005 if (allowed) {
4006 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004007 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 gp.grantedPermissions.add(perm);
4009 gp.gids = appendInts(gp.gids, bp.gids);
4010 }
4011 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004012 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 + " to package " + pkg.packageName
4014 + " because it was previously installed without");
4015 }
4016 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004017 if (gp.grantedPermissions.remove(perm)) {
4018 changedPermission = true;
4019 gp.gids = removeInts(gp.gids, bp.gids);
4020 Slog.i(TAG, "Un-granting permission " + perm
4021 + " from package " + pkg.packageName
4022 + " (protectionLevel=" + bp.protectionLevel
4023 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4024 + ")");
4025 } else {
4026 Slog.w(TAG, "Not granting permission " + perm
4027 + " to package " + pkg.packageName
4028 + " (protectionLevel=" + bp.protectionLevel
4029 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4030 + ")");
4031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 }
4033 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004034 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 + " in package " + pkg.packageName);
4036 }
4037 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004038
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004039 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004040 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4041 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004042 // This is the first that we have heard about this package, so the
4043 // permissions we have now selected are fixed until explicitly
4044 // changed.
4045 ps.permissionsFixed = true;
4046 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
4047 }
4048 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004050 private final class ActivityIntentResolver
4051 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004052 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004054 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004055 }
4056
Mihai Preda074edef2009-05-18 17:13:31 +02004057 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004059 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4061 }
4062
Mihai Predaeae850c2009-05-13 10:13:48 +02004063 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4064 ArrayList<PackageParser.Activity> packageActivities) {
4065 if (packageActivities == null) {
4066 return null;
4067 }
4068 mFlags = flags;
4069 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4070 int N = packageActivities.size();
4071 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4072 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004073
4074 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004075 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004076 intentFilters = packageActivities.get(i).intents;
4077 if (intentFilters != null && intentFilters.size() > 0) {
4078 listCut.add(intentFilters);
4079 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004080 }
4081 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4082 }
4083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004085 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 if (SHOW_INFO || Config.LOGV) Log.v(
4087 TAG, " " + type + " " +
4088 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4089 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4090 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004091 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4093 if (SHOW_INFO || Config.LOGV) {
4094 Log.v(TAG, " IntentFilter:");
4095 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4096 }
4097 if (!intent.debugCheck()) {
4098 Log.w(TAG, "==> For Activity " + a.info.name);
4099 }
4100 addFilter(intent);
4101 }
4102 }
4103
4104 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004105 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 if (SHOW_INFO || Config.LOGV) Log.v(
4107 TAG, " " + type + " " +
4108 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4109 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4110 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004111 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4113 if (SHOW_INFO || Config.LOGV) {
4114 Log.v(TAG, " IntentFilter:");
4115 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4116 }
4117 removeFilter(intent);
4118 }
4119 }
4120
4121 @Override
4122 protected boolean allowFilterResult(
4123 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4124 ActivityInfo filterAi = filter.activity.info;
4125 for (int i=dest.size()-1; i>=0; i--) {
4126 ActivityInfo destAi = dest.get(i).activityInfo;
4127 if (destAi.name == filterAi.name
4128 && destAi.packageName == filterAi.packageName) {
4129 return false;
4130 }
4131 }
4132 return true;
4133 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004136 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4137 return info.activity.owner.packageName;
4138 }
4139
4140 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4142 int match) {
4143 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4144 return null;
4145 }
4146 final PackageParser.Activity activity = info.activity;
4147 if (mSafeMode && (activity.info.applicationInfo.flags
4148 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4149 return null;
4150 }
4151 final ResolveInfo res = new ResolveInfo();
4152 res.activityInfo = PackageParser.generateActivityInfo(activity,
4153 mFlags);
4154 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4155 res.filter = info;
4156 }
4157 res.priority = info.getPriority();
4158 res.preferredOrder = activity.owner.mPreferredOrder;
4159 //System.out.println("Result: " + res.activityInfo.className +
4160 // " = " + res.priority);
4161 res.match = match;
4162 res.isDefault = info.hasDefault;
4163 res.labelRes = info.labelRes;
4164 res.nonLocalizedLabel = info.nonLocalizedLabel;
4165 res.icon = info.icon;
4166 return res;
4167 }
4168
4169 @Override
4170 protected void sortResults(List<ResolveInfo> results) {
4171 Collections.sort(results, mResolvePrioritySorter);
4172 }
4173
4174 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004175 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004177 out.print(prefix); out.print(
4178 Integer.toHexString(System.identityHashCode(filter.activity)));
4179 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004180 out.print(filter.activity.getComponentShortName());
4181 out.print(" filter ");
4182 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 }
4184
4185// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4186// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4187// final List<ResolveInfo> retList = Lists.newArrayList();
4188// while (i.hasNext()) {
4189// final ResolveInfo resolveInfo = i.next();
4190// if (isEnabledLP(resolveInfo.activityInfo)) {
4191// retList.add(resolveInfo);
4192// }
4193// }
4194// return retList;
4195// }
4196
4197 // Keys are String (activity class name), values are Activity.
4198 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4199 = new HashMap<ComponentName, PackageParser.Activity>();
4200 private int mFlags;
4201 }
4202
4203 private final class ServiceIntentResolver
4204 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004205 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004207 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208 }
4209
Mihai Preda074edef2009-05-18 17:13:31 +02004210 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004212 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4214 }
4215
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004216 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4217 ArrayList<PackageParser.Service> packageServices) {
4218 if (packageServices == null) {
4219 return null;
4220 }
4221 mFlags = flags;
4222 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4223 int N = packageServices.size();
4224 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4225 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4226
4227 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4228 for (int i = 0; i < N; ++i) {
4229 intentFilters = packageServices.get(i).intents;
4230 if (intentFilters != null && intentFilters.size() > 0) {
4231 listCut.add(intentFilters);
4232 }
4233 }
4234 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4235 }
4236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004238 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 if (SHOW_INFO || Config.LOGV) Log.v(
4240 TAG, " " + (s.info.nonLocalizedLabel != null
4241 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4242 if (SHOW_INFO || Config.LOGV) Log.v(
4243 TAG, " Class=" + s.info.name);
4244 int NI = s.intents.size();
4245 int j;
4246 for (j=0; j<NI; j++) {
4247 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4248 if (SHOW_INFO || Config.LOGV) {
4249 Log.v(TAG, " IntentFilter:");
4250 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4251 }
4252 if (!intent.debugCheck()) {
4253 Log.w(TAG, "==> For Service " + s.info.name);
4254 }
4255 addFilter(intent);
4256 }
4257 }
4258
4259 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004260 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 if (SHOW_INFO || Config.LOGV) Log.v(
4262 TAG, " " + (s.info.nonLocalizedLabel != null
4263 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4264 if (SHOW_INFO || Config.LOGV) Log.v(
4265 TAG, " Class=" + s.info.name);
4266 int NI = s.intents.size();
4267 int j;
4268 for (j=0; j<NI; j++) {
4269 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4270 if (SHOW_INFO || Config.LOGV) {
4271 Log.v(TAG, " IntentFilter:");
4272 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4273 }
4274 removeFilter(intent);
4275 }
4276 }
4277
4278 @Override
4279 protected boolean allowFilterResult(
4280 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4281 ServiceInfo filterSi = filter.service.info;
4282 for (int i=dest.size()-1; i>=0; i--) {
4283 ServiceInfo destAi = dest.get(i).serviceInfo;
4284 if (destAi.name == filterSi.name
4285 && destAi.packageName == filterSi.packageName) {
4286 return false;
4287 }
4288 }
4289 return true;
4290 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004293 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4294 return info.service.owner.packageName;
4295 }
4296
4297 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004298 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4299 int match) {
4300 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4301 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4302 return null;
4303 }
4304 final PackageParser.Service service = info.service;
4305 if (mSafeMode && (service.info.applicationInfo.flags
4306 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4307 return null;
4308 }
4309 final ResolveInfo res = new ResolveInfo();
4310 res.serviceInfo = PackageParser.generateServiceInfo(service,
4311 mFlags);
4312 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4313 res.filter = filter;
4314 }
4315 res.priority = info.getPriority();
4316 res.preferredOrder = service.owner.mPreferredOrder;
4317 //System.out.println("Result: " + res.activityInfo.className +
4318 // " = " + res.priority);
4319 res.match = match;
4320 res.isDefault = info.hasDefault;
4321 res.labelRes = info.labelRes;
4322 res.nonLocalizedLabel = info.nonLocalizedLabel;
4323 res.icon = info.icon;
4324 return res;
4325 }
4326
4327 @Override
4328 protected void sortResults(List<ResolveInfo> results) {
4329 Collections.sort(results, mResolvePrioritySorter);
4330 }
4331
4332 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004333 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004335 out.print(prefix); out.print(
4336 Integer.toHexString(System.identityHashCode(filter.service)));
4337 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004338 out.print(filter.service.getComponentShortName());
4339 out.print(" filter ");
4340 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004341 }
4342
4343// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4344// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4345// final List<ResolveInfo> retList = Lists.newArrayList();
4346// while (i.hasNext()) {
4347// final ResolveInfo resolveInfo = (ResolveInfo) i;
4348// if (isEnabledLP(resolveInfo.serviceInfo)) {
4349// retList.add(resolveInfo);
4350// }
4351// }
4352// return retList;
4353// }
4354
4355 // Keys are String (activity class name), values are Activity.
4356 private final HashMap<ComponentName, PackageParser.Service> mServices
4357 = new HashMap<ComponentName, PackageParser.Service>();
4358 private int mFlags;
4359 };
4360
4361 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4362 new Comparator<ResolveInfo>() {
4363 public int compare(ResolveInfo r1, ResolveInfo r2) {
4364 int v1 = r1.priority;
4365 int v2 = r2.priority;
4366 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4367 if (v1 != v2) {
4368 return (v1 > v2) ? -1 : 1;
4369 }
4370 v1 = r1.preferredOrder;
4371 v2 = r2.preferredOrder;
4372 if (v1 != v2) {
4373 return (v1 > v2) ? -1 : 1;
4374 }
4375 if (r1.isDefault != r2.isDefault) {
4376 return r1.isDefault ? -1 : 1;
4377 }
4378 v1 = r1.match;
4379 v2 = r2.match;
4380 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4381 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4382 }
4383 };
4384
4385 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4386 new Comparator<ProviderInfo>() {
4387 public int compare(ProviderInfo p1, ProviderInfo p2) {
4388 final int v1 = p1.initOrder;
4389 final int v2 = p2.initOrder;
4390 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4391 }
4392 };
4393
4394 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4395 IActivityManager am = ActivityManagerNative.getDefault();
4396 if (am != null) {
4397 try {
4398 final Intent intent = new Intent(action,
4399 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4400 if (extras != null) {
4401 intent.putExtras(extras);
4402 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004403 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004404 am.broadcastIntent(
4405 null, intent,
4406 null, null, 0, null, null, null, false, false);
4407 } catch (RemoteException ex) {
4408 }
4409 }
4410 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004411
4412 public String nextPackageToClean(String lastPackage) {
4413 synchronized (mPackages) {
4414 if (!mMediaMounted) {
4415 // If the external storage is no longer mounted at this point,
4416 // the caller may not have been able to delete all of this
4417 // packages files and can not delete any more. Bail.
4418 return null;
4419 }
4420 if (lastPackage != null) {
4421 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4422 }
4423 return mSettings.mPackagesToBeCleaned.size() > 0
4424 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4425 }
4426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004427
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004428 void schedulePackageCleaning(String packageName) {
4429 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4430 }
4431
4432 void startCleaningPackages() {
4433 synchronized (mPackages) {
4434 if (!mMediaMounted) {
4435 return;
4436 }
4437 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4438 return;
4439 }
4440 }
4441 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4442 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4443 IActivityManager am = ActivityManagerNative.getDefault();
4444 if (am != null) {
4445 try {
4446 am.startService(null, intent, null);
4447 } catch (RemoteException e) {
4448 }
4449 }
4450 }
4451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 private final class AppDirObserver extends FileObserver {
4453 public AppDirObserver(String path, int mask, boolean isrom) {
4454 super(path, mask);
4455 mRootDir = path;
4456 mIsRom = isrom;
4457 }
4458
4459 public void onEvent(int event, String path) {
4460 String removedPackage = null;
4461 int removedUid = -1;
4462 String addedPackage = null;
4463 int addedUid = -1;
4464
4465 synchronized (mInstallLock) {
4466 String fullPathStr = null;
4467 File fullPath = null;
4468 if (path != null) {
4469 fullPath = new File(mRootDir, path);
4470 fullPathStr = fullPath.getPath();
4471 }
4472
4473 if (Config.LOGV) Log.v(
4474 TAG, "File " + fullPathStr + " changed: "
4475 + Integer.toHexString(event));
4476
4477 if (!isPackageFilename(path)) {
4478 if (Config.LOGV) Log.v(
4479 TAG, "Ignoring change of non-package file: " + fullPathStr);
4480 return;
4481 }
4482
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004483 // Ignore packages that are being installed or
4484 // have just been installed.
4485 if (ignoreCodePath(fullPathStr)) {
4486 return;
4487 }
4488 PackageParser.Package p = null;
4489 synchronized (mPackages) {
4490 p = mAppDirs.get(fullPathStr);
4491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004492 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004493 if (p != null) {
4494 removePackageLI(p, true);
4495 removedPackage = p.applicationInfo.packageName;
4496 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 }
4498 }
4499
4500 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004502 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004503 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4504 PackageParser.PARSE_CHATTY |
4505 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004506 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 if (p != null) {
4508 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004509 updatePermissionsLP(p.packageName, p,
4510 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004511 }
4512 addedPackage = p.applicationInfo.packageName;
4513 addedUid = p.applicationInfo.uid;
4514 }
4515 }
4516 }
4517
4518 synchronized (mPackages) {
4519 mSettings.writeLP();
4520 }
4521 }
4522
4523 if (removedPackage != null) {
4524 Bundle extras = new Bundle(1);
4525 extras.putInt(Intent.EXTRA_UID, removedUid);
4526 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4527 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4528 }
4529 if (addedPackage != null) {
4530 Bundle extras = new Bundle(1);
4531 extras.putInt(Intent.EXTRA_UID, addedUid);
4532 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4533 }
4534 }
4535
4536 private final String mRootDir;
4537 private final boolean mIsRom;
4538 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004540 /* Called when a downloaded package installation has been confirmed by the user */
4541 public void installPackage(
4542 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004543 installPackage(packageURI, observer, flags, null);
4544 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004545
Jacek Surazski65e13172009-04-28 15:26:38 +02004546 /* Called when a downloaded package installation has been confirmed by the user */
4547 public void installPackage(
4548 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4549 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004550 mContext.enforceCallingOrSelfPermission(
4551 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004552
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004553 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004554 msg.obj = new InstallParams(packageURI, observer, flags,
4555 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004556 mHandler.sendMessage(msg);
4557 }
4558
Christopher Tate1bb69062010-02-19 17:02:12 -08004559 public void finishPackageInstall(int token) {
4560 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4561 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4562 mHandler.sendMessage(msg);
4563 }
4564
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004565 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 // Queue up an async operation since the package installation may take a little while.
4567 mHandler.post(new Runnable() {
4568 public void run() {
4569 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004570 // Result object to be returned
4571 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004572 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004573 res.uid = -1;
4574 res.pkg = null;
4575 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004576 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004577 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004578 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004579 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004580 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004581 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004583
4584 // A restore should be performed at this point if (a) the install
4585 // succeeded, (b) the operation is not an update, and (c) the new
4586 // package has a backupAgent defined.
4587 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004588 boolean doRestore = (!update
4589 && res.pkg != null
4590 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004591
4592 // Set up the post-install work request bookkeeping. This will be used
4593 // and cleaned up by the post-install event handling regardless of whether
4594 // there's a restore pass performed. Token values are >= 1.
4595 int token;
4596 if (mNextInstallToken < 0) mNextInstallToken = 1;
4597 token = mNextInstallToken++;
4598
4599 PostInstallData data = new PostInstallData(args, res);
4600 mRunningInstalls.put(token, data);
4601 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4602
4603 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4604 // Pass responsibility to the Backup Manager. It will perform a
4605 // restore if appropriate, then pass responsibility back to the
4606 // Package Manager to run the post-install observer callbacks
4607 // and broadcasts.
4608 IBackupManager bm = IBackupManager.Stub.asInterface(
4609 ServiceManager.getService(Context.BACKUP_SERVICE));
4610 if (bm != null) {
4611 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4612 + " to BM for possible restore");
4613 try {
4614 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4615 } catch (RemoteException e) {
4616 // can't happen; the backup manager is local
4617 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004618 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004619 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004620 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004621 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004622 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004623 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004626
4627 if (!doRestore) {
4628 // No restore possible, or the Backup Manager was mysteriously not
4629 // available -- just fire the post-install work request directly.
4630 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4631 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4632 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004634 }
4635 });
4636 }
4637
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004638 abstract class HandlerParams {
4639 final static int MAX_RETRIES = 4;
4640 int retry = 0;
4641 final void startCopy() {
4642 try {
4643 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4644 retry++;
4645 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004646 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004647 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4648 handleServiceError();
4649 return;
4650 } else {
4651 handleStartCopy();
4652 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4653 mHandler.sendEmptyMessage(MCS_UNBIND);
4654 }
4655 } catch (RemoteException e) {
4656 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4657 mHandler.sendEmptyMessage(MCS_RECONNECT);
4658 }
4659 handleReturnCode();
4660 }
4661
4662 final void serviceError() {
4663 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4664 handleServiceError();
4665 handleReturnCode();
4666 }
4667 abstract void handleStartCopy() throws RemoteException;
4668 abstract void handleServiceError();
4669 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004670 }
4671
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004672 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004673 final IPackageInstallObserver observer;
4674 int flags;
4675 final Uri packageURI;
4676 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004677 private InstallArgs mArgs;
4678 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004679 InstallParams(Uri packageURI,
4680 IPackageInstallObserver observer, int flags,
4681 String installerPackageName) {
4682 this.packageURI = packageURI;
4683 this.flags = flags;
4684 this.observer = observer;
4685 this.installerPackageName = installerPackageName;
4686 }
4687
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004688 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4689 String packageName = pkgLite.packageName;
4690 int installLocation = pkgLite.installLocation;
4691 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4692 synchronized (mPackages) {
4693 PackageParser.Package pkg = mPackages.get(packageName);
4694 if (pkg != null) {
4695 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4696 // Check for updated system application.
4697 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4698 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004699 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004700 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4701 }
4702 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4703 } else {
4704 // When replacing apps make sure we honour
4705 // the existing app location if not overwritten by other options
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08004706 boolean prevOnSd = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004707 if (onSd) {
4708 // Install flag overrides everything.
4709 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4710 }
4711 // If current upgrade does not specify install location.
4712 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4713 // Application explicitly specified internal.
4714 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4715 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4716 // App explictly prefers external. Let policy decide
4717 } else if (installLocation == PackageInfo.INSTALL_LOCATION_AUTO) {
4718 // Prefer previous location
4719 return prevOnSd ? PackageHelper.RECOMMEND_INSTALL_EXTERNAL:
4720 PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4721 }
4722 }
4723 } else {
4724 // Invalid install. Return error code
4725 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4726 }
4727 }
4728 }
4729 // All the special cases have been taken care of.
4730 // Return result based on recommended install location.
4731 if (onSd) {
4732 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4733 }
4734 return pkgLite.recommendedInstallLocation;
4735 }
4736
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004737 /*
4738 * Invoke remote method to get package information and install
4739 * location values. Override install location based on default
4740 * policy if needed and then create install arguments based
4741 * on the install location.
4742 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004743 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004744 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004745 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4746 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004747 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4748 if (onInt && onSd) {
4749 // Check if both bits are set.
4750 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4751 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4752 } else if (fwdLocked && onSd) {
4753 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004754 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004755 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004756 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004757 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004758 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004759 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004760 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4761 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4762 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4763 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4764 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004765 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4766 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4767 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004768 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4769 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004770 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004771 // Override with defaults if needed.
4772 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004773 if (!onSd && !onInt) {
4774 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004775 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4776 // Set the flag to install on external media.
4777 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004778 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004779 } else {
4780 // Make sure the flag for installing on external
4781 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004782 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004783 flags &= ~PackageManager.INSTALL_EXTERNAL;
4784 }
4785 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004786 }
4787 }
4788 // Create the file args now.
4789 mArgs = createInstallArgs(this);
4790 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4791 // Create copy only if we are not in an erroneous state.
4792 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004793 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004794 }
4795 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004796 }
4797
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004798 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004799 void handleReturnCode() {
4800 processPendingInstall(mArgs, mRet);
4801 }
4802
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004803 @Override
4804 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004805 mArgs = createInstallArgs(this);
4806 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004807 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004808 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004809
4810 /*
4811 * Utility class used in movePackage api.
4812 * srcArgs and targetArgs are not set for invalid flags and make
4813 * sure to do null checks when invoking methods on them.
4814 * We probably want to return ErrorPrams for both failed installs
4815 * and moves.
4816 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004817 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004818 final IPackageMoveObserver observer;
4819 final int flags;
4820 final String packageName;
4821 final InstallArgs srcArgs;
4822 final InstallArgs targetArgs;
4823 int mRet;
4824 MoveParams(InstallArgs srcArgs,
4825 IPackageMoveObserver observer,
4826 int flags, String packageName) {
4827 this.srcArgs = srcArgs;
4828 this.observer = observer;
4829 this.flags = flags;
4830 this.packageName = packageName;
4831 if (srcArgs != null) {
4832 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4833 targetArgs = createInstallArgs(packageUri, flags, packageName);
4834 } else {
4835 targetArgs = null;
4836 }
4837 }
4838
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004839 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004840 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4841 // Check for storage space on target medium
4842 if (!targetArgs.checkFreeStorage(mContainerService)) {
4843 Log.w(TAG, "Insufficient storage to install");
4844 return;
4845 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004846 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004847 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004848 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004849 if (DEBUG_SD_INSTALL) {
4850 StringBuilder builder = new StringBuilder();
4851 if (srcArgs != null) {
4852 builder.append("src: ");
4853 builder.append(srcArgs.getCodePath());
4854 }
4855 if (targetArgs != null) {
4856 builder.append(" target : ");
4857 builder.append(targetArgs.getCodePath());
4858 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004859 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004860 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004861 }
4862
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004863 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004864 void handleReturnCode() {
4865 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004866 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4867 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4868 currentStatus = PackageManager.MOVE_SUCCEEDED;
4869 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4870 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4871 }
4872 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004873 }
4874
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004875 @Override
4876 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004877 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004878 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004879 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004880
4881 private InstallArgs createInstallArgs(InstallParams params) {
4882 if (installOnSd(params.flags)) {
4883 return new SdInstallArgs(params);
4884 } else {
4885 return new FileInstallArgs(params);
4886 }
4887 }
4888
4889 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4890 if (installOnSd(flags)) {
4891 return new SdInstallArgs(fullCodePath, fullResourcePath);
4892 } else {
4893 return new FileInstallArgs(fullCodePath, fullResourcePath);
4894 }
4895 }
4896
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004897 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4898 if (installOnSd(flags)) {
4899 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4900 return new SdInstallArgs(packageURI, cid);
4901 } else {
4902 return new FileInstallArgs(packageURI, pkgName);
4903 }
4904 }
4905
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004906 static abstract class InstallArgs {
4907 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004908 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004909 final int flags;
4910 final Uri packageURI;
4911 final String installerPackageName;
4912
4913 InstallArgs(Uri packageURI,
4914 IPackageInstallObserver observer, int flags,
4915 String installerPackageName) {
4916 this.packageURI = packageURI;
4917 this.flags = flags;
4918 this.observer = observer;
4919 this.installerPackageName = installerPackageName;
4920 }
4921
4922 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004923 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004924 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004925 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004926 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004927 abstract String getCodePath();
4928 abstract String getResourcePath();
4929 // Need installer lock especially for dex file removal.
4930 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004931 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004932 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004933 }
4934
4935 class FileInstallArgs extends InstallArgs {
4936 File installDir;
4937 String codeFileName;
4938 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004939 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004940
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004941 FileInstallArgs(InstallParams params) {
4942 super(params.packageURI, params.observer,
4943 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004944 }
4945
4946 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4947 super(null, null, 0, null);
4948 File codeFile = new File(fullCodePath);
4949 installDir = codeFile.getParentFile();
4950 codeFileName = fullCodePath;
4951 resourceFileName = fullResourcePath;
4952 }
4953
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004954 FileInstallArgs(Uri packageURI, String pkgName) {
4955 super(packageURI, null, 0, null);
4956 boolean fwdLocked = isFwdLocked(flags);
4957 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4958 String apkName = getNextCodePath(null, pkgName, ".apk");
4959 codeFileName = new File(installDir, apkName + ".apk").getPath();
4960 resourceFileName = getResourcePathFromCodePath();
4961 }
4962
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004963 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4964 return imcs.checkFreeStorage(false, packageURI);
4965 }
4966
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004967 String getCodePath() {
4968 return codeFileName;
4969 }
4970
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004971 void createCopyFile() {
4972 boolean fwdLocked = isFwdLocked(flags);
4973 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4974 codeFileName = createTempPackageFile(installDir).getPath();
4975 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004976 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004977 }
4978
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004979 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004980 if (temp) {
4981 // Generate temp file name
4982 createCopyFile();
4983 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004984 // Get a ParcelFileDescriptor to write to the output file
4985 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004986 if (!created) {
4987 try {
4988 codeFile.createNewFile();
4989 // Set permissions
4990 if (!setPermissions()) {
4991 // Failed setting permissions.
4992 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4993 }
4994 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004995 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004996 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4997 }
4998 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004999 ParcelFileDescriptor out = null;
5000 try {
5001 out = ParcelFileDescriptor.open(codeFile,
5002 ParcelFileDescriptor.MODE_READ_WRITE);
5003 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005004 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005005 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5006 }
5007 // Copy the resource now
5008 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5009 try {
5010 if (imcs.copyResource(packageURI, out)) {
5011 ret = PackageManager.INSTALL_SUCCEEDED;
5012 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005013 } finally {
5014 try { if (out != null) out.close(); } catch (IOException e) {}
5015 }
5016 return ret;
5017 }
5018
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005019 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005020 if (status != PackageManager.INSTALL_SUCCEEDED) {
5021 cleanUp();
5022 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005023 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005024 }
5025
5026 boolean doRename(int status, final String pkgName, String oldCodePath) {
5027 if (status != PackageManager.INSTALL_SUCCEEDED) {
5028 cleanUp();
5029 return false;
5030 } else {
5031 // Rename based on packageName
5032 File codeFile = new File(getCodePath());
5033 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5034 File desFile = new File(installDir, apkName + ".apk");
5035 if (!codeFile.renameTo(desFile)) {
5036 return false;
5037 }
5038 // Reset paths since the file has been renamed.
5039 codeFileName = desFile.getPath();
5040 resourceFileName = getResourcePathFromCodePath();
5041 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005042 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005043 // Failed setting permissions.
5044 return false;
5045 }
5046 return true;
5047 }
5048 }
5049
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005050 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005051 if (status != PackageManager.INSTALL_SUCCEEDED) {
5052 cleanUp();
5053 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005054 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005055 }
5056
5057 String getResourcePath() {
5058 return resourceFileName;
5059 }
5060
5061 String getResourcePathFromCodePath() {
5062 String codePath = getCodePath();
5063 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5064 String apkNameOnly = getApkName(codePath);
5065 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5066 } else {
5067 return codePath;
5068 }
5069 }
5070
5071 private boolean cleanUp() {
5072 boolean ret = true;
5073 String sourceDir = getCodePath();
5074 String publicSourceDir = getResourcePath();
5075 if (sourceDir != null) {
5076 File sourceFile = new File(sourceDir);
5077 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005078 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005079 ret = false;
5080 }
5081 // Delete application's code and resources
5082 sourceFile.delete();
5083 }
5084 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5085 final File publicSourceFile = new File(publicSourceDir);
5086 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005087 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005088 }
5089 if (publicSourceFile.exists()) {
5090 publicSourceFile.delete();
5091 }
5092 }
5093 return ret;
5094 }
5095
5096 void cleanUpResourcesLI() {
5097 String sourceDir = getCodePath();
5098 if (cleanUp() && mInstaller != null) {
5099 int retCode = mInstaller.rmdex(sourceDir);
5100 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005101 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005102 + " at location "
5103 + sourceDir + ", retcode=" + retCode);
5104 // we don't consider this to be a failure of the core package deletion
5105 }
5106 }
5107 }
5108
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005109 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005110 // TODO Do this in a more elegant way later on. for now just a hack
5111 if (!isFwdLocked(flags)) {
5112 final int filePermissions =
5113 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5114 |FileUtils.S_IROTH;
5115 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5116 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005117 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005118 getCodePath()
5119 + ". The return code was: " + retCode);
5120 // TODO Define new internal error
5121 return false;
5122 }
5123 return true;
5124 }
5125 return true;
5126 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005127
5128 boolean doPostDeleteLI(boolean delete) {
5129 cleanUpResourcesLI();
5130 return true;
5131 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005132 }
5133
5134 class SdInstallArgs extends InstallArgs {
5135 String cid;
5136 String cachePath;
5137 static final String RES_FILE_NAME = "pkg.apk";
5138
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005139 SdInstallArgs(InstallParams params) {
5140 super(params.packageURI, params.observer,
5141 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005142 }
5143
5144 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005145 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005146 // Extract cid from fullCodePath
5147 int eidx = fullCodePath.lastIndexOf("/");
5148 String subStr1 = fullCodePath.substring(0, eidx);
5149 int sidx = subStr1.lastIndexOf("/");
5150 cid = subStr1.substring(sidx+1, eidx);
5151 cachePath = subStr1;
5152 }
5153
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005154 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005155 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5156 this.cid = cid;
5157 }
5158
5159 SdInstallArgs(Uri packageURI, String cid) {
5160 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005161 this.cid = cid;
5162 }
5163
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005164 void createCopyFile() {
5165 cid = getTempContainerId();
5166 }
5167
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005168 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5169 return imcs.checkFreeStorage(true, packageURI);
5170 }
5171
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005172 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005173 if (temp) {
5174 createCopyFile();
5175 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005176 cachePath = imcs.copyResourceToContainer(
5177 packageURI, cid,
5178 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005179 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5180 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005181 }
5182
5183 @Override
5184 String getCodePath() {
5185 return cachePath + "/" + RES_FILE_NAME;
5186 }
5187
5188 @Override
5189 String getResourcePath() {
5190 return cachePath + "/" + RES_FILE_NAME;
5191 }
5192
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005193 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005194 if (status != PackageManager.INSTALL_SUCCEEDED) {
5195 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005196 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005197 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005198 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005199 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005200 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005201 if (cachePath == null) {
5202 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5203 }
5204 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005205 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005206 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005207 }
5208
5209 boolean doRename(int status, final String pkgName,
5210 String oldCodePath) {
5211 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005212 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005213 if (PackageHelper.isContainerMounted(cid)) {
5214 // Unmount the container
5215 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005216 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005217 return false;
5218 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005219 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005220 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005221 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005222 return false;
5223 }
5224 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005225 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005226 newCachePath = PackageHelper.mountSdDir(newCacheId,
5227 getEncryptKey(), Process.SYSTEM_UID);
5228 } else {
5229 newCachePath = PackageHelper.getSdDir(newCacheId);
5230 }
5231 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005232 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005233 return false;
5234 }
5235 Log.i(TAG, "Succesfully renamed " + cid +
5236 " at path: " + cachePath + " to " + newCacheId +
5237 " at new path: " + newCachePath);
5238 cid = newCacheId;
5239 cachePath = newCachePath;
5240 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005241 }
5242
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005243 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005244 if (status != PackageManager.INSTALL_SUCCEEDED) {
5245 cleanUp();
5246 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005247 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005248 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005249 PackageHelper.mountSdDir(cid,
5250 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005251 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005252 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005253 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005254 }
5255
5256 private void cleanUp() {
5257 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005258 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005259 }
5260
5261 void cleanUpResourcesLI() {
5262 String sourceFile = getCodePath();
5263 // Remove dex file
5264 if (mInstaller != null) {
5265 int retCode = mInstaller.rmdex(sourceFile.toString());
5266 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005267 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005268 + " at location "
5269 + sourceFile.toString() + ", retcode=" + retCode);
5270 // we don't consider this to be a failure of the core package deletion
5271 }
5272 }
5273 cleanUp();
5274 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005275
5276 boolean matchContainer(String app) {
5277 if (cid.startsWith(app)) {
5278 return true;
5279 }
5280 return false;
5281 }
5282
5283 String getPackageName() {
5284 int idx = cid.lastIndexOf("-");
5285 if (idx == -1) {
5286 return cid;
5287 }
5288 return cid.substring(0, idx);
5289 }
5290
5291 boolean doPostDeleteLI(boolean delete) {
5292 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005293 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005294 if (mounted) {
5295 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005296 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005297 }
5298 if (ret && delete) {
5299 cleanUpResourcesLI();
5300 }
5301 return ret;
5302 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005303 };
5304
5305 // Utility method used to create code paths based on package name and available index.
5306 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5307 String idxStr = "";
5308 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005309 // Fall back to default value of idx=1 if prefix is not
5310 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005311 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005312 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005313 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005314 if (subStr.endsWith(suffix)) {
5315 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005316 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005317 // If oldCodePath already contains prefix find out the
5318 // ending index to either increment or decrement.
5319 int sidx = subStr.lastIndexOf(prefix);
5320 if (sidx != -1) {
5321 subStr = subStr.substring(sidx + prefix.length());
5322 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005323 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5324 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005325 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005326 try {
5327 idx = Integer.parseInt(subStr);
5328 if (idx <= 1) {
5329 idx++;
5330 } else {
5331 idx--;
5332 }
5333 } catch(NumberFormatException e) {
5334 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005335 }
5336 }
5337 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005338 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005339 return prefix + idxStr;
5340 }
5341
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005342 // Utility method used to ignore ADD/REMOVE events
5343 // by directory observer.
5344 private static boolean ignoreCodePath(String fullPathStr) {
5345 String apkName = getApkName(fullPathStr);
5346 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5347 if (idx != -1 && ((idx+1) < apkName.length())) {
5348 // Make sure the package ends with a numeral
5349 String version = apkName.substring(idx+1);
5350 try {
5351 Integer.parseInt(version);
5352 return true;
5353 } catch (NumberFormatException e) {}
5354 }
5355 return false;
5356 }
5357
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005358 // Utility method that returns the relative package path with respect
5359 // to the installation directory. Like say for /data/data/com.test-1.apk
5360 // string com.test-1 is returned.
5361 static String getApkName(String codePath) {
5362 if (codePath == null) {
5363 return null;
5364 }
5365 int sidx = codePath.lastIndexOf("/");
5366 int eidx = codePath.lastIndexOf(".");
5367 if (eidx == -1) {
5368 eidx = codePath.length();
5369 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005370 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005371 return null;
5372 }
5373 return codePath.substring(sidx+1, eidx);
5374 }
5375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005376 class PackageInstalledInfo {
5377 String name;
5378 int uid;
5379 PackageParser.Package pkg;
5380 int returnCode;
5381 PackageRemovedInfo removedInfo;
5382 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 /*
5385 * Install a non-existing package.
5386 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005387 private void installNewPackageLI(PackageParser.Package pkg,
5388 int parseFlags,
5389 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005390 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005391 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005392 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005393
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005394 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 res.name = pkgName;
5396 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005397 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005398 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005399 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005400 + " without first uninstalling.");
5401 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5402 return;
5403 }
5404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005405 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005406 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005407 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005408 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5410 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5411 }
5412 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005413 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005414 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 res);
5416 // delete the partially installed application. the data directory will have to be
5417 // restored if it was already existing
5418 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5419 // remove package from internal structures. Note that we want deletePackageX to
5420 // delete the package data and cache directories that it created in
5421 // scanPackageLocked, unless those directories existed before we even tried to
5422 // install.
5423 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005424 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005425 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5426 res.removedInfo);
5427 }
5428 }
5429 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005430
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005431 private void replacePackageLI(PackageParser.Package pkg,
5432 int parseFlags,
5433 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005434 String installerPackageName, PackageInstalledInfo res) {
5435
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005436 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005437 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438 // First find the old package info and check signatures
5439 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005440 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005441 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005442 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5444 return;
5445 }
5446 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005447 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005448 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005449 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005451 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 }
5453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005456 PackageParser.Package pkg,
5457 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005458 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459 PackageParser.Package newPackage = null;
5460 String pkgName = deletedPackage.packageName;
5461 boolean deletedPkg = true;
5462 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005463
Jacek Surazski65e13172009-04-28 15:26:38 +02005464 String oldInstallerPackageName = null;
5465 synchronized (mPackages) {
5466 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005468
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005469 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005471 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005472 res.removedInfo)) {
5473 // If the existing package was'nt successfully deleted
5474 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5475 deletedPkg = false;
5476 } else {
5477 // Successfully deleted the old package. Now proceed with re-installation
5478 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005479 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005480 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005481 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005482 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5483 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005484 }
5485 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005486 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005487 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 res);
5489 updatedSettings = true;
5490 }
5491 }
5492
5493 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5494 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005495 // were keeping around in case we needed them (see below) can now be deleted.
5496 // This info will be set on the res.removedInfo to clean up later on as post
5497 // install action.
5498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 //update signature on the new package setting
5500 //this should always succeed, since we checked the
5501 //signature earlier.
5502 synchronized(mPackages) {
5503 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5504 parseFlags, true);
5505 }
5506 } else {
5507 // remove package from internal structures. Note that we want deletePackageX to
5508 // delete the package data and cache directories that it created in
5509 // scanPackageLocked, unless those directories existed before we even tried to
5510 // install.
5511 if(updatedSettings) {
5512 deletePackageLI(
5513 pkgName, true,
5514 PackageManager.DONT_DELETE_DATA,
5515 res.removedInfo);
5516 }
5517 // Since we failed to install the new package we need to restore the old
5518 // package that we deleted.
5519 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005520 File restoreFile = new File(deletedPackage.mPath);
5521 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005522 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005523 return;
5524 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005525 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5526 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005527 // Parse old package
5528 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5529 scanPackageLI(restoreFile, parseFlags, scanMode);
5530 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005531 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5532 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005533 mSettings.writeLP();
5534 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005535 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005536 Slog.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005538 }
5539 }
5540 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005543 PackageParser.Package pkg,
5544 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005545 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 PackageParser.Package newPackage = null;
5547 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005548 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549 PackageParser.PARSE_IS_SYSTEM;
5550 String packageName = deletedPackage.packageName;
5551 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5552 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005553 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005554 return;
5555 }
5556 PackageParser.Package oldPkg;
5557 PackageSetting oldPkgSetting;
5558 synchronized (mPackages) {
5559 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005560 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5562 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005563 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005564 return;
5565 }
5566 }
5567 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5568 res.removedInfo.removedPackage = packageName;
5569 // Remove existing system package
5570 removePackageLI(oldPkg, true);
5571 synchronized (mPackages) {
5572 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5573 }
5574
5575 // Successfully disabled the old package. Now proceed with re-installation
5576 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5577 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005578 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005580 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5582 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5583 }
5584 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005585 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 updatedSettings = true;
5587 }
5588
5589 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5590 //update signature on the new package setting
5591 //this should always succeed, since we checked the
5592 //signature earlier.
5593 synchronized(mPackages) {
5594 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5595 parseFlags, true);
5596 }
5597 } else {
5598 // Re installation failed. Restore old information
5599 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005600 if (newPackage != null) {
5601 removePackageLI(newPackage, true);
5602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005604 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005605 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005606 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 // Restore the old system information in Settings
5608 synchronized(mPackages) {
5609 if(updatedSettings) {
5610 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005611 mSettings.setInstallerPackageName(packageName,
5612 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 }
5614 mSettings.writeLP();
5615 }
5616 }
5617 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005618
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005619 // Utility method used to move dex files during install.
5620 private int moveDexFiles(PackageParser.Package newPackage) {
5621 int retCode;
5622 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5623 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5624 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005625 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005626 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5627 }
5628 }
5629 return PackageManager.INSTALL_SUCCEEDED;
5630 }
5631
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005632 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005633 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005634 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 synchronized (mPackages) {
5636 //write settings. the installStatus will be incomplete at this stage.
5637 //note that the new package setting would have already been
5638 //added to mPackages. It hasn't been persisted yet.
5639 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5640 mSettings.writeLP();
5641 }
5642
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005643 if ((res.returnCode = moveDexFiles(newPackage))
5644 != PackageManager.INSTALL_SUCCEEDED) {
5645 // Discontinue if moving dex files failed.
5646 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005648 if((res.returnCode = setPermissionsLI(newPackage))
5649 != PackageManager.INSTALL_SUCCEEDED) {
5650 if (mInstaller != null) {
5651 mInstaller.rmdex(newPackage.mScanPath);
5652 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005653 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005655 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005658 updatePermissionsLP(newPackage.packageName, newPackage,
5659 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 res.name = pkgName;
5661 res.uid = newPackage.applicationInfo.uid;
5662 res.pkg = newPackage;
5663 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005664 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5666 //to update install status
5667 mSettings.writeLP();
5668 }
5669 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005670
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005671 private void installPackageLI(InstallArgs args,
5672 boolean newInstall, PackageInstalledInfo res) {
5673 int pFlags = args.flags;
5674 String installerPackageName = args.installerPackageName;
5675 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005676 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005677 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005678 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005679 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5680 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005681 // Result object to be returned
5682 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5683
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005684 // Retrieve PackageSettings and parse package
5685 int parseFlags = PackageParser.PARSE_CHATTY |
5686 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5687 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5688 parseFlags |= mDefParseFlags;
5689 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5690 pp.setSeparateProcesses(mSeparateProcesses);
5691 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5692 null, mMetrics, parseFlags);
5693 if (pkg == null) {
5694 res.returnCode = pp.getParseError();
5695 return;
5696 }
5697 String pkgName = res.name = pkg.packageName;
5698 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5699 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5700 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5701 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005703 }
5704 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5705 res.returnCode = pp.getParseError();
5706 return;
5707 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005708 // Get rid of all references to package scan path via parser.
5709 pp = null;
5710 String oldCodePath = null;
5711 boolean systemApp = false;
5712 synchronized (mPackages) {
5713 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005714 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5715 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005716 if (pkg.mOriginalPackages != null
5717 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005718 && mPackages.containsKey(oldName)) {
5719 // This package is derived from an original package,
5720 // and this device has been updating from that original
5721 // name. We must continue using the original name, so
5722 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005723 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005724 pkgName = pkg.packageName;
5725 replace = true;
5726 } else if (mPackages.containsKey(pkgName)) {
5727 // This package, under its official name, already exists
5728 // on the device; we should replace it.
5729 replace = true;
5730 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005731 }
5732 PackageSetting ps = mSettings.mPackages.get(pkgName);
5733 if (ps != null) {
5734 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5735 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5736 systemApp = (ps.pkg.applicationInfo.flags &
5737 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005738 }
5739 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005741
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005742 if (systemApp && onSd) {
5743 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005744 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005745 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5746 return;
5747 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005748
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005749 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5750 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5751 return;
5752 }
5753 // Set application objects path explicitly after the rename
5754 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005755 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005756 replacePackageLI(pkg, parseFlags, scanMode,
5757 installerPackageName, res);
5758 } else {
5759 installNewPackageLI(pkg, parseFlags, scanMode,
5760 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 }
5762 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005763
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005764 private int setPermissionsLI(PackageParser.Package newPackage) {
5765 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005766 int retCode = 0;
5767 // TODO Gross hack but fix later. Ideally move this to be a post installation
5768 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005769 if ((newPackage.applicationInfo.flags
5770 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5771 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005772 try {
5773 extractPublicFiles(newPackage, destResourceFile);
5774 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005775 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 -08005776 " forward-locked app.");
5777 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5778 } finally {
5779 //TODO clean up the extracted public files
5780 }
5781 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005782 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 newPackage.applicationInfo.uid);
5784 } else {
5785 final int filePermissions =
5786 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005787 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005788 newPackage.applicationInfo.uid);
5789 }
5790 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005791 // The permissions on the resource file was set when it was copied for
5792 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005793 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005796 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005797 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005799 // TODO Define new internal error
5800 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005801 }
5802 return PackageManager.INSTALL_SUCCEEDED;
5803 }
5804
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005805 private boolean isForwardLocked(PackageParser.Package pkg) {
5806 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005807 }
5808
5809 private void extractPublicFiles(PackageParser.Package newPackage,
5810 File publicZipFile) throws IOException {
5811 final ZipOutputStream publicZipOutStream =
5812 new ZipOutputStream(new FileOutputStream(publicZipFile));
5813 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5814
5815 // Copy manifest, resources.arsc and res directory to public zip
5816
5817 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5818 while (privateZipEntries.hasMoreElements()) {
5819 final ZipEntry zipEntry = privateZipEntries.nextElement();
5820 final String zipEntryName = zipEntry.getName();
5821 if ("AndroidManifest.xml".equals(zipEntryName)
5822 || "resources.arsc".equals(zipEntryName)
5823 || zipEntryName.startsWith("res/")) {
5824 try {
5825 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5826 } catch (IOException e) {
5827 try {
5828 publicZipOutStream.close();
5829 throw e;
5830 } finally {
5831 publicZipFile.delete();
5832 }
5833 }
5834 }
5835 }
5836
5837 publicZipOutStream.close();
5838 FileUtils.setPermissions(
5839 publicZipFile.getAbsolutePath(),
5840 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5841 -1, -1);
5842 }
5843
5844 private static void copyZipEntry(ZipEntry zipEntry,
5845 ZipFile inZipFile,
5846 ZipOutputStream outZipStream) throws IOException {
5847 byte[] buffer = new byte[4096];
5848 int num;
5849
5850 ZipEntry newEntry;
5851 if (zipEntry.getMethod() == ZipEntry.STORED) {
5852 // Preserve the STORED method of the input entry.
5853 newEntry = new ZipEntry(zipEntry);
5854 } else {
5855 // Create a new entry so that the compressed len is recomputed.
5856 newEntry = new ZipEntry(zipEntry.getName());
5857 }
5858 outZipStream.putNextEntry(newEntry);
5859
5860 InputStream data = inZipFile.getInputStream(zipEntry);
5861 while ((num = data.read(buffer)) > 0) {
5862 outZipStream.write(buffer, 0, num);
5863 }
5864 outZipStream.flush();
5865 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 private void deleteTempPackageFiles() {
5868 FilenameFilter filter = new FilenameFilter() {
5869 public boolean accept(File dir, String name) {
5870 return name.startsWith("vmdl") && name.endsWith(".tmp");
5871 }
5872 };
5873 String tmpFilesList[] = mAppInstallDir.list(filter);
5874 if(tmpFilesList == null) {
5875 return;
5876 }
5877 for(int i = 0; i < tmpFilesList.length; i++) {
5878 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5879 tmpFile.delete();
5880 }
5881 }
5882
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005883 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005884 File tmpPackageFile;
5885 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005886 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005888 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005889 return null;
5890 }
5891 try {
5892 FileUtils.setPermissions(
5893 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5894 -1, -1);
5895 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005896 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 return null;
5898 }
5899 return tmpPackageFile;
5900 }
5901
5902 public void deletePackage(final String packageName,
5903 final IPackageDeleteObserver observer,
5904 final int flags) {
5905 mContext.enforceCallingOrSelfPermission(
5906 android.Manifest.permission.DELETE_PACKAGES, null);
5907 // Queue up an async operation since the package deletion may take a little while.
5908 mHandler.post(new Runnable() {
5909 public void run() {
5910 mHandler.removeCallbacks(this);
5911 final boolean succeded = deletePackageX(packageName, true, true, flags);
5912 if (observer != null) {
5913 try {
5914 observer.packageDeleted(succeded);
5915 } catch (RemoteException e) {
5916 Log.i(TAG, "Observer no longer exists.");
5917 } //end catch
5918 } //end if
5919 } //end run
5920 });
5921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 /**
5924 * This method is an internal method that could be get invoked either
5925 * to delete an installed package or to clean up a failed installation.
5926 * After deleting an installed package, a broadcast is sent to notify any
5927 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005928 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005929 * installation wouldn't have sent the initial broadcast either
5930 * The key steps in deleting a package are
5931 * deleting the package information in internal structures like mPackages,
5932 * deleting the packages base directories through installd
5933 * updating mSettings to reflect current status
5934 * persisting settings for later use
5935 * sending a broadcast if necessary
5936 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005937 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5938 boolean deleteCodeAndResources, int flags) {
5939 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005940 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005941
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005942 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5943 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5944 try {
5945 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005946 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005947 return false;
5948 }
5949 } catch (RemoteException e) {
5950 }
5951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005952 synchronized (mInstallLock) {
5953 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5954 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005956 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005957 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5958 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5959
5960 // If the removed package was a system update, the old system packaged
5961 // was re-enabled; we need to broadcast this information
5962 if (systemUpdate) {
5963 Bundle extras = new Bundle(1);
5964 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5965 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5966
5967 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5968 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005971 // Force a gc here.
5972 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005973 // Delete the resources here after sending the broadcast to let
5974 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005975 if (info.args != null) {
5976 synchronized (mInstallLock) {
5977 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005978 }
5979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005980 return res;
5981 }
5982
5983 static class PackageRemovedInfo {
5984 String removedPackage;
5985 int uid = -1;
5986 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005987 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005988 // Clean up resources deleted packages.
5989 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 void sendBroadcast(boolean fullRemove, boolean replacing) {
5992 Bundle extras = new Bundle(1);
5993 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5994 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5995 if (replacing) {
5996 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5997 }
5998 if (removedPackage != null) {
5999 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
6000 }
6001 if (removedUid >= 0) {
6002 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
6003 }
6004 }
6005 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 /*
6008 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6009 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006010 * 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 -08006011 * delete a partially installed application.
6012 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006013 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006014 int flags) {
6015 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006016 if (outInfo != null) {
6017 outInfo.removedPackage = packageName;
6018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 removePackageLI(p, true);
6020 // Retrieve object to delete permissions for shared user later on
6021 PackageSetting deletedPs;
6022 synchronized (mPackages) {
6023 deletedPs = mSettings.mPackages.get(packageName);
6024 }
6025 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006026 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006028 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006030 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 + packageName + ", retcode=" + retCode);
6032 // we don't consider this to be a failure of the core package deletion
6033 }
6034 } else {
6035 //for emulator
6036 PackageParser.Package pkg = mPackages.get(packageName);
6037 File dataDir = new File(pkg.applicationInfo.dataDir);
6038 dataDir.delete();
6039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 }
6041 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006042 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006043 schedulePackageCleaning(packageName);
6044
6045 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6046 if (outInfo != null) {
6047 outInfo.removedUid = mSettings.removePackageLP(packageName);
6048 }
6049 if (deletedPs != null) {
6050 updatePermissionsLP(deletedPs.name, null, false, false);
6051 if (deletedPs.sharedUser != null) {
6052 // remove permissions associated with package
6053 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6054 }
6055 }
6056 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006057 // remove from preferred activities.
6058 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6059 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6060 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6061 removed.add(pa);
6062 }
6063 }
6064 for (PreferredActivity pa : removed) {
6065 mSettings.mPreferredActivities.removeFilter(pa);
6066 }
6067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006068 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006069 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070 }
6071 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006073 /*
6074 * Tries to delete system package.
6075 */
6076 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006077 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 ApplicationInfo applicationInfo = p.applicationInfo;
6079 //applicable for non-partially installed applications only
6080 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006081 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 return false;
6083 }
6084 PackageSetting ps = null;
6085 // Confirm if the system package has been updated
6086 // An updated system app can be deleted. This will also have to restore
6087 // the system pkg from system partition
6088 synchronized (mPackages) {
6089 ps = mSettings.getDisabledSystemPkg(p.packageName);
6090 }
6091 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006092 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 return false;
6094 } else {
6095 Log.i(TAG, "Deleting system pkg from data partition");
6096 }
6097 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006098 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006099 boolean deleteCodeAndResources = false;
6100 if (ps.versionCode < p.mVersionCode) {
6101 // Delete code and resources for downgrades
6102 deleteCodeAndResources = true;
6103 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6104 flags &= ~PackageManager.DONT_DELETE_DATA;
6105 }
6106 } else {
6107 // Preserve data by setting flag
6108 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6109 flags |= PackageManager.DONT_DELETE_DATA;
6110 }
6111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006112 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6113 if (!ret) {
6114 return false;
6115 }
6116 synchronized (mPackages) {
6117 // Reinstate the old system package
6118 mSettings.enableSystemPackageLP(p.packageName);
6119 }
6120 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006121 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006123 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006126 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 return false;
6128 }
6129 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006130 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 mSettings.writeLP();
6132 }
6133 return true;
6134 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006136 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6137 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6138 ApplicationInfo applicationInfo = p.applicationInfo;
6139 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006140 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 return false;
6142 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006143 if (outInfo != null) {
6144 outInfo.uid = applicationInfo.uid;
6145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146
6147 // Delete package data from internal structures and also remove data if flag is set
6148 removePackageDataLI(p, outInfo, flags);
6149
6150 // Delete application code and resources
6151 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006152 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006153 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006154 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006155 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6156 PackageManager.INSTALL_FORWARD_LOCK : 0;
6157 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006158 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006159 }
6160 return true;
6161 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006163 /*
6164 * This method handles package deletion in general
6165 */
6166 private boolean deletePackageLI(String packageName,
6167 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6168 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006169 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006170 return false;
6171 }
6172 PackageParser.Package p;
6173 boolean dataOnly = false;
6174 synchronized (mPackages) {
6175 p = mPackages.get(packageName);
6176 if (p == null) {
6177 //this retrieves partially installed apps
6178 dataOnly = true;
6179 PackageSetting ps = mSettings.mPackages.get(packageName);
6180 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006181 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 return false;
6183 }
6184 p = ps.pkg;
6185 }
6186 }
6187 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006188 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 return false;
6190 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 if (dataOnly) {
6193 // Delete application data first
6194 removePackageDataLI(p, outInfo, flags);
6195 return true;
6196 }
6197 // At this point the package should have ApplicationInfo associated with it
6198 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006199 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 return false;
6201 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006202 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6204 Log.i(TAG, "Removing system package:"+p.packageName);
6205 // When an updated system application is deleted we delete the existing resources as well and
6206 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006207 ret = deleteSystemPackageLI(p, flags, outInfo);
6208 } else {
6209 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006210 // Kill application pre-emptively especially for apps on sd.
6211 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006212 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006214 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217 public void clearApplicationUserData(final String packageName,
6218 final IPackageDataObserver observer) {
6219 mContext.enforceCallingOrSelfPermission(
6220 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6221 // Queue up an async operation since the package deletion may take a little while.
6222 mHandler.post(new Runnable() {
6223 public void run() {
6224 mHandler.removeCallbacks(this);
6225 final boolean succeeded;
6226 synchronized (mInstallLock) {
6227 succeeded = clearApplicationUserDataLI(packageName);
6228 }
6229 if (succeeded) {
6230 // invoke DeviceStorageMonitor's update method to clear any notifications
6231 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6232 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6233 if (dsm != null) {
6234 dsm.updateMemory();
6235 }
6236 }
6237 if(observer != null) {
6238 try {
6239 observer.onRemoveCompleted(packageName, succeeded);
6240 } catch (RemoteException e) {
6241 Log.i(TAG, "Observer no longer exists.");
6242 }
6243 } //end if observer
6244 } //end run
6245 });
6246 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 private boolean clearApplicationUserDataLI(String packageName) {
6249 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006250 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 return false;
6252 }
6253 PackageParser.Package p;
6254 boolean dataOnly = false;
6255 synchronized (mPackages) {
6256 p = mPackages.get(packageName);
6257 if(p == null) {
6258 dataOnly = true;
6259 PackageSetting ps = mSettings.mPackages.get(packageName);
6260 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006261 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 return false;
6263 }
6264 p = ps.pkg;
6265 }
6266 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006267 boolean useEncryptedFSDir = false;
6268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 if(!dataOnly) {
6270 //need to check this only for fully installed applications
6271 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006272 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006273 return false;
6274 }
6275 final ApplicationInfo applicationInfo = p.applicationInfo;
6276 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006277 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 return false;
6279 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006280 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 }
6282 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006283 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006285 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 + packageName);
6287 return false;
6288 }
6289 }
6290 return true;
6291 }
6292
6293 public void deleteApplicationCacheFiles(final String packageName,
6294 final IPackageDataObserver observer) {
6295 mContext.enforceCallingOrSelfPermission(
6296 android.Manifest.permission.DELETE_CACHE_FILES, null);
6297 // Queue up an async operation since the package deletion may take a little while.
6298 mHandler.post(new Runnable() {
6299 public void run() {
6300 mHandler.removeCallbacks(this);
6301 final boolean succeded;
6302 synchronized (mInstallLock) {
6303 succeded = deleteApplicationCacheFilesLI(packageName);
6304 }
6305 if(observer != null) {
6306 try {
6307 observer.onRemoveCompleted(packageName, succeded);
6308 } catch (RemoteException e) {
6309 Log.i(TAG, "Observer no longer exists.");
6310 }
6311 } //end if observer
6312 } //end run
6313 });
6314 }
6315
6316 private boolean deleteApplicationCacheFilesLI(String packageName) {
6317 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006318 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 return false;
6320 }
6321 PackageParser.Package p;
6322 synchronized (mPackages) {
6323 p = mPackages.get(packageName);
6324 }
6325 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006326 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 return false;
6328 }
6329 final ApplicationInfo applicationInfo = p.applicationInfo;
6330 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006331 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 return false;
6333 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006334 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006336 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006337 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006338 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 + packageName);
6340 return false;
6341 }
6342 }
6343 return true;
6344 }
6345
6346 public void getPackageSizeInfo(final String packageName,
6347 final IPackageStatsObserver observer) {
6348 mContext.enforceCallingOrSelfPermission(
6349 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6350 // Queue up an async operation since the package deletion may take a little while.
6351 mHandler.post(new Runnable() {
6352 public void run() {
6353 mHandler.removeCallbacks(this);
6354 PackageStats lStats = new PackageStats(packageName);
6355 final boolean succeded;
6356 synchronized (mInstallLock) {
6357 succeded = getPackageSizeInfoLI(packageName, lStats);
6358 }
6359 if(observer != null) {
6360 try {
6361 observer.onGetStatsCompleted(lStats, succeded);
6362 } catch (RemoteException e) {
6363 Log.i(TAG, "Observer no longer exists.");
6364 }
6365 } //end if observer
6366 } //end run
6367 });
6368 }
6369
6370 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6371 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006372 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 return false;
6374 }
6375 PackageParser.Package p;
6376 boolean dataOnly = false;
6377 synchronized (mPackages) {
6378 p = mPackages.get(packageName);
6379 if(p == null) {
6380 dataOnly = true;
6381 PackageSetting ps = mSettings.mPackages.get(packageName);
6382 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006383 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 return false;
6385 }
6386 p = ps.pkg;
6387 }
6388 }
6389 String publicSrcDir = null;
6390 if(!dataOnly) {
6391 final ApplicationInfo applicationInfo = p.applicationInfo;
6392 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006393 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 return false;
6395 }
6396 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6397 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006398 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006399 if (mInstaller != null) {
6400 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006401 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 if (res < 0) {
6403 return false;
6404 } else {
6405 return true;
6406 }
6407 }
6408 return true;
6409 }
6410
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 public void addPackageToPreferred(String packageName) {
6413 mContext.enforceCallingOrSelfPermission(
6414 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006415 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 }
6417
6418 public void removePackageFromPreferred(String packageName) {
6419 mContext.enforceCallingOrSelfPermission(
6420 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006421 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 }
6423
6424 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006425 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 }
6427
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006428 int getUidTargetSdkVersionLockedLP(int uid) {
6429 Object obj = mSettings.getUserIdLP(uid);
6430 if (obj instanceof SharedUserSetting) {
6431 SharedUserSetting sus = (SharedUserSetting)obj;
6432 final int N = sus.packages.size();
6433 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6434 Iterator<PackageSetting> it = sus.packages.iterator();
6435 int i=0;
6436 while (it.hasNext()) {
6437 PackageSetting ps = it.next();
6438 if (ps.pkg != null) {
6439 int v = ps.pkg.applicationInfo.targetSdkVersion;
6440 if (v < vers) vers = v;
6441 }
6442 }
6443 return vers;
6444 } else if (obj instanceof PackageSetting) {
6445 PackageSetting ps = (PackageSetting)obj;
6446 if (ps.pkg != null) {
6447 return ps.pkg.applicationInfo.targetSdkVersion;
6448 }
6449 }
6450 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6451 }
6452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 public void addPreferredActivity(IntentFilter filter, int match,
6454 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006456 if (mContext.checkCallingOrSelfPermission(
6457 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6458 != PackageManager.PERMISSION_GRANTED) {
6459 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6460 < Build.VERSION_CODES.FROYO) {
6461 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6462 + Binder.getCallingUid());
6463 return;
6464 }
6465 mContext.enforceCallingOrSelfPermission(
6466 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6467 }
6468
6469 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6471 mSettings.mPreferredActivities.addFilter(
6472 new PreferredActivity(filter, match, set, activity));
6473 mSettings.writeLP();
6474 }
6475 }
6476
Satish Sampath8dbe6122009-06-02 23:35:54 +01006477 public void replacePreferredActivity(IntentFilter filter, int match,
6478 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006479 if (filter.countActions() != 1) {
6480 throw new IllegalArgumentException(
6481 "replacePreferredActivity expects filter to have only 1 action.");
6482 }
6483 if (filter.countCategories() != 1) {
6484 throw new IllegalArgumentException(
6485 "replacePreferredActivity expects filter to have only 1 category.");
6486 }
6487 if (filter.countDataAuthorities() != 0
6488 || filter.countDataPaths() != 0
6489 || filter.countDataSchemes() != 0
6490 || filter.countDataTypes() != 0) {
6491 throw new IllegalArgumentException(
6492 "replacePreferredActivity expects filter to have no data authorities, " +
6493 "paths, schemes or types.");
6494 }
6495 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006496 if (mContext.checkCallingOrSelfPermission(
6497 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6498 != PackageManager.PERMISSION_GRANTED) {
6499 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6500 < Build.VERSION_CODES.FROYO) {
6501 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6502 + Binder.getCallingUid());
6503 return;
6504 }
6505 mContext.enforceCallingOrSelfPermission(
6506 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6507 }
6508
Satish Sampath8dbe6122009-06-02 23:35:54 +01006509 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6510 String action = filter.getAction(0);
6511 String category = filter.getCategory(0);
6512 while (it.hasNext()) {
6513 PreferredActivity pa = it.next();
6514 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6515 it.remove();
6516 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6517 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6518 }
6519 }
6520 addPreferredActivity(filter, match, set, activity);
6521 }
6522 }
6523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006526 int uid = Binder.getCallingUid();
6527 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006528 if (pkg == null || pkg.applicationInfo.uid != uid) {
6529 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 clearPackagePreferredActivities() from uid "
6535 + Binder.getCallingUid());
6536 return;
6537 }
6538 mContext.enforceCallingOrSelfPermission(
6539 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6540 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006541 }
6542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 if (clearPackagePreferredActivitiesLP(packageName)) {
6544 mSettings.writeLP();
6545 }
6546 }
6547 }
6548
6549 boolean clearPackagePreferredActivitiesLP(String packageName) {
6550 boolean changed = false;
6551 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6552 while (it.hasNext()) {
6553 PreferredActivity pa = it.next();
6554 if (pa.mActivity.getPackageName().equals(packageName)) {
6555 it.remove();
6556 changed = true;
6557 }
6558 }
6559 return changed;
6560 }
6561
6562 public int getPreferredActivities(List<IntentFilter> outFilters,
6563 List<ComponentName> outActivities, String packageName) {
6564
6565 int num = 0;
6566 synchronized (mPackages) {
6567 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6568 while (it.hasNext()) {
6569 PreferredActivity pa = it.next();
6570 if (packageName == null
6571 || pa.mActivity.getPackageName().equals(packageName)) {
6572 if (outFilters != null) {
6573 outFilters.add(new IntentFilter(pa));
6574 }
6575 if (outActivities != null) {
6576 outActivities.add(pa.mActivity);
6577 }
6578 }
6579 }
6580 }
6581
6582 return num;
6583 }
6584
6585 public void setApplicationEnabledSetting(String appPackageName,
6586 int newState, int flags) {
6587 setEnabledSetting(appPackageName, null, newState, flags);
6588 }
6589
6590 public void setComponentEnabledSetting(ComponentName componentName,
6591 int newState, int flags) {
6592 setEnabledSetting(componentName.getPackageName(),
6593 componentName.getClassName(), newState, flags);
6594 }
6595
6596 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006597 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6599 || newState == COMPONENT_ENABLED_STATE_ENABLED
6600 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6601 throw new IllegalArgumentException("Invalid new component state: "
6602 + newState);
6603 }
6604 PackageSetting pkgSetting;
6605 final int uid = Binder.getCallingUid();
6606 final int permission = mContext.checkCallingPermission(
6607 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6608 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006609 boolean sendNow = false;
6610 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006611 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006613 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006615 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006617 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006619 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 }
6621 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006622 "Unknown component: " + packageName
6623 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 }
6625 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6626 throw new SecurityException(
6627 "Permission Denial: attempt to change component state from pid="
6628 + Binder.getCallingPid()
6629 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6630 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006631 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 // We're dealing with an application/package level state change
6633 pkgSetting.enabled = newState;
6634 } else {
6635 // We're dealing with a component level state change
6636 switch (newState) {
6637 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006638 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 break;
6640 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006641 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006642 break;
6643 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006644 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 break;
6646 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006647 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006648 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006649 }
6650 }
6651 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006652 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006653 components = mPendingBroadcasts.get(packageName);
6654 boolean newPackage = components == null;
6655 if (newPackage) {
6656 components = new ArrayList<String>();
6657 }
6658 if (!components.contains(componentName)) {
6659 components.add(componentName);
6660 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006661 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6662 sendNow = true;
6663 // Purge entry from pending broadcast list if another one exists already
6664 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006665 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006666 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006667 if (newPackage) {
6668 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006669 }
6670 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6671 // Schedule a message
6672 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6673 }
6674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677 long callingId = Binder.clearCallingIdentity();
6678 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006679 if (sendNow) {
6680 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006681 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 } finally {
6684 Binder.restoreCallingIdentity(callingId);
6685 }
6686 }
6687
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006688 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006689 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6690 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6691 + " components=" + componentNames);
6692 Bundle extras = new Bundle(4);
6693 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6694 String nameList[] = new String[componentNames.size()];
6695 componentNames.toArray(nameList);
6696 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006697 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6698 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006699 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006700 }
6701
Jacek Surazski65e13172009-04-28 15:26:38 +02006702 public String getInstallerPackageName(String packageName) {
6703 synchronized (mPackages) {
6704 PackageSetting pkg = mSettings.mPackages.get(packageName);
6705 if (pkg == null) {
6706 throw new IllegalArgumentException("Unknown package: " + packageName);
6707 }
6708 return pkg.installerPackageName;
6709 }
6710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 public int getApplicationEnabledSetting(String appPackageName) {
6713 synchronized (mPackages) {
6714 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6715 if (pkg == null) {
6716 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6717 }
6718 return pkg.enabled;
6719 }
6720 }
6721
6722 public int getComponentEnabledSetting(ComponentName componentName) {
6723 synchronized (mPackages) {
6724 final String packageNameStr = componentName.getPackageName();
6725 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6726 if (pkg == null) {
6727 throw new IllegalArgumentException("Unknown component: " + componentName);
6728 }
6729 final String classNameStr = componentName.getClassName();
6730 return pkg.currentEnabledStateLP(classNameStr);
6731 }
6732 }
6733
6734 public void enterSafeMode() {
6735 if (!mSystemReady) {
6736 mSafeMode = true;
6737 }
6738 }
6739
6740 public void systemReady() {
6741 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006742
6743 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006744 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006745 mContext.getContentResolver(),
6746 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006747 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006748 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006749 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006751 }
6752
6753 public boolean isSafeMode() {
6754 return mSafeMode;
6755 }
6756
6757 public boolean hasSystemUidErrors() {
6758 return mHasSystemUidErrors;
6759 }
6760
6761 static String arrayToString(int[] array) {
6762 StringBuffer buf = new StringBuffer(128);
6763 buf.append('[');
6764 if (array != null) {
6765 for (int i=0; i<array.length; i++) {
6766 if (i > 0) buf.append(", ");
6767 buf.append(array[i]);
6768 }
6769 }
6770 buf.append(']');
6771 return buf.toString();
6772 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 @Override
6775 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6776 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6777 != PackageManager.PERMISSION_GRANTED) {
6778 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6779 + Binder.getCallingPid()
6780 + ", uid=" + Binder.getCallingUid()
6781 + " without permission "
6782 + android.Manifest.permission.DUMP);
6783 return;
6784 }
6785
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006786 String packageName = null;
6787
6788 int opti = 0;
6789 while (opti < args.length) {
6790 String opt = args[opti];
6791 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6792 break;
6793 }
6794 opti++;
6795 if ("-a".equals(opt)) {
6796 // Right now we only know how to print all.
6797 } else if ("-h".equals(opt)) {
6798 pw.println("Package manager dump options:");
6799 pw.println(" [-h] [cmd] ...");
6800 pw.println(" cmd may be one of:");
6801 pw.println(" [package.name]: info about given package");
6802 return;
6803 } else {
6804 pw.println("Unknown argument: " + opt + "; use -h for help");
6805 }
6806 }
6807
6808 // Is the caller requesting to dump a particular piece of data?
6809 if (opti < args.length) {
6810 String cmd = args[opti];
6811 opti++;
6812 // Is this a package name?
6813 if ("android".equals(cmd) || cmd.contains(".")) {
6814 packageName = cmd;
6815 }
6816 }
6817
6818 boolean printedTitle = false;
6819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006820 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006821 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6822 printedTitle = true;
6823 }
6824 if (mReceivers.dump(pw, printedTitle
6825 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6826 " ", packageName)) {
6827 printedTitle = true;
6828 }
6829 if (mServices.dump(pw, printedTitle
6830 ? "\nService Resolver Table:" : "Service Resolver Table:",
6831 " ", packageName)) {
6832 printedTitle = true;
6833 }
6834 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6835 ? "\nPreferred Activities:" : "Preferred Activities:",
6836 " ", packageName)) {
6837 printedTitle = true;
6838 }
6839 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 {
6841 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006842 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6843 continue;
6844 }
6845 if (!printedSomething) {
6846 if (printedTitle) pw.println(" ");
6847 pw.println("Permissions:");
6848 printedSomething = true;
6849 printedTitle = true;
6850 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006851 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6852 pw.print(Integer.toHexString(System.identityHashCode(p)));
6853 pw.println("):");
6854 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6855 pw.print(" uid="); pw.print(p.uid);
6856 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006857 pw.print(" type="); pw.print(p.type);
6858 pw.print(" prot="); pw.println(p.protectionLevel);
6859 if (p.packageSetting != null) {
6860 pw.print(" packageSetting="); pw.println(p.packageSetting);
6861 }
6862 if (p.perm != null) {
6863 pw.print(" perm="); pw.println(p.perm);
6864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865 }
6866 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006867 printedSomething = false;
6868 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006869 {
6870 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006871 if (packageName != null && !packageName.equals(ps.realName)
6872 && !packageName.equals(ps.name)) {
6873 continue;
6874 }
6875 if (!printedSomething) {
6876 if (printedTitle) pw.println(" ");
6877 pw.println("Packages:");
6878 printedSomething = true;
6879 printedTitle = true;
6880 }
6881 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006882 pw.print(" Package [");
6883 pw.print(ps.realName != null ? ps.realName : ps.name);
6884 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006885 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6886 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006887 if (ps.realName != null) {
6888 pw.print(" compat name="); pw.println(ps.name);
6889 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006890 pw.print(" userId="); pw.print(ps.userId);
6891 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6892 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6893 pw.print(" pkg="); pw.println(ps.pkg);
6894 pw.print(" codePath="); pw.println(ps.codePathString);
6895 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006896 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006897 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006898 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006899 pw.print(" supportsScreens=[");
6900 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006901 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006902 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006903 if (!first) pw.print(", ");
6904 first = false;
6905 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006906 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006907 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006908 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006909 if (!first) pw.print(", ");
6910 first = false;
6911 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006913 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006914 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006915 if (!first) pw.print(", ");
6916 first = false;
6917 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006918 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006919 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006920 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006921 if (!first) pw.print(", ");
6922 first = false;
6923 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006924 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006925 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006926 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6927 if (!first) pw.print(", ");
6928 first = false;
6929 pw.print("anyDensity");
6930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006931 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006932 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006933 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6934 pw.print(" signatures="); pw.println(ps.signatures);
6935 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6936 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6937 pw.print(" installStatus="); pw.print(ps.installStatus);
6938 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006939 if (ps.disabledComponents.size() > 0) {
6940 pw.println(" disabledComponents:");
6941 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006942 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006943 }
6944 }
6945 if (ps.enabledComponents.size() > 0) {
6946 pw.println(" enabledComponents:");
6947 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006948 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006949 }
6950 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006951 if (ps.grantedPermissions.size() > 0) {
6952 pw.println(" grantedPermissions:");
6953 for (String s : ps.grantedPermissions) {
6954 pw.print(" "); pw.println(s);
6955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006956 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006957 if (ps.loadedPermissions.size() > 0) {
6958 pw.println(" loadedPermissions:");
6959 for (String s : ps.loadedPermissions) {
6960 pw.print(" "); pw.println(s);
6961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006962 }
6963 }
6964 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006965 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006966 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006967 for (HashMap.Entry<String, String> e
6968 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006969 if (packageName != null && !packageName.equals(e.getKey())
6970 && !packageName.equals(e.getValue())) {
6971 continue;
6972 }
6973 if (!printedSomething) {
6974 if (printedTitle) pw.println(" ");
6975 pw.println("Renamed packages:");
6976 printedSomething = true;
6977 printedTitle = true;
6978 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006979 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6980 pw.println(e.getValue());
6981 }
6982 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006983 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006984 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006985 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006986 if (packageName != null && !packageName.equals(ps.realName)
6987 && !packageName.equals(ps.name)) {
6988 continue;
6989 }
6990 if (!printedSomething) {
6991 if (printedTitle) pw.println(" ");
6992 pw.println("Hidden system packages:");
6993 printedSomething = true;
6994 printedTitle = true;
6995 }
6996 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006997 pw.print(ps.realName != null ? ps.realName : ps.name);
6998 pw.print("] (");
6999 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7000 pw.println("):");
7001 if (ps.realName != null) {
7002 pw.print(" compat name="); pw.println(ps.name);
7003 }
7004 pw.print(" userId="); pw.println(ps.userId);
7005 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7006 pw.print(" codePath="); pw.println(ps.codePathString);
7007 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7008 }
7009 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007010 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 {
7012 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007013 if (packageName != null && su != packageSharedUser) {
7014 continue;
7015 }
7016 if (!printedSomething) {
7017 if (printedTitle) pw.println(" ");
7018 pw.println("Shared users:");
7019 printedSomething = true;
7020 printedTitle = true;
7021 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007022 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7023 pw.print(Integer.toHexString(System.identityHashCode(su)));
7024 pw.println("):");
7025 pw.print(" userId="); pw.print(su.userId);
7026 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 pw.println(" grantedPermissions:");
7028 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007029 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007030 }
7031 pw.println(" loadedPermissions:");
7032 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007033 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007034 }
7035 }
7036 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007037
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007038 if (packageName == null) {
7039 if (printedTitle) pw.println(" ");
7040 printedTitle = true;
7041 pw.println("Settings parse messages:");
7042 pw.println(mSettings.mReadMessages.toString());
7043
7044 pw.println(" ");
7045 pw.println("Package warning messages:");
7046 File fname = getSettingsProblemFile();
7047 FileInputStream in;
7048 try {
7049 in = new FileInputStream(fname);
7050 int avail = in.available();
7051 byte[] data = new byte[avail];
7052 in.read(data);
7053 pw.println(new String(data));
7054 } catch (FileNotFoundException e) {
7055 } catch (IOException e) {
7056 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007058 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007059
7060 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007061 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007062 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007063 if (packageName != null && !packageName.equals(p.info.packageName)) {
7064 continue;
7065 }
7066 if (!printedSomething) {
7067 if (printedTitle) pw.println(" ");
7068 pw.println("Registered ContentProviders:");
7069 printedSomething = true;
7070 printedTitle = true;
7071 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007072 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007073 pw.println(p.toString());
7074 }
7075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007076 }
7077
7078 static final class BasePermission {
7079 final static int TYPE_NORMAL = 0;
7080 final static int TYPE_BUILTIN = 1;
7081 final static int TYPE_DYNAMIC = 2;
7082
7083 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007084 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007085 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007086 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007087 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007088 PackageParser.Permission perm;
7089 PermissionInfo pendingInfo;
7090 int uid;
7091 int[] gids;
7092
7093 BasePermission(String _name, String _sourcePackage, int _type) {
7094 name = _name;
7095 sourcePackage = _sourcePackage;
7096 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007097 // Default to most conservative protection level.
7098 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7099 }
7100
7101 public String toString() {
7102 return "BasePermission{"
7103 + Integer.toHexString(System.identityHashCode(this))
7104 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007105 }
7106 }
7107
7108 static class PackageSignatures {
7109 private Signature[] mSignatures;
7110
7111 PackageSignatures(Signature[] sigs) {
7112 assignSignatures(sigs);
7113 }
7114
7115 PackageSignatures() {
7116 }
7117
7118 void writeXml(XmlSerializer serializer, String tagName,
7119 ArrayList<Signature> pastSignatures) throws IOException {
7120 if (mSignatures == null) {
7121 return;
7122 }
7123 serializer.startTag(null, tagName);
7124 serializer.attribute(null, "count",
7125 Integer.toString(mSignatures.length));
7126 for (int i=0; i<mSignatures.length; i++) {
7127 serializer.startTag(null, "cert");
7128 final Signature sig = mSignatures[i];
7129 final int sigHash = sig.hashCode();
7130 final int numPast = pastSignatures.size();
7131 int j;
7132 for (j=0; j<numPast; j++) {
7133 Signature pastSig = pastSignatures.get(j);
7134 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7135 serializer.attribute(null, "index", Integer.toString(j));
7136 break;
7137 }
7138 }
7139 if (j >= numPast) {
7140 pastSignatures.add(sig);
7141 serializer.attribute(null, "index", Integer.toString(numPast));
7142 serializer.attribute(null, "key", sig.toCharsString());
7143 }
7144 serializer.endTag(null, "cert");
7145 }
7146 serializer.endTag(null, tagName);
7147 }
7148
7149 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7150 throws IOException, XmlPullParserException {
7151 String countStr = parser.getAttributeValue(null, "count");
7152 if (countStr == null) {
7153 reportSettingsProblem(Log.WARN,
7154 "Error in package manager settings: <signatures> has"
7155 + " no count at " + parser.getPositionDescription());
7156 XmlUtils.skipCurrentTag(parser);
7157 }
7158 final int count = Integer.parseInt(countStr);
7159 mSignatures = new Signature[count];
7160 int pos = 0;
7161
7162 int outerDepth = parser.getDepth();
7163 int type;
7164 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7165 && (type != XmlPullParser.END_TAG
7166 || parser.getDepth() > outerDepth)) {
7167 if (type == XmlPullParser.END_TAG
7168 || type == XmlPullParser.TEXT) {
7169 continue;
7170 }
7171
7172 String tagName = parser.getName();
7173 if (tagName.equals("cert")) {
7174 if (pos < count) {
7175 String index = parser.getAttributeValue(null, "index");
7176 if (index != null) {
7177 try {
7178 int idx = Integer.parseInt(index);
7179 String key = parser.getAttributeValue(null, "key");
7180 if (key == null) {
7181 if (idx >= 0 && idx < pastSignatures.size()) {
7182 Signature sig = pastSignatures.get(idx);
7183 if (sig != null) {
7184 mSignatures[pos] = pastSignatures.get(idx);
7185 pos++;
7186 } else {
7187 reportSettingsProblem(Log.WARN,
7188 "Error in package manager settings: <cert> "
7189 + "index " + index + " is not defined at "
7190 + parser.getPositionDescription());
7191 }
7192 } else {
7193 reportSettingsProblem(Log.WARN,
7194 "Error in package manager settings: <cert> "
7195 + "index " + index + " is out of bounds at "
7196 + parser.getPositionDescription());
7197 }
7198 } else {
7199 while (pastSignatures.size() <= idx) {
7200 pastSignatures.add(null);
7201 }
7202 Signature sig = new Signature(key);
7203 pastSignatures.set(idx, sig);
7204 mSignatures[pos] = sig;
7205 pos++;
7206 }
7207 } catch (NumberFormatException e) {
7208 reportSettingsProblem(Log.WARN,
7209 "Error in package manager settings: <cert> "
7210 + "index " + index + " is not a number at "
7211 + parser.getPositionDescription());
7212 }
7213 } else {
7214 reportSettingsProblem(Log.WARN,
7215 "Error in package manager settings: <cert> has"
7216 + " no index at " + parser.getPositionDescription());
7217 }
7218 } else {
7219 reportSettingsProblem(Log.WARN,
7220 "Error in package manager settings: too "
7221 + "many <cert> tags, expected " + count
7222 + " at " + parser.getPositionDescription());
7223 }
7224 } else {
7225 reportSettingsProblem(Log.WARN,
7226 "Unknown element under <cert>: "
7227 + parser.getName());
7228 }
7229 XmlUtils.skipCurrentTag(parser);
7230 }
7231
7232 if (pos < count) {
7233 // Should never happen -- there is an error in the written
7234 // settings -- but if it does we don't want to generate
7235 // a bad array.
7236 Signature[] newSigs = new Signature[pos];
7237 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7238 mSignatures = newSigs;
7239 }
7240 }
7241
7242 /**
7243 * If any of the given 'sigs' is contained in the existing signatures,
7244 * then completely replace the current signatures with the ones in
7245 * 'sigs'. This is used for updating an existing package to a newly
7246 * installed version.
7247 */
7248 boolean updateSignatures(Signature[] sigs, boolean update) {
7249 if (mSignatures == null) {
7250 if (update) {
7251 assignSignatures(sigs);
7252 }
7253 return true;
7254 }
7255 if (sigs == null) {
7256 return false;
7257 }
7258
7259 for (int i=0; i<sigs.length; i++) {
7260 Signature sig = sigs[i];
7261 for (int j=0; j<mSignatures.length; j++) {
7262 if (mSignatures[j].equals(sig)) {
7263 if (update) {
7264 assignSignatures(sigs);
7265 }
7266 return true;
7267 }
7268 }
7269 }
7270 return false;
7271 }
7272
7273 /**
7274 * If any of the given 'sigs' is contained in the existing signatures,
7275 * then add in any new signatures found in 'sigs'. This is used for
7276 * including a new package into an existing shared user id.
7277 */
7278 boolean mergeSignatures(Signature[] sigs, boolean update) {
7279 if (mSignatures == null) {
7280 if (update) {
7281 assignSignatures(sigs);
7282 }
7283 return true;
7284 }
7285 if (sigs == null) {
7286 return false;
7287 }
7288
7289 Signature[] added = null;
7290 int addedCount = 0;
7291 boolean haveMatch = false;
7292 for (int i=0; i<sigs.length; i++) {
7293 Signature sig = sigs[i];
7294 boolean found = false;
7295 for (int j=0; j<mSignatures.length; j++) {
7296 if (mSignatures[j].equals(sig)) {
7297 found = true;
7298 haveMatch = true;
7299 break;
7300 }
7301 }
7302
7303 if (!found) {
7304 if (added == null) {
7305 added = new Signature[sigs.length];
7306 }
7307 added[i] = sig;
7308 addedCount++;
7309 }
7310 }
7311
7312 if (!haveMatch) {
7313 // Nothing matched -- reject the new signatures.
7314 return false;
7315 }
7316 if (added == null) {
7317 // Completely matched -- nothing else to do.
7318 return true;
7319 }
7320
7321 // Add additional signatures in.
7322 if (update) {
7323 Signature[] total = new Signature[addedCount+mSignatures.length];
7324 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
7325 int j = mSignatures.length;
7326 for (int i=0; i<added.length; i++) {
7327 if (added[i] != null) {
7328 total[j] = added[i];
7329 j++;
7330 }
7331 }
7332 mSignatures = total;
7333 }
7334 return true;
7335 }
7336
7337 private void assignSignatures(Signature[] sigs) {
7338 if (sigs == null) {
7339 mSignatures = null;
7340 return;
7341 }
7342 mSignatures = new Signature[sigs.length];
7343 for (int i=0; i<sigs.length; i++) {
7344 mSignatures[i] = sigs[i];
7345 }
7346 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007348 @Override
7349 public String toString() {
7350 StringBuffer buf = new StringBuffer(128);
7351 buf.append("PackageSignatures{");
7352 buf.append(Integer.toHexString(System.identityHashCode(this)));
7353 buf.append(" [");
7354 if (mSignatures != null) {
7355 for (int i=0; i<mSignatures.length; i++) {
7356 if (i > 0) buf.append(", ");
7357 buf.append(Integer.toHexString(
7358 System.identityHashCode(mSignatures[i])));
7359 }
7360 }
7361 buf.append("]}");
7362 return buf.toString();
7363 }
7364 }
7365
7366 static class PreferredActivity extends IntentFilter {
7367 final int mMatch;
7368 final String[] mSetPackages;
7369 final String[] mSetClasses;
7370 final String[] mSetComponents;
7371 final ComponentName mActivity;
7372 final String mShortActivity;
7373 String mParseError;
7374
7375 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7376 ComponentName activity) {
7377 super(filter);
7378 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7379 mActivity = activity;
7380 mShortActivity = activity.flattenToShortString();
7381 mParseError = null;
7382 if (set != null) {
7383 final int N = set.length;
7384 String[] myPackages = new String[N];
7385 String[] myClasses = new String[N];
7386 String[] myComponents = new String[N];
7387 for (int i=0; i<N; i++) {
7388 ComponentName cn = set[i];
7389 if (cn == null) {
7390 mSetPackages = null;
7391 mSetClasses = null;
7392 mSetComponents = null;
7393 return;
7394 }
7395 myPackages[i] = cn.getPackageName().intern();
7396 myClasses[i] = cn.getClassName().intern();
7397 myComponents[i] = cn.flattenToShortString().intern();
7398 }
7399 mSetPackages = myPackages;
7400 mSetClasses = myClasses;
7401 mSetComponents = myComponents;
7402 } else {
7403 mSetPackages = null;
7404 mSetClasses = null;
7405 mSetComponents = null;
7406 }
7407 }
7408
7409 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7410 IOException {
7411 mShortActivity = parser.getAttributeValue(null, "name");
7412 mActivity = ComponentName.unflattenFromString(mShortActivity);
7413 if (mActivity == null) {
7414 mParseError = "Bad activity name " + mShortActivity;
7415 }
7416 String matchStr = parser.getAttributeValue(null, "match");
7417 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7418 String setCountStr = parser.getAttributeValue(null, "set");
7419 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7420
7421 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7422 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7423 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7424
7425 int setPos = 0;
7426
7427 int outerDepth = parser.getDepth();
7428 int type;
7429 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7430 && (type != XmlPullParser.END_TAG
7431 || parser.getDepth() > outerDepth)) {
7432 if (type == XmlPullParser.END_TAG
7433 || type == XmlPullParser.TEXT) {
7434 continue;
7435 }
7436
7437 String tagName = parser.getName();
7438 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7439 // + parser.getDepth() + " tag=" + tagName);
7440 if (tagName.equals("set")) {
7441 String name = parser.getAttributeValue(null, "name");
7442 if (name == null) {
7443 if (mParseError == null) {
7444 mParseError = "No name in set tag in preferred activity "
7445 + mShortActivity;
7446 }
7447 } else if (setPos >= setCount) {
7448 if (mParseError == null) {
7449 mParseError = "Too many set tags in preferred activity "
7450 + mShortActivity;
7451 }
7452 } else {
7453 ComponentName cn = ComponentName.unflattenFromString(name);
7454 if (cn == null) {
7455 if (mParseError == null) {
7456 mParseError = "Bad set name " + name + " in preferred activity "
7457 + mShortActivity;
7458 }
7459 } else {
7460 myPackages[setPos] = cn.getPackageName();
7461 myClasses[setPos] = cn.getClassName();
7462 myComponents[setPos] = name;
7463 setPos++;
7464 }
7465 }
7466 XmlUtils.skipCurrentTag(parser);
7467 } else if (tagName.equals("filter")) {
7468 //Log.i(TAG, "Starting to parse filter...");
7469 readFromXml(parser);
7470 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7471 // + parser.getDepth() + " tag=" + parser.getName());
7472 } else {
7473 reportSettingsProblem(Log.WARN,
7474 "Unknown element under <preferred-activities>: "
7475 + parser.getName());
7476 XmlUtils.skipCurrentTag(parser);
7477 }
7478 }
7479
7480 if (setPos != setCount) {
7481 if (mParseError == null) {
7482 mParseError = "Not enough set tags (expected " + setCount
7483 + " but found " + setPos + ") in " + mShortActivity;
7484 }
7485 }
7486
7487 mSetPackages = myPackages;
7488 mSetClasses = myClasses;
7489 mSetComponents = myComponents;
7490 }
7491
7492 public void writeToXml(XmlSerializer serializer) throws IOException {
7493 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7494 serializer.attribute(null, "name", mShortActivity);
7495 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7496 serializer.attribute(null, "set", Integer.toString(NS));
7497 for (int s=0; s<NS; s++) {
7498 serializer.startTag(null, "set");
7499 serializer.attribute(null, "name", mSetComponents[s]);
7500 serializer.endTag(null, "set");
7501 }
7502 serializer.startTag(null, "filter");
7503 super.writeToXml(serializer);
7504 serializer.endTag(null, "filter");
7505 }
7506
7507 boolean sameSet(List<ResolveInfo> query, int priority) {
7508 if (mSetPackages == null) return false;
7509 final int NQ = query.size();
7510 final int NS = mSetPackages.length;
7511 int numMatch = 0;
7512 for (int i=0; i<NQ; i++) {
7513 ResolveInfo ri = query.get(i);
7514 if (ri.priority != priority) continue;
7515 ActivityInfo ai = ri.activityInfo;
7516 boolean good = false;
7517 for (int j=0; j<NS; j++) {
7518 if (mSetPackages[j].equals(ai.packageName)
7519 && mSetClasses[j].equals(ai.name)) {
7520 numMatch++;
7521 good = true;
7522 break;
7523 }
7524 }
7525 if (!good) return false;
7526 }
7527 return numMatch == NS;
7528 }
7529 }
7530
7531 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007532 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007534 HashSet<String> grantedPermissions = new HashSet<String>();
7535 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007537 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007539 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007540 setFlags(pkgFlags);
7541 }
7542
7543 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007544 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007545 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08007546 (pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) |
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08007547 (pkgFlags & ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548 }
7549 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007551 /**
7552 * Settings base class for pending and resolved classes.
7553 */
7554 static class PackageSettingBase extends GrantedPermissions {
7555 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007556 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007557 File codePath;
7558 String codePathString;
7559 File resourcePath;
7560 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007561 private long timeStamp;
7562 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007563 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007565 boolean uidError;
7566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007567 PackageSignatures signatures = new PackageSignatures();
7568
7569 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007571 /* Explicitly disabled components */
7572 HashSet<String> disabledComponents = new HashSet<String>(0);
7573 /* Explicitly enabled components */
7574 HashSet<String> enabledComponents = new HashSet<String>(0);
7575 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7576 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007577
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007578 PackageSettingBase origPackage;
7579
Jacek Surazski65e13172009-04-28 15:26:38 +02007580 /* package name of the app that installed this package */
7581 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007583 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007584 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585 super(pkgFlags);
7586 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007587 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007588 init(codePath, resourcePath, pVersionCode);
7589 }
7590
7591 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592 this.codePath = codePath;
7593 this.codePathString = codePath.toString();
7594 this.resourcePath = resourcePath;
7595 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007596 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007597 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007598
Jacek Surazski65e13172009-04-28 15:26:38 +02007599 public void setInstallerPackageName(String packageName) {
7600 installerPackageName = packageName;
7601 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007602
Jacek Surazski65e13172009-04-28 15:26:38 +02007603 String getInstallerPackageName() {
7604 return installerPackageName;
7605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007607 public void setInstallStatus(int newStatus) {
7608 installStatus = newStatus;
7609 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 public int getInstallStatus() {
7612 return installStatus;
7613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007615 public void setTimeStamp(long newStamp) {
7616 if (newStamp != timeStamp) {
7617 timeStamp = newStamp;
7618 timeStampString = Long.toString(newStamp);
7619 }
7620 }
7621
7622 public void setTimeStamp(long newStamp, String newStampStr) {
7623 timeStamp = newStamp;
7624 timeStampString = newStampStr;
7625 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627 public long getTimeStamp() {
7628 return timeStamp;
7629 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007631 public String getTimeStampStr() {
7632 return timeStampString;
7633 }
7634
7635 public void copyFrom(PackageSettingBase base) {
7636 grantedPermissions = base.grantedPermissions;
7637 gids = base.gids;
7638 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007640 timeStamp = base.timeStamp;
7641 timeStampString = base.timeStampString;
7642 signatures = base.signatures;
7643 permissionsFixed = base.permissionsFixed;
7644 disabledComponents = base.disabledComponents;
7645 enabledComponents = base.enabledComponents;
7646 enabled = base.enabled;
7647 installStatus = base.installStatus;
7648 }
7649
7650 void enableComponentLP(String componentClassName) {
7651 disabledComponents.remove(componentClassName);
7652 enabledComponents.add(componentClassName);
7653 }
7654
7655 void disableComponentLP(String componentClassName) {
7656 enabledComponents.remove(componentClassName);
7657 disabledComponents.add(componentClassName);
7658 }
7659
7660 void restoreComponentLP(String componentClassName) {
7661 enabledComponents.remove(componentClassName);
7662 disabledComponents.remove(componentClassName);
7663 }
7664
7665 int currentEnabledStateLP(String componentName) {
7666 if (enabledComponents.contains(componentName)) {
7667 return COMPONENT_ENABLED_STATE_ENABLED;
7668 } else if (disabledComponents.contains(componentName)) {
7669 return COMPONENT_ENABLED_STATE_DISABLED;
7670 } else {
7671 return COMPONENT_ENABLED_STATE_DEFAULT;
7672 }
7673 }
7674 }
7675
7676 /**
7677 * Settings data for a particular package we know about.
7678 */
7679 static final class PackageSetting extends PackageSettingBase {
7680 int userId;
7681 PackageParser.Package pkg;
7682 SharedUserSetting sharedUser;
7683
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007684 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007685 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007686 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007689 @Override
7690 public String toString() {
7691 return "PackageSetting{"
7692 + Integer.toHexString(System.identityHashCode(this))
7693 + " " + name + "/" + userId + "}";
7694 }
7695 }
7696
7697 /**
7698 * Settings data for a particular shared user ID we know about.
7699 */
7700 static final class SharedUserSetting extends GrantedPermissions {
7701 final String name;
7702 int userId;
7703 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7704 final PackageSignatures signatures = new PackageSignatures();
7705
7706 SharedUserSetting(String _name, int _pkgFlags) {
7707 super(_pkgFlags);
7708 name = _name;
7709 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007711 @Override
7712 public String toString() {
7713 return "SharedUserSetting{"
7714 + Integer.toHexString(System.identityHashCode(this))
7715 + " " + name + "/" + userId + "}";
7716 }
7717 }
7718
7719 /**
7720 * Holds information about dynamic settings.
7721 */
7722 private static final class Settings {
7723 private final File mSettingsFilename;
7724 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007725 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726 private final HashMap<String, PackageSetting> mPackages =
7727 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007728 // List of replaced system applications
7729 final HashMap<String, PackageSetting> mDisabledSysPackages =
7730 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007732 // The user's preferred activities associated with particular intent
7733 // filters.
7734 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7735 new IntentResolver<PreferredActivity, PreferredActivity>() {
7736 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007737 protected String packageForFilter(PreferredActivity filter) {
7738 return filter.mActivity.getPackageName();
7739 }
7740 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007741 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007742 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007743 out.print(prefix); out.print(
7744 Integer.toHexString(System.identityHashCode(filter)));
7745 out.print(' ');
7746 out.print(filter.mActivity.flattenToShortString());
7747 out.print(" match=0x");
7748 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007749 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007750 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007751 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007752 out.print(prefix); out.print(" ");
7753 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007754 }
7755 }
7756 }
7757 };
7758 private final HashMap<String, SharedUserSetting> mSharedUsers =
7759 new HashMap<String, SharedUserSetting>();
7760 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7761 private final SparseArray<Object> mOtherUserIds =
7762 new SparseArray<Object>();
7763
7764 // For reading/writing settings file.
7765 private final ArrayList<Signature> mPastSignatures =
7766 new ArrayList<Signature>();
7767
7768 // Mapping from permission names to info about them.
7769 final HashMap<String, BasePermission> mPermissions =
7770 new HashMap<String, BasePermission>();
7771
7772 // Mapping from permission tree names to info about them.
7773 final HashMap<String, BasePermission> mPermissionTrees =
7774 new HashMap<String, BasePermission>();
7775
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007776 // Packages that have been uninstalled and still need their external
7777 // storage data deleted.
7778 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7779
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007780 // Packages that have been renamed since they were first installed.
7781 // Keys are the new names of the packages, values are the original
7782 // names. The packages appear everwhere else under their original
7783 // names.
7784 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007786 private final StringBuilder mReadMessages = new StringBuilder();
7787
7788 private static final class PendingPackage extends PackageSettingBase {
7789 final int sharedId;
7790
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007791 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007792 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007793 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007794 this.sharedId = sharedId;
7795 }
7796 }
7797 private final ArrayList<PendingPackage> mPendingPackages
7798 = new ArrayList<PendingPackage>();
7799
7800 Settings() {
7801 File dataDir = Environment.getDataDirectory();
7802 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007803 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7804 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007806 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 FileUtils.setPermissions(systemDir.toString(),
7808 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7809 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7810 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007811 FileUtils.setPermissions(systemSecureDir.toString(),
7812 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7813 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7814 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 mSettingsFilename = new File(systemDir, "packages.xml");
7816 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007817 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 }
7819
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007820 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007821 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007822 int pkgFlags, boolean create, boolean add) {
7823 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007824 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007825 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 return p;
7827 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007828
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007829 PackageSetting peekPackageLP(String name) {
7830 return mPackages.get(name);
7831 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007832 PackageSetting p = mPackages.get(name);
7833 if (p != null && p.codePath.getPath().equals(codePath)) {
7834 return p;
7835 }
7836 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007837 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007840 void setInstallStatus(String pkgName, int status) {
7841 PackageSetting p = mPackages.get(pkgName);
7842 if(p != null) {
7843 if(p.getInstallStatus() != status) {
7844 p.setInstallStatus(status);
7845 }
7846 }
7847 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007848
Jacek Surazski65e13172009-04-28 15:26:38 +02007849 void setInstallerPackageName(String pkgName,
7850 String installerPkgName) {
7851 PackageSetting p = mPackages.get(pkgName);
7852 if(p != null) {
7853 p.setInstallerPackageName(installerPkgName);
7854 }
7855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007856
Jacek Surazski65e13172009-04-28 15:26:38 +02007857 String getInstallerPackageName(String pkgName) {
7858 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007859 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007860 }
7861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 int getInstallStatus(String pkgName) {
7863 PackageSetting p = mPackages.get(pkgName);
7864 if(p != null) {
7865 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007867 return -1;
7868 }
7869
7870 SharedUserSetting getSharedUserLP(String name,
7871 int pkgFlags, boolean create) {
7872 SharedUserSetting s = mSharedUsers.get(name);
7873 if (s == null) {
7874 if (!create) {
7875 return null;
7876 }
7877 s = new SharedUserSetting(name, pkgFlags);
7878 if (MULTIPLE_APPLICATION_UIDS) {
7879 s.userId = newUserIdLP(s);
7880 } else {
7881 s.userId = FIRST_APPLICATION_UID;
7882 }
7883 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7884 // < 0 means we couldn't assign a userid; fall out and return
7885 // s, which is currently null
7886 if (s.userId >= 0) {
7887 mSharedUsers.put(name, s);
7888 }
7889 }
7890
7891 return s;
7892 }
7893
7894 int disableSystemPackageLP(String name) {
7895 PackageSetting p = mPackages.get(name);
7896 if(p == null) {
7897 Log.w(TAG, "Package:"+name+" is not an installed package");
7898 return -1;
7899 }
7900 PackageSetting dp = mDisabledSysPackages.get(name);
7901 // always make sure the system package code and resource paths dont change
7902 if(dp == null) {
7903 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7904 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7905 }
7906 mDisabledSysPackages.put(name, p);
7907 }
7908 return removePackageLP(name);
7909 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007911 PackageSetting enableSystemPackageLP(String name) {
7912 PackageSetting p = mDisabledSysPackages.get(name);
7913 if(p == null) {
7914 Log.w(TAG, "Package:"+name+" is not disabled");
7915 return null;
7916 }
7917 // Reset flag in ApplicationInfo object
7918 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7919 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7920 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007921 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007922 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007923 mDisabledSysPackages.remove(name);
7924 return ret;
7925 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007926
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007927 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007928 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007929 PackageSetting p = mPackages.get(name);
7930 if (p != null) {
7931 if (p.userId == uid) {
7932 return p;
7933 }
7934 reportSettingsProblem(Log.ERROR,
7935 "Adding duplicate package, keeping first: " + name);
7936 return null;
7937 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007938 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007939 p.userId = uid;
7940 if (addUserIdLP(uid, p, name)) {
7941 mPackages.put(name, p);
7942 return p;
7943 }
7944 return null;
7945 }
7946
7947 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7948 SharedUserSetting s = mSharedUsers.get(name);
7949 if (s != null) {
7950 if (s.userId == uid) {
7951 return s;
7952 }
7953 reportSettingsProblem(Log.ERROR,
7954 "Adding duplicate shared user, keeping first: " + name);
7955 return null;
7956 }
7957 s = new SharedUserSetting(name, pkgFlags);
7958 s.userId = uid;
7959 if (addUserIdLP(uid, s, name)) {
7960 mSharedUsers.put(name, s);
7961 return s;
7962 }
7963 return null;
7964 }
7965
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007966 // Transfer ownership of permissions from one package to another.
7967 private void transferPermissions(String origPkg, String newPkg) {
7968 // Transfer ownership of permissions to the new package.
7969 for (int i=0; i<2; i++) {
7970 HashMap<String, BasePermission> permissions =
7971 i == 0 ? mPermissionTrees : mPermissions;
7972 for (BasePermission bp : permissions.values()) {
7973 if (origPkg.equals(bp.sourcePackage)) {
7974 if (DEBUG_UPGRADE) Log.v(TAG,
7975 "Moving permission " + bp.name
7976 + " from pkg " + bp.sourcePackage
7977 + " to " + newPkg);
7978 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007979 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007980 bp.perm = null;
7981 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007982 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007983 }
7984 bp.uid = 0;
7985 bp.gids = null;
7986 }
7987 }
7988 }
7989 }
7990
7991 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007992 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007993 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007994 PackageSetting p = mPackages.get(name);
7995 if (p != null) {
7996 if (!p.codePath.equals(codePath)) {
7997 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007998 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007999 // This is an updated system app with versions in both system
8000 // and data partition. Just let the most recent version
8001 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008002 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008003 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008004 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008005 // Just a change in the code path is not an issue, but
8006 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008007 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008008 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008009 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008010 }
8011 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008012 reportSettingsProblem(Log.WARN,
8013 "Package " + name + " shared user changed from "
8014 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8015 + " to "
8016 + (sharedUser != null ? sharedUser.name : "<nothing>")
8017 + "; replacing with new");
8018 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008019 } else {
8020 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8021 // If what we are scanning is a system package, then
8022 // make it so, regardless of whether it was previously
8023 // installed only in the data partition.
8024 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008026 }
8027 }
8028 if (p == null) {
8029 // Create a new PackageSettings entry. this can end up here because
8030 // of code path mismatch or user id mismatch of an updated system partition
8031 if (!create) {
8032 return null;
8033 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008034 if (origPackage != null) {
8035 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008036 p = new PackageSetting(origPackage.name, name, codePath,
8037 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008038 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8039 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008040 // Note that we will retain the new package's signature so
8041 // that we can keep its data.
8042 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008043 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008044 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008045 p.sharedUser = origPackage.sharedUser;
8046 p.userId = origPackage.userId;
8047 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008048 mRenamedPackages.put(name, origPackage.name);
8049 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008050 // Update new package state.
8051 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008052 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008053 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008054 p.setTimeStamp(codePath.lastModified());
8055 p.sharedUser = sharedUser;
8056 if (sharedUser != null) {
8057 p.userId = sharedUser.userId;
8058 } else if (MULTIPLE_APPLICATION_UIDS) {
8059 // Clone the setting here for disabled system packages
8060 PackageSetting dis = mDisabledSysPackages.get(name);
8061 if (dis != null) {
8062 // For disabled packages a new setting is created
8063 // from the existing user id. This still has to be
8064 // added to list of user id's
8065 // Copy signatures from previous setting
8066 if (dis.signatures.mSignatures != null) {
8067 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8068 }
8069 p.userId = dis.userId;
8070 // Clone permissions
8071 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
8072 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
8073 // Clone component info
8074 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8075 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8076 // Add new setting to list of user ids
8077 addUserIdLP(p.userId, p, name);
8078 } else {
8079 // Assign new user id
8080 p.userId = newUserIdLP(p);
8081 }
8082 } else {
8083 p.userId = FIRST_APPLICATION_UID;
8084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 }
8086 if (p.userId < 0) {
8087 reportSettingsProblem(Log.WARN,
8088 "Package " + name + " could not be assigned a valid uid");
8089 return null;
8090 }
8091 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008092 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008093 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008094 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 }
8096 }
8097 return p;
8098 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008099
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008100 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008101 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008102 String codePath = pkg.applicationInfo.sourceDir;
8103 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008104 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008105 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008106 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008107 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008108 p.codePath = new File(codePath);
8109 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008110 }
8111 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008112 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008113 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008114 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008115 p.resourcePath = new File(resourcePath);
8116 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008117 }
8118 // Update version code if needed
8119 if (pkg.mVersionCode != p.versionCode) {
8120 p.versionCode = pkg.mVersionCode;
8121 }
8122 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8123 }
8124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008125 // Utility method that adds a PackageSetting to mPackages and
8126 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008127 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008128 SharedUserSetting sharedUser) {
8129 mPackages.put(name, p);
8130 if (sharedUser != null) {
8131 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8132 reportSettingsProblem(Log.ERROR,
8133 "Package " + p.name + " was user "
8134 + p.sharedUser + " but is now " + sharedUser
8135 + "; I am not changing its files so it will probably fail!");
8136 p.sharedUser.packages.remove(p);
8137 } else if (p.userId != sharedUser.userId) {
8138 reportSettingsProblem(Log.ERROR,
8139 "Package " + p.name + " was user id " + p.userId
8140 + " but is now user " + sharedUser
8141 + " with id " + sharedUser.userId
8142 + "; I am not changing its files so it will probably fail!");
8143 }
8144
8145 sharedUser.packages.add(p);
8146 p.sharedUser = sharedUser;
8147 p.userId = sharedUser.userId;
8148 }
8149 }
8150
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008151 /*
8152 * Update the shared user setting when a package using
8153 * specifying the shared user id is removed. The gids
8154 * associated with each permission of the deleted package
8155 * are removed from the shared user's gid list only if its
8156 * not in use by other permissions of packages in the
8157 * shared user setting.
8158 */
8159 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008161 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008162 return;
8163 }
8164 // No sharedUserId
8165 if (deletedPs.sharedUser == null) {
8166 return;
8167 }
8168 SharedUserSetting sus = deletedPs.sharedUser;
8169 // Update permissions
8170 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8171 boolean used = false;
8172 if (!sus.grantedPermissions.contains (eachPerm)) {
8173 continue;
8174 }
8175 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008176 if (pkg.pkg != null &&
8177 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
8178 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008179 used = true;
8180 break;
8181 }
8182 }
8183 if (!used) {
8184 // can safely delete this permission from list
8185 sus.grantedPermissions.remove(eachPerm);
8186 sus.loadedPermissions.remove(eachPerm);
8187 }
8188 }
8189 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008190 int newGids[] = globalGids;
8191 for (String eachPerm : sus.grantedPermissions) {
8192 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008193 if (bp != null) {
8194 newGids = appendInts(newGids, bp.gids);
8195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008196 }
8197 sus.gids = newGids;
8198 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008200 private int removePackageLP(String name) {
8201 PackageSetting p = mPackages.get(name);
8202 if (p != null) {
8203 mPackages.remove(name);
8204 if (p.sharedUser != null) {
8205 p.sharedUser.packages.remove(p);
8206 if (p.sharedUser.packages.size() == 0) {
8207 mSharedUsers.remove(p.sharedUser.name);
8208 removeUserIdLP(p.sharedUser.userId);
8209 return p.sharedUser.userId;
8210 }
8211 } else {
8212 removeUserIdLP(p.userId);
8213 return p.userId;
8214 }
8215 }
8216 return -1;
8217 }
8218
8219 private boolean addUserIdLP(int uid, Object obj, Object name) {
8220 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8221 return false;
8222 }
8223
8224 if (uid >= FIRST_APPLICATION_UID) {
8225 int N = mUserIds.size();
8226 final int index = uid - FIRST_APPLICATION_UID;
8227 while (index >= N) {
8228 mUserIds.add(null);
8229 N++;
8230 }
8231 if (mUserIds.get(index) != null) {
8232 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008233 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008234 + " name=" + name);
8235 return false;
8236 }
8237 mUserIds.set(index, obj);
8238 } else {
8239 if (mOtherUserIds.get(uid) != null) {
8240 reportSettingsProblem(Log.ERROR,
8241 "Adding duplicate shared id: " + uid
8242 + " name=" + name);
8243 return false;
8244 }
8245 mOtherUserIds.put(uid, obj);
8246 }
8247 return true;
8248 }
8249
8250 public Object getUserIdLP(int uid) {
8251 if (uid >= FIRST_APPLICATION_UID) {
8252 int N = mUserIds.size();
8253 final int index = uid - FIRST_APPLICATION_UID;
8254 return index < N ? mUserIds.get(index) : null;
8255 } else {
8256 return mOtherUserIds.get(uid);
8257 }
8258 }
8259
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008260 private Set<String> findPackagesWithFlag(int flag) {
8261 Set<String> ret = new HashSet<String>();
8262 for (PackageSetting ps : mPackages.values()) {
8263 // Has to match atleast all the flag bits set on flag
8264 if ((ps.pkgFlags & flag) == flag) {
8265 ret.add(ps.name);
8266 }
8267 }
8268 return ret;
8269 }
8270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008271 private void removeUserIdLP(int uid) {
8272 if (uid >= FIRST_APPLICATION_UID) {
8273 int N = mUserIds.size();
8274 final int index = uid - FIRST_APPLICATION_UID;
8275 if (index < N) mUserIds.set(index, null);
8276 } else {
8277 mOtherUserIds.remove(uid);
8278 }
8279 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008281 void writeLP() {
8282 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8283
8284 // Keep the old settings around until we know the new ones have
8285 // been successfully written.
8286 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008287 // Presence of backup settings file indicates that we failed
8288 // to persist settings earlier. So preserve the older
8289 // backup for future reference since the current settings
8290 // might have been corrupted.
8291 if (!mBackupSettingsFilename.exists()) {
8292 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008293 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008294 return;
8295 }
8296 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008297 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008299 }
8300
8301 mPastSignatures.clear();
8302
8303 try {
8304 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8305
8306 //XmlSerializer serializer = XmlUtils.serializerInstance();
8307 XmlSerializer serializer = new FastXmlSerializer();
8308 serializer.setOutput(str, "utf-8");
8309 serializer.startDocument(null, true);
8310 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8311
8312 serializer.startTag(null, "packages");
8313
8314 serializer.startTag(null, "permission-trees");
8315 for (BasePermission bp : mPermissionTrees.values()) {
8316 writePermission(serializer, bp);
8317 }
8318 serializer.endTag(null, "permission-trees");
8319
8320 serializer.startTag(null, "permissions");
8321 for (BasePermission bp : mPermissions.values()) {
8322 writePermission(serializer, bp);
8323 }
8324 serializer.endTag(null, "permissions");
8325
8326 for (PackageSetting pkg : mPackages.values()) {
8327 writePackage(serializer, pkg);
8328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008330 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8331 writeDisabledSysPackage(serializer, pkg);
8332 }
8333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008334 serializer.startTag(null, "preferred-activities");
8335 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8336 serializer.startTag(null, "item");
8337 pa.writeToXml(serializer);
8338 serializer.endTag(null, "item");
8339 }
8340 serializer.endTag(null, "preferred-activities");
8341
8342 for (SharedUserSetting usr : mSharedUsers.values()) {
8343 serializer.startTag(null, "shared-user");
8344 serializer.attribute(null, "name", usr.name);
8345 serializer.attribute(null, "userId",
8346 Integer.toString(usr.userId));
8347 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8348 serializer.startTag(null, "perms");
8349 for (String name : usr.grantedPermissions) {
8350 serializer.startTag(null, "item");
8351 serializer.attribute(null, "name", name);
8352 serializer.endTag(null, "item");
8353 }
8354 serializer.endTag(null, "perms");
8355 serializer.endTag(null, "shared-user");
8356 }
8357
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008358 if (mPackagesToBeCleaned.size() > 0) {
8359 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8360 serializer.startTag(null, "cleaning-package");
8361 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8362 serializer.endTag(null, "cleaning-package");
8363 }
8364 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008365
8366 if (mRenamedPackages.size() > 0) {
8367 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8368 serializer.startTag(null, "renamed-package");
8369 serializer.attribute(null, "new", e.getKey());
8370 serializer.attribute(null, "old", e.getValue());
8371 serializer.endTag(null, "renamed-package");
8372 }
8373 }
8374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008375 serializer.endTag(null, "packages");
8376
8377 serializer.endDocument();
8378
8379 str.flush();
8380 str.close();
8381
8382 // New settings successfully written, old ones are no longer
8383 // needed.
8384 mBackupSettingsFilename.delete();
8385 FileUtils.setPermissions(mSettingsFilename.toString(),
8386 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8387 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8388 |FileUtils.S_IROTH,
8389 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008390
8391 // Write package list file now, use a JournaledFile.
8392 //
8393 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8394 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8395
8396 str = new FileOutputStream(journal.chooseForWrite());
8397 try {
8398 StringBuilder sb = new StringBuilder();
8399 for (PackageSetting pkg : mPackages.values()) {
8400 ApplicationInfo ai = pkg.pkg.applicationInfo;
8401 String dataPath = ai.dataDir;
8402 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8403
8404 // Avoid any application that has a space in its path
8405 // or that is handled by the system.
8406 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8407 continue;
8408
8409 // we store on each line the following information for now:
8410 //
8411 // pkgName - package name
8412 // userId - application-specific user id
8413 // debugFlag - 0 or 1 if the package is debuggable.
8414 // dataPath - path to package's data path
8415 //
8416 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8417 //
8418 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8419 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8420 // system/core/run-as/run-as.c
8421 //
8422 sb.setLength(0);
8423 sb.append(ai.packageName);
8424 sb.append(" ");
8425 sb.append((int)ai.uid);
8426 sb.append(isDebug ? " 1 " : " 0 ");
8427 sb.append(dataPath);
8428 sb.append("\n");
8429 str.write(sb.toString().getBytes());
8430 }
8431 str.flush();
8432 str.close();
8433 journal.commit();
8434 }
8435 catch (Exception e) {
8436 journal.rollback();
8437 }
8438
8439 FileUtils.setPermissions(mPackageListFilename.toString(),
8440 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8441 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8442 |FileUtils.S_IROTH,
8443 -1, -1);
8444
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008445 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008446
8447 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008448 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 -08008449 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008450 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 -08008451 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008452 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008453 if (mSettingsFilename.exists()) {
8454 if (!mSettingsFilename.delete()) {
8455 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8456 }
8457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458 //Debug.stopMethodTracing();
8459 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008460
8461 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008462 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008463 serializer.startTag(null, "updated-package");
8464 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008465 if (pkg.realName != null) {
8466 serializer.attribute(null, "realName", pkg.realName);
8467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008468 serializer.attribute(null, "codePath", pkg.codePathString);
8469 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008470 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008471 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8472 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8473 }
8474 if (pkg.sharedUser == null) {
8475 serializer.attribute(null, "userId",
8476 Integer.toString(pkg.userId));
8477 } else {
8478 serializer.attribute(null, "sharedUserId",
8479 Integer.toString(pkg.userId));
8480 }
8481 serializer.startTag(null, "perms");
8482 if (pkg.sharedUser == null) {
8483 // If this is a shared user, the permissions will
8484 // be written there. We still need to write an
8485 // empty permissions list so permissionsFixed will
8486 // be set.
8487 for (final String name : pkg.grantedPermissions) {
8488 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008489 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008490 // We only need to write signature or system permissions but this wont
8491 // match the semantics of grantedPermissions. So write all permissions.
8492 serializer.startTag(null, "item");
8493 serializer.attribute(null, "name", name);
8494 serializer.endTag(null, "item");
8495 }
8496 }
8497 }
8498 serializer.endTag(null, "perms");
8499 serializer.endTag(null, "updated-package");
8500 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008501
8502 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008503 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008504 serializer.startTag(null, "package");
8505 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008506 if (pkg.realName != null) {
8507 serializer.attribute(null, "realName", pkg.realName);
8508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008509 serializer.attribute(null, "codePath", pkg.codePathString);
8510 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8511 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8512 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008513 serializer.attribute(null, "flags",
8514 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008515 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008516 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 if (pkg.sharedUser == null) {
8518 serializer.attribute(null, "userId",
8519 Integer.toString(pkg.userId));
8520 } else {
8521 serializer.attribute(null, "sharedUserId",
8522 Integer.toString(pkg.userId));
8523 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008524 if (pkg.uidError) {
8525 serializer.attribute(null, "uidError", "true");
8526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008527 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8528 serializer.attribute(null, "enabled",
8529 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8530 ? "true" : "false");
8531 }
8532 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8533 serializer.attribute(null, "installStatus", "false");
8534 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008535 if (pkg.installerPackageName != null) {
8536 serializer.attribute(null, "installer", pkg.installerPackageName);
8537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008538 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8539 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8540 serializer.startTag(null, "perms");
8541 if (pkg.sharedUser == null) {
8542 // If this is a shared user, the permissions will
8543 // be written there. We still need to write an
8544 // empty permissions list so permissionsFixed will
8545 // be set.
8546 for (final String name : pkg.grantedPermissions) {
8547 serializer.startTag(null, "item");
8548 serializer.attribute(null, "name", name);
8549 serializer.endTag(null, "item");
8550 }
8551 }
8552 serializer.endTag(null, "perms");
8553 }
8554 if (pkg.disabledComponents.size() > 0) {
8555 serializer.startTag(null, "disabled-components");
8556 for (final String name : pkg.disabledComponents) {
8557 serializer.startTag(null, "item");
8558 serializer.attribute(null, "name", name);
8559 serializer.endTag(null, "item");
8560 }
8561 serializer.endTag(null, "disabled-components");
8562 }
8563 if (pkg.enabledComponents.size() > 0) {
8564 serializer.startTag(null, "enabled-components");
8565 for (final String name : pkg.enabledComponents) {
8566 serializer.startTag(null, "item");
8567 serializer.attribute(null, "name", name);
8568 serializer.endTag(null, "item");
8569 }
8570 serializer.endTag(null, "enabled-components");
8571 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008573 serializer.endTag(null, "package");
8574 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008576 void writePermission(XmlSerializer serializer, BasePermission bp)
8577 throws XmlPullParserException, java.io.IOException {
8578 if (bp.type != BasePermission.TYPE_BUILTIN
8579 && bp.sourcePackage != null) {
8580 serializer.startTag(null, "item");
8581 serializer.attribute(null, "name", bp.name);
8582 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008583 if (bp.protectionLevel !=
8584 PermissionInfo.PROTECTION_NORMAL) {
8585 serializer.attribute(null, "protection",
8586 Integer.toString(bp.protectionLevel));
8587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008588 if (DEBUG_SETTINGS) Log.v(TAG,
8589 "Writing perm: name=" + bp.name + " type=" + bp.type);
8590 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8591 PermissionInfo pi = bp.perm != null ? bp.perm.info
8592 : bp.pendingInfo;
8593 if (pi != null) {
8594 serializer.attribute(null, "type", "dynamic");
8595 if (pi.icon != 0) {
8596 serializer.attribute(null, "icon",
8597 Integer.toString(pi.icon));
8598 }
8599 if (pi.nonLocalizedLabel != null) {
8600 serializer.attribute(null, "label",
8601 pi.nonLocalizedLabel.toString());
8602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008603 }
8604 }
8605 serializer.endTag(null, "item");
8606 }
8607 }
8608
8609 String getReadMessagesLP() {
8610 return mReadMessages.toString();
8611 }
8612
Oscar Montemayora8529f62009-11-18 10:14:20 -08008613 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008614 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8615 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008616 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008617 while(its.hasNext()) {
8618 String key = its.next();
8619 PackageSetting ps = mPackages.get(key);
8620 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008621 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 }
8623 }
8624 return ret;
8625 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008627 boolean readLP() {
8628 FileInputStream str = null;
8629 if (mBackupSettingsFilename.exists()) {
8630 try {
8631 str = new FileInputStream(mBackupSettingsFilename);
8632 mReadMessages.append("Reading from backup settings file\n");
8633 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008634 if (mSettingsFilename.exists()) {
8635 // If both the backup and settings file exist, we
8636 // ignore the settings since it might have been
8637 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008638 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008639 mSettingsFilename.delete();
8640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 } catch (java.io.IOException e) {
8642 // We'll try for the normal settings file.
8643 }
8644 }
8645
8646 mPastSignatures.clear();
8647
8648 try {
8649 if (str == null) {
8650 if (!mSettingsFilename.exists()) {
8651 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008652 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008653 return false;
8654 }
8655 str = new FileInputStream(mSettingsFilename);
8656 }
8657 XmlPullParser parser = Xml.newPullParser();
8658 parser.setInput(str, null);
8659
8660 int type;
8661 while ((type=parser.next()) != XmlPullParser.START_TAG
8662 && type != XmlPullParser.END_DOCUMENT) {
8663 ;
8664 }
8665
8666 if (type != XmlPullParser.START_TAG) {
8667 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008668 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008669 return false;
8670 }
8671
8672 int outerDepth = parser.getDepth();
8673 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8674 && (type != XmlPullParser.END_TAG
8675 || parser.getDepth() > outerDepth)) {
8676 if (type == XmlPullParser.END_TAG
8677 || type == XmlPullParser.TEXT) {
8678 continue;
8679 }
8680
8681 String tagName = parser.getName();
8682 if (tagName.equals("package")) {
8683 readPackageLP(parser);
8684 } else if (tagName.equals("permissions")) {
8685 readPermissionsLP(mPermissions, parser);
8686 } else if (tagName.equals("permission-trees")) {
8687 readPermissionsLP(mPermissionTrees, parser);
8688 } else if (tagName.equals("shared-user")) {
8689 readSharedUserLP(parser);
8690 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008691 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008692 } else if (tagName.equals("preferred-activities")) {
8693 readPreferredActivitiesLP(parser);
8694 } else if(tagName.equals("updated-package")) {
8695 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008696 } else if (tagName.equals("cleaning-package")) {
8697 String name = parser.getAttributeValue(null, "name");
8698 if (name != null) {
8699 mPackagesToBeCleaned.add(name);
8700 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008701 } else if (tagName.equals("renamed-package")) {
8702 String nname = parser.getAttributeValue(null, "new");
8703 String oname = parser.getAttributeValue(null, "old");
8704 if (nname != null && oname != null) {
8705 mRenamedPackages.put(nname, oname);
8706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008707 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008708 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709 + parser.getName());
8710 XmlUtils.skipCurrentTag(parser);
8711 }
8712 }
8713
8714 str.close();
8715
8716 } catch(XmlPullParserException e) {
8717 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008718 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008719
8720 } catch(java.io.IOException e) {
8721 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008722 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723
8724 }
8725
8726 int N = mPendingPackages.size();
8727 for (int i=0; i<N; i++) {
8728 final PendingPackage pp = mPendingPackages.get(i);
8729 Object idObj = getUserIdLP(pp.sharedId);
8730 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008731 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008732 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008733 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008734 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008735 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008736 + pp.name);
8737 continue;
8738 }
8739 p.copyFrom(pp);
8740 } else if (idObj != null) {
8741 String msg = "Bad package setting: package " + pp.name
8742 + " has shared uid " + pp.sharedId
8743 + " that is not a shared uid\n";
8744 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008745 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008746 } else {
8747 String msg = "Bad package setting: package " + pp.name
8748 + " has shared uid " + pp.sharedId
8749 + " that is not defined\n";
8750 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008751 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008752 }
8753 }
8754 mPendingPackages.clear();
8755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008756 mReadMessages.append("Read completed successfully: "
8757 + mPackages.size() + " packages, "
8758 + mSharedUsers.size() + " shared uids\n");
8759
8760 return true;
8761 }
8762
8763 private int readInt(XmlPullParser parser, String ns, String name,
8764 int defValue) {
8765 String v = parser.getAttributeValue(ns, name);
8766 try {
8767 if (v == null) {
8768 return defValue;
8769 }
8770 return Integer.parseInt(v);
8771 } catch (NumberFormatException e) {
8772 reportSettingsProblem(Log.WARN,
8773 "Error in package manager settings: attribute " +
8774 name + " has bad integer value " + v + " at "
8775 + parser.getPositionDescription());
8776 }
8777 return defValue;
8778 }
8779
8780 private void readPermissionsLP(HashMap<String, BasePermission> out,
8781 XmlPullParser parser)
8782 throws IOException, XmlPullParserException {
8783 int outerDepth = parser.getDepth();
8784 int type;
8785 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8786 && (type != XmlPullParser.END_TAG
8787 || parser.getDepth() > outerDepth)) {
8788 if (type == XmlPullParser.END_TAG
8789 || type == XmlPullParser.TEXT) {
8790 continue;
8791 }
8792
8793 String tagName = parser.getName();
8794 if (tagName.equals("item")) {
8795 String name = parser.getAttributeValue(null, "name");
8796 String sourcePackage = parser.getAttributeValue(null, "package");
8797 String ptype = parser.getAttributeValue(null, "type");
8798 if (name != null && sourcePackage != null) {
8799 boolean dynamic = "dynamic".equals(ptype);
8800 BasePermission bp = new BasePermission(name, sourcePackage,
8801 dynamic
8802 ? BasePermission.TYPE_DYNAMIC
8803 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008804 bp.protectionLevel = readInt(parser, null, "protection",
8805 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008806 if (dynamic) {
8807 PermissionInfo pi = new PermissionInfo();
8808 pi.packageName = sourcePackage.intern();
8809 pi.name = name.intern();
8810 pi.icon = readInt(parser, null, "icon", 0);
8811 pi.nonLocalizedLabel = parser.getAttributeValue(
8812 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008813 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008814 bp.pendingInfo = pi;
8815 }
8816 out.put(bp.name, bp);
8817 } else {
8818 reportSettingsProblem(Log.WARN,
8819 "Error in package manager settings: permissions has"
8820 + " no name at " + parser.getPositionDescription());
8821 }
8822 } else {
8823 reportSettingsProblem(Log.WARN,
8824 "Unknown element reading permissions: "
8825 + parser.getName() + " at "
8826 + parser.getPositionDescription());
8827 }
8828 XmlUtils.skipCurrentTag(parser);
8829 }
8830 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008833 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008834 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008835 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008836 String codePathStr = parser.getAttributeValue(null, "codePath");
8837 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008838 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008839 resourcePathStr = codePathStr;
8840 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008841 String version = parser.getAttributeValue(null, "version");
8842 int versionCode = 0;
8843 if (version != null) {
8844 try {
8845 versionCode = Integer.parseInt(version);
8846 } catch (NumberFormatException e) {
8847 }
8848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008850 int pkgFlags = 0;
8851 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008852 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008853 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008854 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008855 String timeStampStr = parser.getAttributeValue(null, "ts");
8856 if (timeStampStr != null) {
8857 try {
8858 long timeStamp = Long.parseLong(timeStampStr);
8859 ps.setTimeStamp(timeStamp, timeStampStr);
8860 } catch (NumberFormatException e) {
8861 }
8862 }
8863 String idStr = parser.getAttributeValue(null, "userId");
8864 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8865 if(ps.userId <= 0) {
8866 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8867 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8868 }
8869 int outerDepth = parser.getDepth();
8870 int type;
8871 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8872 && (type != XmlPullParser.END_TAG
8873 || parser.getDepth() > outerDepth)) {
8874 if (type == XmlPullParser.END_TAG
8875 || type == XmlPullParser.TEXT) {
8876 continue;
8877 }
8878
8879 String tagName = parser.getName();
8880 if (tagName.equals("perms")) {
8881 readGrantedPermissionsLP(parser,
8882 ps.grantedPermissions);
8883 } else {
8884 reportSettingsProblem(Log.WARN,
8885 "Unknown element under <updated-package>: "
8886 + parser.getName());
8887 XmlUtils.skipCurrentTag(parser);
8888 }
8889 }
8890 mDisabledSysPackages.put(name, ps);
8891 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008893 private void readPackageLP(XmlPullParser parser)
8894 throws XmlPullParserException, IOException {
8895 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008896 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008897 String idStr = null;
8898 String sharedIdStr = null;
8899 String codePathStr = null;
8900 String resourcePathStr = null;
8901 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008902 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008903 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008904 int pkgFlags = 0;
8905 String timeStampStr;
8906 long timeStamp = 0;
8907 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008908 String version = null;
8909 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008910 try {
8911 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008912 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008913 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008914 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8916 codePathStr = parser.getAttributeValue(null, "codePath");
8917 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008918 version = parser.getAttributeValue(null, "version");
8919 if (version != null) {
8920 try {
8921 versionCode = Integer.parseInt(version);
8922 } catch (NumberFormatException e) {
8923 }
8924 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008925 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008926
8927 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008929 try {
8930 pkgFlags = Integer.parseInt(systemStr);
8931 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932 }
8933 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008934 // For backward compatibility
8935 systemStr = parser.getAttributeValue(null, "system");
8936 if (systemStr != null) {
8937 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8938 } else {
8939 // Old settings that don't specify system... just treat
8940 // them as system, good enough.
8941 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 }
8944 timeStampStr = parser.getAttributeValue(null, "ts");
8945 if (timeStampStr != null) {
8946 try {
8947 timeStamp = Long.parseLong(timeStampStr);
8948 } catch (NumberFormatException e) {
8949 }
8950 }
8951 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8952 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8953 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8954 if (resourcePathStr == null) {
8955 resourcePathStr = codePathStr;
8956 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008957 if (realName != null) {
8958 realName = realName.intern();
8959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 if (name == null) {
8961 reportSettingsProblem(Log.WARN,
8962 "Error in package manager settings: <package> has no name at "
8963 + parser.getPositionDescription());
8964 } else if (codePathStr == null) {
8965 reportSettingsProblem(Log.WARN,
8966 "Error in package manager settings: <package> has no codePath at "
8967 + parser.getPositionDescription());
8968 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008969 packageSetting = addPackageLP(name.intern(), realName,
8970 new File(codePathStr), new File(resourcePathStr),
8971 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008972 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8973 + ": userId=" + userId + " pkg=" + packageSetting);
8974 if (packageSetting == null) {
8975 reportSettingsProblem(Log.ERROR,
8976 "Failure adding uid " + userId
8977 + " while parsing settings at "
8978 + parser.getPositionDescription());
8979 } else {
8980 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8981 }
8982 } else if (sharedIdStr != null) {
8983 userId = sharedIdStr != null
8984 ? Integer.parseInt(sharedIdStr) : 0;
8985 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008986 packageSetting = new PendingPackage(name.intern(), realName,
8987 new File(codePathStr), new File(resourcePathStr),
8988 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008989 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8990 mPendingPackages.add((PendingPackage) packageSetting);
8991 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8992 + ": sharedUserId=" + userId + " pkg="
8993 + packageSetting);
8994 } else {
8995 reportSettingsProblem(Log.WARN,
8996 "Error in package manager settings: package "
8997 + name + " has bad sharedId " + sharedIdStr
8998 + " at " + parser.getPositionDescription());
8999 }
9000 } else {
9001 reportSettingsProblem(Log.WARN,
9002 "Error in package manager settings: package "
9003 + name + " has bad userId " + idStr + " at "
9004 + parser.getPositionDescription());
9005 }
9006 } catch (NumberFormatException e) {
9007 reportSettingsProblem(Log.WARN,
9008 "Error in package manager settings: package "
9009 + name + " has bad userId " + idStr + " at "
9010 + parser.getPositionDescription());
9011 }
9012 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009013 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009014 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009015 final String enabledStr = parser.getAttributeValue(null, "enabled");
9016 if (enabledStr != null) {
9017 if (enabledStr.equalsIgnoreCase("true")) {
9018 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9019 } else if (enabledStr.equalsIgnoreCase("false")) {
9020 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9021 } else if (enabledStr.equalsIgnoreCase("default")) {
9022 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9023 } else {
9024 reportSettingsProblem(Log.WARN,
9025 "Error in package manager settings: package "
9026 + name + " has bad enabled value: " + idStr
9027 + " at " + parser.getPositionDescription());
9028 }
9029 } else {
9030 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9031 }
9032 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9033 if (installStatusStr != null) {
9034 if (installStatusStr.equalsIgnoreCase("false")) {
9035 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9036 } else {
9037 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9038 }
9039 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009041 int outerDepth = parser.getDepth();
9042 int type;
9043 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9044 && (type != XmlPullParser.END_TAG
9045 || parser.getDepth() > outerDepth)) {
9046 if (type == XmlPullParser.END_TAG
9047 || type == XmlPullParser.TEXT) {
9048 continue;
9049 }
9050
9051 String tagName = parser.getName();
9052 if (tagName.equals("disabled-components")) {
9053 readDisabledComponentsLP(packageSetting, parser);
9054 } else if (tagName.equals("enabled-components")) {
9055 readEnabledComponentsLP(packageSetting, parser);
9056 } else if (tagName.equals("sigs")) {
9057 packageSetting.signatures.readXml(parser, mPastSignatures);
9058 } else if (tagName.equals("perms")) {
9059 readGrantedPermissionsLP(parser,
9060 packageSetting.loadedPermissions);
9061 packageSetting.permissionsFixed = true;
9062 } else {
9063 reportSettingsProblem(Log.WARN,
9064 "Unknown element under <package>: "
9065 + parser.getName());
9066 XmlUtils.skipCurrentTag(parser);
9067 }
9068 }
9069 } else {
9070 XmlUtils.skipCurrentTag(parser);
9071 }
9072 }
9073
9074 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9075 XmlPullParser parser)
9076 throws IOException, XmlPullParserException {
9077 int outerDepth = parser.getDepth();
9078 int type;
9079 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9080 && (type != XmlPullParser.END_TAG
9081 || parser.getDepth() > outerDepth)) {
9082 if (type == XmlPullParser.END_TAG
9083 || type == XmlPullParser.TEXT) {
9084 continue;
9085 }
9086
9087 String tagName = parser.getName();
9088 if (tagName.equals("item")) {
9089 String name = parser.getAttributeValue(null, "name");
9090 if (name != null) {
9091 packageSetting.disabledComponents.add(name.intern());
9092 } else {
9093 reportSettingsProblem(Log.WARN,
9094 "Error in package manager settings: <disabled-components> has"
9095 + " no name at " + parser.getPositionDescription());
9096 }
9097 } else {
9098 reportSettingsProblem(Log.WARN,
9099 "Unknown element under <disabled-components>: "
9100 + parser.getName());
9101 }
9102 XmlUtils.skipCurrentTag(parser);
9103 }
9104 }
9105
9106 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9107 XmlPullParser parser)
9108 throws IOException, XmlPullParserException {
9109 int outerDepth = parser.getDepth();
9110 int type;
9111 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9112 && (type != XmlPullParser.END_TAG
9113 || parser.getDepth() > outerDepth)) {
9114 if (type == XmlPullParser.END_TAG
9115 || type == XmlPullParser.TEXT) {
9116 continue;
9117 }
9118
9119 String tagName = parser.getName();
9120 if (tagName.equals("item")) {
9121 String name = parser.getAttributeValue(null, "name");
9122 if (name != null) {
9123 packageSetting.enabledComponents.add(name.intern());
9124 } else {
9125 reportSettingsProblem(Log.WARN,
9126 "Error in package manager settings: <enabled-components> has"
9127 + " no name at " + parser.getPositionDescription());
9128 }
9129 } else {
9130 reportSettingsProblem(Log.WARN,
9131 "Unknown element under <enabled-components>: "
9132 + parser.getName());
9133 }
9134 XmlUtils.skipCurrentTag(parser);
9135 }
9136 }
9137
9138 private void readSharedUserLP(XmlPullParser parser)
9139 throws XmlPullParserException, IOException {
9140 String name = null;
9141 String idStr = null;
9142 int pkgFlags = 0;
9143 SharedUserSetting su = null;
9144 try {
9145 name = parser.getAttributeValue(null, "name");
9146 idStr = parser.getAttributeValue(null, "userId");
9147 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9148 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9149 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9150 }
9151 if (name == null) {
9152 reportSettingsProblem(Log.WARN,
9153 "Error in package manager settings: <shared-user> has no name at "
9154 + parser.getPositionDescription());
9155 } else if (userId == 0) {
9156 reportSettingsProblem(Log.WARN,
9157 "Error in package manager settings: shared-user "
9158 + name + " has bad userId " + idStr + " at "
9159 + parser.getPositionDescription());
9160 } else {
9161 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9162 reportSettingsProblem(Log.ERROR,
9163 "Occurred while parsing settings at "
9164 + parser.getPositionDescription());
9165 }
9166 }
9167 } catch (NumberFormatException e) {
9168 reportSettingsProblem(Log.WARN,
9169 "Error in package manager settings: package "
9170 + name + " has bad userId " + idStr + " at "
9171 + parser.getPositionDescription());
9172 };
9173
9174 if (su != null) {
9175 int outerDepth = parser.getDepth();
9176 int type;
9177 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9178 && (type != XmlPullParser.END_TAG
9179 || parser.getDepth() > outerDepth)) {
9180 if (type == XmlPullParser.END_TAG
9181 || type == XmlPullParser.TEXT) {
9182 continue;
9183 }
9184
9185 String tagName = parser.getName();
9186 if (tagName.equals("sigs")) {
9187 su.signatures.readXml(parser, mPastSignatures);
9188 } else if (tagName.equals("perms")) {
9189 readGrantedPermissionsLP(parser, su.loadedPermissions);
9190 } else {
9191 reportSettingsProblem(Log.WARN,
9192 "Unknown element under <shared-user>: "
9193 + parser.getName());
9194 XmlUtils.skipCurrentTag(parser);
9195 }
9196 }
9197
9198 } else {
9199 XmlUtils.skipCurrentTag(parser);
9200 }
9201 }
9202
9203 private void readGrantedPermissionsLP(XmlPullParser parser,
9204 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9205 int outerDepth = parser.getDepth();
9206 int type;
9207 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9208 && (type != XmlPullParser.END_TAG
9209 || parser.getDepth() > outerDepth)) {
9210 if (type == XmlPullParser.END_TAG
9211 || type == XmlPullParser.TEXT) {
9212 continue;
9213 }
9214
9215 String tagName = parser.getName();
9216 if (tagName.equals("item")) {
9217 String name = parser.getAttributeValue(null, "name");
9218 if (name != null) {
9219 outPerms.add(name.intern());
9220 } else {
9221 reportSettingsProblem(Log.WARN,
9222 "Error in package manager settings: <perms> has"
9223 + " no name at " + parser.getPositionDescription());
9224 }
9225 } else {
9226 reportSettingsProblem(Log.WARN,
9227 "Unknown element under <perms>: "
9228 + parser.getName());
9229 }
9230 XmlUtils.skipCurrentTag(parser);
9231 }
9232 }
9233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009234 private void readPreferredActivitiesLP(XmlPullParser parser)
9235 throws XmlPullParserException, IOException {
9236 int outerDepth = parser.getDepth();
9237 int type;
9238 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9239 && (type != XmlPullParser.END_TAG
9240 || parser.getDepth() > outerDepth)) {
9241 if (type == XmlPullParser.END_TAG
9242 || type == XmlPullParser.TEXT) {
9243 continue;
9244 }
9245
9246 String tagName = parser.getName();
9247 if (tagName.equals("item")) {
9248 PreferredActivity pa = new PreferredActivity(parser);
9249 if (pa.mParseError == null) {
9250 mPreferredActivities.addFilter(pa);
9251 } else {
9252 reportSettingsProblem(Log.WARN,
9253 "Error in package manager settings: <preferred-activity> "
9254 + pa.mParseError + " at "
9255 + parser.getPositionDescription());
9256 }
9257 } else {
9258 reportSettingsProblem(Log.WARN,
9259 "Unknown element under <preferred-activities>: "
9260 + parser.getName());
9261 XmlUtils.skipCurrentTag(parser);
9262 }
9263 }
9264 }
9265
9266 // Returns -1 if we could not find an available UserId to assign
9267 private int newUserIdLP(Object obj) {
9268 // Let's be stupidly inefficient for now...
9269 final int N = mUserIds.size();
9270 for (int i=0; i<N; i++) {
9271 if (mUserIds.get(i) == null) {
9272 mUserIds.set(i, obj);
9273 return FIRST_APPLICATION_UID + i;
9274 }
9275 }
9276
9277 // None left?
9278 if (N >= MAX_APPLICATION_UIDS) {
9279 return -1;
9280 }
9281
9282 mUserIds.add(obj);
9283 return FIRST_APPLICATION_UID + N;
9284 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009286 public PackageSetting getDisabledSystemPkg(String name) {
9287 synchronized(mPackages) {
9288 PackageSetting ps = mDisabledSysPackages.get(name);
9289 return ps;
9290 }
9291 }
9292
9293 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9294 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9295 if (Config.LOGV) {
9296 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9297 + " componentName = " + componentInfo.name);
9298 Log.v(TAG, "enabledComponents: "
9299 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9300 Log.v(TAG, "disabledComponents: "
9301 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9302 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009303 if (packageSettings == null) {
9304 if (false) {
9305 Log.w(TAG, "WAITING FOR DEBUGGER");
9306 Debug.waitForDebugger();
9307 Log.i(TAG, "We will crash!");
9308 }
9309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009310 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9311 || ((componentInfo.enabled
9312 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9313 || (componentInfo.applicationInfo.enabled
9314 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9315 && !packageSettings.disabledComponents.contains(componentInfo.name))
9316 || packageSettings.enabledComponents.contains(componentInfo.name));
9317 }
9318 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009319
9320 // ------- apps on sdcard specific code -------
9321 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009322 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009323 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009324 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009325 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009326
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009327 private String getEncryptKey() {
9328 try {
9329 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9330 if (sdEncKey == null) {
9331 sdEncKey = SystemKeyStore.getInstance().
9332 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9333 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009334 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009335 return null;
9336 }
9337 }
9338 return sdEncKey;
9339 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009340 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009341 return null;
9342 }
9343 }
9344
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009345 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009346 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009347 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009348 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009349 if (list != null) {
9350 int idx = 0;
9351 int idList[] = new int[MAX_CONTAINERS];
9352 boolean neverFound = true;
9353 for (String name : list) {
9354 // Ignore null entries
9355 if (name == null) {
9356 continue;
9357 }
9358 int sidx = name.indexOf(prefix);
9359 if (sidx == -1) {
9360 // Not a temp file. just ignore
9361 continue;
9362 }
9363 String subStr = name.substring(sidx + prefix.length());
9364 idList[idx] = -1;
9365 if (subStr != null) {
9366 try {
9367 int cid = Integer.parseInt(subStr);
9368 idList[idx++] = cid;
9369 neverFound = false;
9370 } catch (NumberFormatException e) {
9371 }
9372 }
9373 }
9374 if (!neverFound) {
9375 // Sort idList
9376 Arrays.sort(idList);
9377 for (int j = 1; j <= idList.length; j++) {
9378 if (idList[j-1] != j) {
9379 tmpIdx = j;
9380 break;
9381 }
9382 }
9383 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009384 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009385 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009386 }
9387
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009388 /*
9389 * Return true if PackageManager does have packages to be updated.
9390 */
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009391 public boolean updateExternalMediaStatus(final boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009392 final boolean ret;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009393 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009394 Log.i(TAG, "Updating external media status from " +
9395 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9396 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009397 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9398 mediaStatus+", mMediaMounted=" + mMediaMounted);
9399 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009400 return false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009401 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009402 mMediaMounted = mediaStatus;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009403 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_EXTERNAL_STORAGE);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009404 ret = appList != null && appList.size() > 0;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009405 if (DEBUG_SD_INSTALL) {
9406 if (appList != null) {
9407 for (String app : appList) {
9408 Log.i(TAG, "Should enable " + app + " on sdcard");
9409 }
9410 }
9411 }
9412 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus returning " + ret);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009413 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009414 // Queue up an async operation since the package installation may take a little while.
9415 mHandler.post(new Runnable() {
9416 public void run() {
9417 mHandler.removeCallbacks(this);
9418 updateExternalMediaStatusInner(mediaStatus, ret);
9419 }
9420 });
9421 return ret;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009422 }
9423
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009424 private void updateExternalMediaStatusInner(boolean mediaStatus,
9425 boolean sendUpdateBroadcast) {
9426 // If we are up here that means there are packages to be
9427 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009428 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009429 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009430 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009431 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009432 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009433
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009434 int uidList[] = new int[list.length];
9435 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009436 HashSet<String> removeCids = new HashSet<String>();
9437 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009438 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009439 for (String cid : list) {
9440 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009441 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9442 boolean failed = true;
9443 try {
9444 String pkgName = args.getPackageName();
9445 if (pkgName == null) {
9446 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009447 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009448 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9449 PackageSetting ps = mSettings.mPackages.get(pkgName);
9450 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009451 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009452 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9453 " corresponds to pkg : " + pkgName +
9454 " at code path: " + ps.codePathString);
9455 // We do have a valid package installed on sdcard
9456 processCids.put(args, ps.codePathString);
9457 failed = false;
9458 int uid = ps.userId;
9459 if (uid != -1) {
9460 uidList[num++] = uid;
9461 }
9462 }
9463 } finally {
9464 if (failed) {
9465 // Stale container on sdcard. Just delete
9466 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9467 removeCids.add(cid);
9468 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009469 }
9470 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009471 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009472 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009473 int uidArr[] = null;
9474 if (num > 0) {
9475 // Sort uid list
9476 Arrays.sort(uidList, 0, num);
9477 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009478 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009479 uidArr[0] = uidList[0];
9480 int di = 0;
9481 for (int i = 1; i < num; i++) {
9482 if (uidList[i-1] != uidList[i]) {
9483 uidArr[di++] = uidList[i];
9484 }
9485 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009486 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009487 // Process packages with valid entries.
9488 if (mediaStatus) {
9489 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
9490 loadMediaPackages(processCids, uidArr, sendUpdateBroadcast, removeCids);
9491 startCleaningPackages();
9492 } else {
9493 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
9494 unloadMediaPackages(processCids, uidArr, sendUpdateBroadcast);
9495 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009496 }
9497
9498 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9499 ArrayList<String> pkgList, int uidArr[]) {
9500 int size = pkgList.size();
9501 if (size > 0) {
9502 // Send broadcasts here
9503 Bundle extras = new Bundle();
9504 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9505 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009506 if (uidArr != null) {
9507 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9508 }
9509 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9510 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009511 sendPackageBroadcast(action, null, extras);
9512 }
9513 }
9514
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009515 /*
9516 * Look at potentially valid container ids from processCids
9517 * If package information doesn't match the one on record
9518 * or package scanning fails, the cid is added to list of
9519 * removeCids and cleaned up. Since cleaning up containers
9520 * involves destroying them, we do not want any parse
9521 * references to such stale containers. So force gc's
9522 * to avoid unnecessary crashes.
9523 */
9524 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9525 int uidArr[], boolean sendUpdateBroadcast,
9526 HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009527 ArrayList<String> pkgList = new ArrayList<String>();
9528 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009529 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009530 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009531 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009532 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9533 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009534 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009535 try {
9536 // Make sure there are no container errors first.
9537 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9538 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009539 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009540 " when installing from sdcard");
9541 continue;
9542 }
9543 // Check code path here.
9544 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009545 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009546 " does not match one in settings " + codePath);
9547 continue;
9548 }
9549 // Parse package
9550 int parseFlags = PackageParser.PARSE_CHATTY |
9551 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9552 PackageParser pp = new PackageParser(codePath);
9553 pp.setSeparateProcesses(mSeparateProcesses);
9554 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9555 codePath, mMetrics, parseFlags);
9556 pp = null;
9557 doGc = true;
9558 // Check for parse errors
9559 if (pkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009560 Slog.e(TAG, "Parse error when installing install pkg : "
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009561 + args.cid + " from " + args.cachePath);
9562 continue;
9563 }
9564 setApplicationInfoPaths(pkg, codePath, codePath);
9565 synchronized (mInstallLock) {
9566 // Scan the package
9567 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9568 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009569 retCode = PackageManager.INSTALL_SUCCEEDED;
9570 pkgList.add(pkg.packageName);
9571 // Post process args
9572 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9573 }
9574 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009575 Slog.i(TAG, "Failed to install pkg: " +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009576 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009577 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009578 }
9579
9580 } finally {
9581 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9582 // Don't destroy container here. Wait till gc clears things up.
9583 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009584 }
9585 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009586 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009587 synchronized (mPackages) {
9588 // Persist settings
9589 mSettings.writeLP();
9590 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009591 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009592 if (sendUpdateBroadcast) {
9593 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9594 }
9595 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009596 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009597 }
9598 // Delete any stale containers if needed.
9599 if (removeCids != null) {
9600 for (String cid : removeCids) {
9601 Log.i(TAG, "Destroying stale container : " + cid);
9602 PackageHelper.destroySdDir(cid);
9603 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009604 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009605 }
9606
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009607 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9608 int uidArr[], boolean sendUpdateBroadcast) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009609 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009610 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009611 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009612 Set<SdInstallArgs> keys = processCids.keySet();
9613 for (SdInstallArgs args : keys) {
9614 String cid = args.cid;
9615 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009616 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009617 // Delete package internally
9618 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9619 synchronized (mInstallLock) {
9620 boolean res = deletePackageLI(pkgName, false,
9621 PackageManager.DONT_DELETE_DATA, outInfo);
9622 if (res) {
9623 pkgList.add(pkgName);
9624 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009625 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009626 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009627 }
9628 }
9629 }
9630 // Send broadcasts
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009631 if (sendUpdateBroadcast) {
9632 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009633 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009634 // Force gc
9635 Runtime.getRuntime().gc();
9636 // Just unmount all valid containers.
9637 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009638 synchronized (mInstallLock) {
9639 args.doPostDeleteLI(false);
9640 }
9641 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009642 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009643
9644 public void movePackage(final String packageName,
9645 final IPackageMoveObserver observer, final int flags) {
9646 if (packageName == null) {
9647 return;
9648 }
9649 mContext.enforceCallingOrSelfPermission(
9650 android.Manifest.permission.MOVE_PACKAGE, null);
9651 int returnCode = PackageManager.MOVE_SUCCEEDED;
9652 int currFlags = 0;
9653 int newFlags = 0;
9654 synchronized (mPackages) {
9655 PackageParser.Package pkg = mPackages.get(packageName);
9656 if (pkg == null) {
9657 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9658 }
9659 // Disable moving fwd locked apps and system packages
9660 if (pkg.applicationInfo != null &&
9661 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009662 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009663 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9664 } else if (pkg.applicationInfo != null &&
9665 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009666 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009667 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9668 } else {
9669 // Find install location first
9670 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9671 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009672 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009673 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9674 } else {
9675 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9676 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009677 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009678 PackageManager.INSTALL_EXTERNAL : 0;
9679 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009680 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009681 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9682 }
9683 }
9684 }
9685 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9686 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9687 } else {
9688 Message msg = mHandler.obtainMessage(INIT_COPY);
9689 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9690 pkg.applicationInfo.publicSourceDir);
9691 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9692 packageName);
9693 msg.obj = mp;
9694 mHandler.sendMessage(msg);
9695 }
9696 }
9697 }
9698
9699 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9700 // Queue up an async operation since the package deletion may take a little while.
9701 mHandler.post(new Runnable() {
9702 public void run() {
9703 mHandler.removeCallbacks(this);
9704 int returnCode = currentStatus;
9705 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9706 if (moveSucceeded) {
9707 int uid = -1;
9708 synchronized (mPackages) {
9709 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9710 }
9711 ArrayList<String> pkgList = new ArrayList<String>();
9712 pkgList.add(mp.packageName);
9713 int uidArr[] = new int[] { uid };
9714 // Send resources unavailable broadcast
9715 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9716
9717 // Update package code and resource paths
9718 synchronized (mPackages) {
9719 PackageParser.Package pkg = mPackages.get(mp.packageName);
9720 if (pkg != null) {
9721 String oldCodePath = pkg.mPath;
9722 String newCodePath = mp.targetArgs.getCodePath();
9723 String newResPath = mp.targetArgs.getResourcePath();
9724 pkg.mPath = newCodePath;
9725 // Move dex files around
9726 if (moveDexFiles(pkg)
9727 != PackageManager.INSTALL_SUCCEEDED) {
9728 // Moving of dex files failed. Set
9729 // error code and abort move.
9730 pkg.mPath = pkg.mScanPath;
9731 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9732 moveSucceeded = false;
9733 } else {
9734 pkg.mScanPath = newCodePath;
9735 pkg.applicationInfo.sourceDir = newCodePath;
9736 pkg.applicationInfo.publicSourceDir = newResPath;
9737 PackageSetting ps = (PackageSetting) pkg.mExtras;
9738 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9739 ps.codePathString = ps.codePath.getPath();
9740 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9741 ps.resourcePathString = ps.resourcePath.getPath();
9742 // Set the application info flag correctly.
9743 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009744 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009745 } else {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009746 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009747 }
9748 ps.setFlags(pkg.applicationInfo.flags);
9749 mAppDirs.remove(oldCodePath);
9750 mAppDirs.put(newCodePath, pkg);
9751 // Persist settings
9752 mSettings.writeLP();
9753 }
9754 }
9755 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009756 // Send resources available broadcast
9757 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009758 }
9759 if (!moveSucceeded){
9760 // Clean up failed installation
9761 if (mp.targetArgs != null) {
9762 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009763 returnCode);
9764 }
9765 } else {
9766 // Force a gc to clear things up.
9767 Runtime.getRuntime().gc();
9768 // Delete older code
9769 synchronized (mInstallLock) {
9770 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009771 }
9772 }
9773 IPackageMoveObserver observer = mp.observer;
9774 if (observer != null) {
9775 try {
9776 observer.packageMoved(mp.packageName, returnCode);
9777 } catch (RemoteException e) {
9778 Log.i(TAG, "Observer no longer exists.");
9779 }
9780 }
9781 }
9782 });
9783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009784}