blob: 9eb63a65d419c690cf963e5eb7d6384e85da409c [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;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070023import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080024import com.android.internal.util.XmlUtils;
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;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700346 static final int UPDATED_MEDIA_STATUS = 12;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800347
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700348 // Delay time in millisecs
349 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800350 final private DefaultContainerConnection mDefContainerConn =
351 new DefaultContainerConnection();
352 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800353 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800354 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800355 IMediaContainerService imcs =
356 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800357 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800358 }
359
360 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800361 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800362 }
363 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700364
Christopher Tate1bb69062010-02-19 17:02:12 -0800365 // Recordkeeping of restore-after-install operations that are currently in flight
366 // between the Package Manager and the Backup Manager
367 class PostInstallData {
368 public InstallArgs args;
369 public PackageInstalledInfo res;
370
371 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
372 args = _a;
373 res = _r;
374 }
375 };
376 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
377 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
378
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700379 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800380 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800381 final ArrayList<HandlerParams> mPendingInstalls =
382 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800383
384 private boolean connectToService() {
385 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
386 " DefaultContainerService");
387 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
388 if (mContext.bindService(service, mDefContainerConn,
389 Context.BIND_AUTO_CREATE)) {
390 mBound = true;
391 return true;
392 }
393 return false;
394 }
395
396 private void disconnectService() {
397 mContainerService = null;
398 mBound = false;
399 mContext.unbindService(mDefContainerConn);
400 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800401
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700402 PackageHandler(Looper looper) {
403 super(looper);
404 }
405 public void handleMessage(Message msg) {
406 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800407 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800408 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800409 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800410 int idx = mPendingInstalls.size();
411 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
412 // If a bind was already initiated we dont really
413 // need to do anything. The pending install
414 // will be processed later on.
415 if (!mBound) {
416 // If this is the only one pending we might
417 // have to bind to the service again.
418 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800419 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800420 params.serviceError();
421 return;
422 } else {
423 // Once we bind to the service, the first
424 // pending request will be processed.
425 mPendingInstalls.add(idx, params);
426 }
427 } else {
428 mPendingInstalls.add(idx, params);
429 // Already bound to the service. Just make
430 // sure we trigger off processing the first request.
431 if (idx == 0) {
432 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800433 }
434 }
435 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800436 }
437 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800438 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800439 if (msg.obj != null) {
440 mContainerService = (IMediaContainerService) msg.obj;
441 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800442 if (mContainerService == null) {
443 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800444 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800445 for (HandlerParams params : mPendingInstalls) {
446 mPendingInstalls.remove(0);
447 // Indicate service bind error
448 params.serviceError();
449 }
450 mPendingInstalls.clear();
451 } else if (mPendingInstalls.size() > 0) {
452 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800453 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800454 params.startCopy();
455 }
456 } else {
457 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800458 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800459 }
460 break;
461 }
462 case MCS_RECONNECT : {
463 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
464 if (mPendingInstalls.size() > 0) {
465 if (mBound) {
466 disconnectService();
467 }
468 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800469 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 for (HandlerParams params : mPendingInstalls) {
471 mPendingInstalls.remove(0);
472 // Indicate service bind error
473 params.serviceError();
474 }
475 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800476 }
477 }
478 break;
479 }
480 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800481 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
482 // Delete pending install
483 if (mPendingInstalls.size() > 0) {
484 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800485 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800486 if (mPendingInstalls.size() == 0) {
487 if (mBound) {
488 disconnectService();
489 }
490 } else {
491 // There are more pending requests in queue.
492 // Just post MCS_BOUND message to trigger processing
493 // of next pending install.
494 mHandler.sendEmptyMessage(MCS_BOUND);
495 }
496 break;
497 }
498 case MCS_GIVE_UP: {
499 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
500 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800501 break;
502 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700503 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800504 String packages[];
505 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700506 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700507 int uids[];
508 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800509 if (mPendingBroadcasts == null) {
510 return;
511 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700512 size = mPendingBroadcasts.size();
513 if (size <= 0) {
514 // Nothing to be done. Just return
515 return;
516 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800517 packages = new String[size];
518 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700519 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800520 Iterator<HashMap.Entry<String, ArrayList<String>>>
521 it = mPendingBroadcasts.entrySet().iterator();
522 int i = 0;
523 while (it.hasNext() && i < size) {
524 HashMap.Entry<String, ArrayList<String>> ent = it.next();
525 packages[i] = ent.getKey();
526 components[i] = ent.getValue();
527 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700528 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800529 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700530 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800531 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700532 mPendingBroadcasts.clear();
533 }
534 // Send broadcasts
535 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800536 sendPackageChangedBroadcast(packages[i], true,
537 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700538 }
539 break;
540 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800541 case START_CLEANING_PACKAGE: {
542 String packageName = (String)msg.obj;
543 synchronized (mPackages) {
544 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
545 mSettings.mPackagesToBeCleaned.add(packageName);
546 }
547 }
548 startCleaningPackages();
549 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800550 case POST_INSTALL: {
551 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
552 PostInstallData data = mRunningInstalls.get(msg.arg1);
553 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800554 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800555
556 if (data != null) {
557 InstallArgs args = data.args;
558 PackageInstalledInfo res = data.res;
559
560 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
561 res.removedInfo.sendBroadcast(false, true);
562 Bundle extras = new Bundle(1);
563 extras.putInt(Intent.EXTRA_UID, res.uid);
564 final boolean update = res.removedInfo.removedPackage != null;
565 if (update) {
566 extras.putBoolean(Intent.EXTRA_REPLACING, true);
567 }
568 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
569 res.pkg.applicationInfo.packageName,
570 extras);
571 if (update) {
572 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
573 res.pkg.applicationInfo.packageName,
574 extras);
575 }
576 if (res.removedInfo.args != null) {
577 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800578 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800579 }
580 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800581 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800582 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800583 // We delete after a gc for applications on sdcard.
584 if (deleteOld) {
585 synchronized (mInstallLock) {
586 res.removedInfo.args.doPostDeleteLI(true);
587 }
588 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800589 if (args.observer != null) {
590 try {
591 args.observer.packageInstalled(res.name, res.returnCode);
592 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800593 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800594 }
595 }
596 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800597 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800598 }
599 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700600 case UPDATED_MEDIA_STATUS: {
601 try {
602 PackageHelper.getMountService().finishMediaUpdate();
603 } catch (RemoteException e) {
604 Log.e(TAG, "MountService not running?");
605 }
606 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700607 }
608 }
609 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800610
611 static boolean installOnSd(int flags) {
612 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700613 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800614 return false;
615 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700616 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
617 return true;
618 }
619 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800620 }
621
622 static boolean isFwdLocked(int flags) {
623 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
624 return true;
625 }
626 return false;
627 }
628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 public static final IPackageManager main(Context context, boolean factoryTest) {
630 PackageManagerService m = new PackageManagerService(context, factoryTest);
631 ServiceManager.addService("package", m);
632 return m;
633 }
634
635 static String[] splitString(String str, char sep) {
636 int count = 1;
637 int i = 0;
638 while ((i=str.indexOf(sep, i)) >= 0) {
639 count++;
640 i++;
641 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 String[] res = new String[count];
644 i=0;
645 count = 0;
646 int lastI=0;
647 while ((i=str.indexOf(sep, i)) >= 0) {
648 res[count] = str.substring(lastI, i);
649 count++;
650 i++;
651 lastI = i;
652 }
653 res[count] = str.substring(lastI, str.length());
654 return res;
655 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800658 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800662 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 mContext = context;
666 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700667 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 mMetrics = new DisplayMetrics();
669 mSettings = new Settings();
670 mSettings.addSharedUserLP("android.uid.system",
671 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
672 mSettings.addSharedUserLP("android.uid.phone",
673 MULTIPLE_APPLICATION_UIDS
674 ? RADIO_UID : FIRST_APPLICATION_UID,
675 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400676 mSettings.addSharedUserLP("android.uid.log",
677 MULTIPLE_APPLICATION_UIDS
678 ? LOG_UID : FIRST_APPLICATION_UID,
679 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680
681 String separateProcesses = SystemProperties.get("debug.separate_processes");
682 if (separateProcesses != null && separateProcesses.length() > 0) {
683 if ("*".equals(separateProcesses)) {
684 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
685 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800686 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 } else {
688 mDefParseFlags = 0;
689 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800690 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 + separateProcesses);
692 }
693 } else {
694 mDefParseFlags = 0;
695 mSeparateProcesses = null;
696 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 Installer installer = new Installer();
699 // Little hacky thing to check if installd is here, to determine
700 // whether we are running on the simulator and thus need to take
701 // care of building the /data file structure ourself.
702 // (apparently the sim now has a working installer)
703 if (installer.ping() && Process.supportsProcesses()) {
704 mInstaller = installer;
705 } else {
706 mInstaller = null;
707 }
708
709 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
710 Display d = wm.getDefaultDisplay();
711 d.getMetrics(mMetrics);
712
713 synchronized (mInstallLock) {
714 synchronized (mPackages) {
715 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700716 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 File dataDir = Environment.getDataDirectory();
719 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800720 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
722
723 if (mInstaller == null) {
724 // Make sure these dirs exist, when we are running in
725 // the simulator.
726 // Make a wide-open directory for random misc stuff.
727 File miscDir = new File(dataDir, "misc");
728 miscDir.mkdirs();
729 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800730 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 mDrmAppPrivateInstallDir.mkdirs();
732 }
733
734 readPermissions();
735
736 mRestoredSettings = mSettings.readLP();
737 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800738
739 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800741
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800742 // Set flag to monitor and not change apk file paths when
743 // scanning install directories.
744 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700745 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800746 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800747 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700748 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700753 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700756 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 /**
759 * Out of paranoia, ensure that everything in the boot class
760 * path has been dexed.
761 */
762 String bootClassPath = System.getProperty("java.boot.class.path");
763 if (bootClassPath != null) {
764 String[] paths = splitString(bootClassPath, ':');
765 for (int i=0; i<paths.length; i++) {
766 try {
767 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
768 libFiles.add(paths[i]);
769 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700770 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 }
772 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800773 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800775 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 }
777 }
778 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800779 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 /**
783 * Also ensure all external libraries have had dexopt run on them.
784 */
785 if (mSharedLibraries.size() > 0) {
786 Iterator<String> libs = mSharedLibraries.values().iterator();
787 while (libs.hasNext()) {
788 String lib = libs.next();
789 try {
790 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
791 libFiles.add(lib);
792 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700793 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 }
795 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800796 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800798 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 }
800 }
801 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 // Gross hack for now: we know this file doesn't contain any
804 // code, so don't dexopt it to avoid the resulting log spew.
805 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 /**
808 * And there are a number of commands implemented in Java, which
809 * we currently need to do the dexopt on so that they can be
810 * run from a non-root shell.
811 */
812 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700813 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 for (int i=0; i<frameworkFiles.length; i++) {
815 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
816 String path = libPath.getPath();
817 // Skip the file if we alrady did it.
818 if (libFiles.contains(path)) {
819 continue;
820 }
821 // Skip the file if it is not a type we want to dexopt.
822 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
823 continue;
824 }
825 try {
826 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
827 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700828 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 }
830 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800831 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800833 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
835 }
836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800837
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700838 if (didDexOpt) {
839 // If we had to do a dexopt of one of the previous
840 // things, then something on the system has changed.
841 // Consider this significant, and wipe away all other
842 // existing dexopt files to ensure we don't leave any
843 // dangling around.
844 String[] files = mDalvikCacheDir.list();
845 if (files != null) {
846 for (int i=0; i<files.length; i++) {
847 String fn = files[i];
848 if (fn.startsWith("data@app@")
849 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800850 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700851 (new File(mDalvikCacheDir, fn)).delete();
852 }
853 }
854 }
855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800857
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800858 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 mFrameworkInstallObserver = new AppDirObserver(
860 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
861 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700862 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
863 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800864 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800865
866 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
868 mSystemInstallObserver = new AppDirObserver(
869 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
870 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700871 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
872 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800873
874 if (mInstaller != null) {
875 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
876 mInstaller.moveFiles();
877 }
878
879 // Prune any system packages that no longer exist.
880 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
881 while (psit.hasNext()) {
882 PackageSetting ps = psit.next();
883 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800884 && !mPackages.containsKey(ps.name)
885 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800886 psit.remove();
887 String msg = "System package " + ps.name
888 + " no longer exists; wiping its data";
889 reportSettingsProblem(Log.WARN, msg);
890 if (mInstaller != null) {
891 // XXX how to set useEncryptedFSDir for packages that
892 // are not encrypted?
893 mInstaller.remove(ps.name, true);
894 }
895 }
896 }
897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 mAppInstallDir = new File(dataDir, "app");
899 if (mInstaller == null) {
900 // Make sure these dirs exist, when we are running in
901 // the simulator.
902 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
903 }
904 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800905 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 //clean up list
907 for(int i = 0; i < deletePkgsList.size(); i++) {
908 //clean up here
909 cleanupInstallFailedPackage(deletePkgsList.get(i));
910 }
911 //delete tmp files
912 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800913
914 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 SystemClock.uptimeMillis());
916 mAppInstallObserver = new AppDirObserver(
917 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
918 mAppInstallObserver.startWatching();
919 scanDirLI(mAppInstallDir, 0, scanMode);
920
921 mDrmAppInstallObserver = new AppDirObserver(
922 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
923 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800924 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800926 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800928 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 + ((SystemClock.uptimeMillis()-startTime)/1000f)
930 + " seconds");
931
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700932 updatePermissionsLP(null, null, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933
934 mSettings.writeLP();
935
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800936 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 // Now after opening every single application zip, make sure they
940 // are all flushed. Not really needed, but keeps things nice and
941 // tidy.
942 Runtime.getRuntime().gc();
943 } // synchronized (mPackages)
944 } // synchronized (mInstallLock)
945 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 @Override
948 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
949 throws RemoteException {
950 try {
951 return super.onTransact(code, data, reply, flags);
952 } catch (RuntimeException e) {
953 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800954 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 }
956 throw e;
957 }
958 }
959
Dianne Hackborne6620b22010-01-22 14:46:21 -0800960 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800961 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800963 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
964 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800966 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800967 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 }
969 } else {
970 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800971 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 File dataDir = new File(pkg.applicationInfo.dataDir);
973 dataDir.delete();
974 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800975 if (ps.codePath != null) {
976 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800977 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800978 }
979 }
980 if (ps.resourcePath != null) {
981 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800982 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800983 }
984 }
985 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 }
987
988 void readPermissions() {
989 // Read permissions from .../etc/permission directory.
990 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
991 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800992 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 return;
994 }
995 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800996 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 return;
998 }
999
1000 // Iterate over the files in the directory and scan .xml files
1001 for (File f : libraryDir.listFiles()) {
1002 // We'll read platform.xml last
1003 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1004 continue;
1005 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001008 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 continue;
1010 }
1011 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001012 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 continue;
1014 }
1015
1016 readPermissionsFromXml(f);
1017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1020 final File permFile = new File(Environment.getRootDirectory(),
1021 "etc/permissions/platform.xml");
1022 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001023
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001024 StringBuilder sb = new StringBuilder(128);
1025 sb.append("Libs:");
1026 Iterator<String> it = mSharedLibraries.keySet().iterator();
1027 while (it.hasNext()) {
1028 sb.append(' ');
1029 String name = it.next();
1030 sb.append(name);
1031 sb.append(':');
1032 sb.append(mSharedLibraries.get(name));
1033 }
1034 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001035
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001036 sb.setLength(0);
1037 sb.append("Features:");
1038 it = mAvailableFeatures.keySet().iterator();
1039 while (it.hasNext()) {
1040 sb.append(' ');
1041 sb.append(it.next());
1042 }
1043 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001045
1046 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 FileReader permReader = null;
1048 try {
1049 permReader = new FileReader(permFile);
1050 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001051 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 return;
1053 }
1054
1055 try {
1056 XmlPullParser parser = Xml.newPullParser();
1057 parser.setInput(permReader);
1058
1059 XmlUtils.beginDocument(parser, "permissions");
1060
1061 while (true) {
1062 XmlUtils.nextElement(parser);
1063 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1064 break;
1065 }
1066
1067 String name = parser.getName();
1068 if ("group".equals(name)) {
1069 String gidStr = parser.getAttributeValue(null, "gid");
1070 if (gidStr != null) {
1071 int gid = Integer.parseInt(gidStr);
1072 mGlobalGids = appendInt(mGlobalGids, gid);
1073 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001074 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 + parser.getPositionDescription());
1076 }
1077
1078 XmlUtils.skipCurrentTag(parser);
1079 continue;
1080 } else if ("permission".equals(name)) {
1081 String perm = parser.getAttributeValue(null, "name");
1082 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001083 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 + parser.getPositionDescription());
1085 XmlUtils.skipCurrentTag(parser);
1086 continue;
1087 }
1088 perm = perm.intern();
1089 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 } else if ("assign-permission".equals(name)) {
1092 String perm = parser.getAttributeValue(null, "name");
1093 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001094 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 + parser.getPositionDescription());
1096 XmlUtils.skipCurrentTag(parser);
1097 continue;
1098 }
1099 String uidStr = parser.getAttributeValue(null, "uid");
1100 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001101 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 + parser.getPositionDescription());
1103 XmlUtils.skipCurrentTag(parser);
1104 continue;
1105 }
1106 int uid = Process.getUidForName(uidStr);
1107 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001108 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 + uidStr + "\" at "
1110 + parser.getPositionDescription());
1111 XmlUtils.skipCurrentTag(parser);
1112 continue;
1113 }
1114 perm = perm.intern();
1115 HashSet<String> perms = mSystemPermissions.get(uid);
1116 if (perms == null) {
1117 perms = new HashSet<String>();
1118 mSystemPermissions.put(uid, perms);
1119 }
1120 perms.add(perm);
1121 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 } else if ("library".equals(name)) {
1124 String lname = parser.getAttributeValue(null, "name");
1125 String lfile = parser.getAttributeValue(null, "file");
1126 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001127 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 + parser.getPositionDescription());
1129 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001130 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 + parser.getPositionDescription());
1132 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001133 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001134 mSharedLibraries.put(lname, lfile);
1135 }
1136 XmlUtils.skipCurrentTag(parser);
1137 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001138
Dianne Hackborn49237342009-08-27 20:08:01 -07001139 } else if ("feature".equals(name)) {
1140 String fname = parser.getAttributeValue(null, "name");
1141 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001142 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001143 + parser.getPositionDescription());
1144 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001145 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001146 FeatureInfo fi = new FeatureInfo();
1147 fi.name = fname;
1148 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 }
1150 XmlUtils.skipCurrentTag(parser);
1151 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 } else {
1154 XmlUtils.skipCurrentTag(parser);
1155 continue;
1156 }
1157
1158 }
1159 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001160 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001162 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 }
1164 }
1165
1166 void readPermission(XmlPullParser parser, String name)
1167 throws IOException, XmlPullParserException {
1168
1169 name = name.intern();
1170
1171 BasePermission bp = mSettings.mPermissions.get(name);
1172 if (bp == null) {
1173 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1174 mSettings.mPermissions.put(name, bp);
1175 }
1176 int outerDepth = parser.getDepth();
1177 int type;
1178 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1179 && (type != XmlPullParser.END_TAG
1180 || parser.getDepth() > outerDepth)) {
1181 if (type == XmlPullParser.END_TAG
1182 || type == XmlPullParser.TEXT) {
1183 continue;
1184 }
1185
1186 String tagName = parser.getName();
1187 if ("group".equals(tagName)) {
1188 String gidStr = parser.getAttributeValue(null, "gid");
1189 if (gidStr != null) {
1190 int gid = Process.getGidForName(gidStr);
1191 bp.gids = appendInt(bp.gids, gid);
1192 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001193 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 + parser.getPositionDescription());
1195 }
1196 }
1197 XmlUtils.skipCurrentTag(parser);
1198 }
1199 }
1200
1201 static int[] appendInt(int[] cur, int val) {
1202 if (cur == null) {
1203 return new int[] { val };
1204 }
1205 final int N = cur.length;
1206 for (int i=0; i<N; i++) {
1207 if (cur[i] == val) {
1208 return cur;
1209 }
1210 }
1211 int[] ret = new int[N+1];
1212 System.arraycopy(cur, 0, ret, 0, N);
1213 ret[N] = val;
1214 return ret;
1215 }
1216
1217 static int[] appendInts(int[] cur, int[] add) {
1218 if (add == null) return cur;
1219 if (cur == null) return add;
1220 final int N = add.length;
1221 for (int i=0; i<N; i++) {
1222 cur = appendInt(cur, add[i]);
1223 }
1224 return cur;
1225 }
1226
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001227 static int[] removeInt(int[] cur, int val) {
1228 if (cur == null) {
1229 return null;
1230 }
1231 final int N = cur.length;
1232 for (int i=0; i<N; i++) {
1233 if (cur[i] == val) {
1234 int[] ret = new int[N-1];
1235 if (i > 0) {
1236 System.arraycopy(cur, 0, ret, 0, i);
1237 }
1238 if (i < (N-1)) {
1239 System.arraycopy(cur, i, ret, i+1, N-i-1);
1240 }
1241 return ret;
1242 }
1243 }
1244 return cur;
1245 }
1246
1247 static int[] removeInts(int[] cur, int[] rem) {
1248 if (rem == null) return cur;
1249 if (cur == null) return cur;
1250 final int N = rem.length;
1251 for (int i=0; i<N; i++) {
1252 cur = removeInt(cur, rem[i]);
1253 }
1254 return cur;
1255 }
1256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001258 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1259 // The package has been uninstalled but has retained data and resources.
1260 return PackageParser.generatePackageInfo(p, null, flags);
1261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 final PackageSetting ps = (PackageSetting)p.mExtras;
1263 if (ps == null) {
1264 return null;
1265 }
1266 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1267 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1268 }
1269
1270 public PackageInfo getPackageInfo(String packageName, int flags) {
1271 synchronized (mPackages) {
1272 PackageParser.Package p = mPackages.get(packageName);
1273 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001274 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 + ": " + p);
1276 if (p != null) {
1277 return generatePackageInfo(p, flags);
1278 }
1279 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1280 return generatePackageInfoFromSettingsLP(packageName, flags);
1281 }
1282 }
1283 return null;
1284 }
1285
Dianne Hackborn47096932010-02-11 15:57:09 -08001286 public String[] currentToCanonicalPackageNames(String[] names) {
1287 String[] out = new String[names.length];
1288 synchronized (mPackages) {
1289 for (int i=names.length-1; i>=0; i--) {
1290 PackageSetting ps = mSettings.mPackages.get(names[i]);
1291 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1292 }
1293 }
1294 return out;
1295 }
1296
1297 public String[] canonicalToCurrentPackageNames(String[] names) {
1298 String[] out = new String[names.length];
1299 synchronized (mPackages) {
1300 for (int i=names.length-1; i>=0; i--) {
1301 String cur = mSettings.mRenamedPackages.get(names[i]);
1302 out[i] = cur != null ? cur : names[i];
1303 }
1304 }
1305 return out;
1306 }
1307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 public int getPackageUid(String packageName) {
1309 synchronized (mPackages) {
1310 PackageParser.Package p = mPackages.get(packageName);
1311 if(p != null) {
1312 return p.applicationInfo.uid;
1313 }
1314 PackageSetting ps = mSettings.mPackages.get(packageName);
1315 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1316 return -1;
1317 }
1318 p = ps.pkg;
1319 return p != null ? p.applicationInfo.uid : -1;
1320 }
1321 }
1322
1323 public int[] getPackageGids(String packageName) {
1324 synchronized (mPackages) {
1325 PackageParser.Package p = mPackages.get(packageName);
1326 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001327 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 + ": " + p);
1329 if (p != null) {
1330 final PackageSetting ps = (PackageSetting)p.mExtras;
1331 final SharedUserSetting suid = ps.sharedUser;
1332 return suid != null ? suid.gids : ps.gids;
1333 }
1334 }
1335 // stupid thing to indicate an error.
1336 return new int[0];
1337 }
1338
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001339 static final PermissionInfo generatePermissionInfo(
1340 BasePermission bp, int flags) {
1341 if (bp.perm != null) {
1342 return PackageParser.generatePermissionInfo(bp.perm, flags);
1343 }
1344 PermissionInfo pi = new PermissionInfo();
1345 pi.name = bp.name;
1346 pi.packageName = bp.sourcePackage;
1347 pi.nonLocalizedLabel = bp.name;
1348 pi.protectionLevel = bp.protectionLevel;
1349 return pi;
1350 }
1351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 public PermissionInfo getPermissionInfo(String name, int flags) {
1353 synchronized (mPackages) {
1354 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001355 if (p != null) {
1356 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 }
1358 return null;
1359 }
1360 }
1361
1362 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1363 synchronized (mPackages) {
1364 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1365 for (BasePermission p : mSettings.mPermissions.values()) {
1366 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001367 if (p.perm == null || p.perm.info.group == null) {
1368 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 }
1370 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001371 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1373 }
1374 }
1375 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 if (out.size() > 0) {
1378 return out;
1379 }
1380 return mPermissionGroups.containsKey(group) ? out : null;
1381 }
1382 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1385 synchronized (mPackages) {
1386 return PackageParser.generatePermissionGroupInfo(
1387 mPermissionGroups.get(name), flags);
1388 }
1389 }
1390
1391 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1392 synchronized (mPackages) {
1393 final int N = mPermissionGroups.size();
1394 ArrayList<PermissionGroupInfo> out
1395 = new ArrayList<PermissionGroupInfo>(N);
1396 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1397 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1398 }
1399 return out;
1400 }
1401 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1404 PackageSetting ps = mSettings.mPackages.get(packageName);
1405 if(ps != null) {
1406 if(ps.pkg == null) {
1407 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1408 if(pInfo != null) {
1409 return pInfo.applicationInfo;
1410 }
1411 return null;
1412 }
1413 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1414 }
1415 return null;
1416 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1419 PackageSetting ps = mSettings.mPackages.get(packageName);
1420 if(ps != null) {
1421 if(ps.pkg == null) {
1422 ps.pkg = new PackageParser.Package(packageName);
1423 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001424 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1425 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1426 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1427 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429 return generatePackageInfo(ps.pkg, flags);
1430 }
1431 return null;
1432 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1435 synchronized (mPackages) {
1436 PackageParser.Package p = mPackages.get(packageName);
1437 if (Config.LOGV) Log.v(
1438 TAG, "getApplicationInfo " + packageName
1439 + ": " + p);
1440 if (p != null) {
1441 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001442 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 }
1444 if ("android".equals(packageName)||"system".equals(packageName)) {
1445 return mAndroidApplication;
1446 }
1447 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1448 return generateApplicationInfoFromSettingsLP(packageName, flags);
1449 }
1450 }
1451 return null;
1452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001453
1454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1456 mContext.enforceCallingOrSelfPermission(
1457 android.Manifest.permission.CLEAR_APP_CACHE, null);
1458 // Queue up an async operation since clearing cache may take a little while.
1459 mHandler.post(new Runnable() {
1460 public void run() {
1461 mHandler.removeCallbacks(this);
1462 int retCode = -1;
1463 if (mInstaller != null) {
1464 retCode = mInstaller.freeCache(freeStorageSize);
1465 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001466 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
1468 } //end if mInstaller
1469 if (observer != null) {
1470 try {
1471 observer.onRemoveCompleted(null, (retCode >= 0));
1472 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001473 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 }
1475 }
1476 }
1477 });
1478 }
1479
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001480 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001481 mContext.enforceCallingOrSelfPermission(
1482 android.Manifest.permission.CLEAR_APP_CACHE, null);
1483 // Queue up an async operation since clearing cache may take a little while.
1484 mHandler.post(new Runnable() {
1485 public void run() {
1486 mHandler.removeCallbacks(this);
1487 int retCode = -1;
1488 if (mInstaller != null) {
1489 retCode = mInstaller.freeCache(freeStorageSize);
1490 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001491 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001492 }
1493 }
1494 if(pi != null) {
1495 try {
1496 // Callback via pending intent
1497 int code = (retCode >= 0) ? 1 : 0;
1498 pi.sendIntent(null, code, null,
1499 null, null);
1500 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001501 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001502 }
1503 }
1504 }
1505 });
1506 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1509 synchronized (mPackages) {
1510 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001511
1512 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001514 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516 if (mResolveComponentName.equals(component)) {
1517 return mResolveActivity;
1518 }
1519 }
1520 return null;
1521 }
1522
1523 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1524 synchronized (mPackages) {
1525 PackageParser.Activity a = mReceivers.mActivities.get(component);
1526 if (Config.LOGV) Log.v(
1527 TAG, "getReceiverInfo " + component + ": " + a);
1528 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1529 return PackageParser.generateActivityInfo(a, flags);
1530 }
1531 }
1532 return null;
1533 }
1534
1535 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1536 synchronized (mPackages) {
1537 PackageParser.Service s = mServices.mServices.get(component);
1538 if (Config.LOGV) Log.v(
1539 TAG, "getServiceInfo " + component + ": " + s);
1540 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1541 return PackageParser.generateServiceInfo(s, flags);
1542 }
1543 }
1544 return null;
1545 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 public String[] getSystemSharedLibraryNames() {
1548 Set<String> libSet;
1549 synchronized (mPackages) {
1550 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001551 int size = libSet.size();
1552 if (size > 0) {
1553 String[] libs = new String[size];
1554 libSet.toArray(libs);
1555 return libs;
1556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001558 return null;
1559 }
1560
1561 public FeatureInfo[] getSystemAvailableFeatures() {
1562 Collection<FeatureInfo> featSet;
1563 synchronized (mPackages) {
1564 featSet = mAvailableFeatures.values();
1565 int size = featSet.size();
1566 if (size > 0) {
1567 FeatureInfo[] features = new FeatureInfo[size+1];
1568 featSet.toArray(features);
1569 FeatureInfo fi = new FeatureInfo();
1570 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1571 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1572 features[size] = fi;
1573 return features;
1574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 }
1576 return null;
1577 }
1578
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001579 public boolean hasSystemFeature(String name) {
1580 synchronized (mPackages) {
1581 return mAvailableFeatures.containsKey(name);
1582 }
1583 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 public int checkPermission(String permName, String pkgName) {
1586 synchronized (mPackages) {
1587 PackageParser.Package p = mPackages.get(pkgName);
1588 if (p != null && p.mExtras != null) {
1589 PackageSetting ps = (PackageSetting)p.mExtras;
1590 if (ps.sharedUser != null) {
1591 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1592 return PackageManager.PERMISSION_GRANTED;
1593 }
1594 } else if (ps.grantedPermissions.contains(permName)) {
1595 return PackageManager.PERMISSION_GRANTED;
1596 }
1597 }
1598 }
1599 return PackageManager.PERMISSION_DENIED;
1600 }
1601
1602 public int checkUidPermission(String permName, int uid) {
1603 synchronized (mPackages) {
1604 Object obj = mSettings.getUserIdLP(uid);
1605 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001606 GrantedPermissions gp = (GrantedPermissions)obj;
1607 if (gp.grantedPermissions.contains(permName)) {
1608 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
1610 } else {
1611 HashSet<String> perms = mSystemPermissions.get(uid);
1612 if (perms != null && perms.contains(permName)) {
1613 return PackageManager.PERMISSION_GRANTED;
1614 }
1615 }
1616 }
1617 return PackageManager.PERMISSION_DENIED;
1618 }
1619
1620 private BasePermission findPermissionTreeLP(String permName) {
1621 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1622 if (permName.startsWith(bp.name) &&
1623 permName.length() > bp.name.length() &&
1624 permName.charAt(bp.name.length()) == '.') {
1625 return bp;
1626 }
1627 }
1628 return null;
1629 }
1630
1631 private BasePermission checkPermissionTreeLP(String permName) {
1632 if (permName != null) {
1633 BasePermission bp = findPermissionTreeLP(permName);
1634 if (bp != null) {
1635 if (bp.uid == Binder.getCallingUid()) {
1636 return bp;
1637 }
1638 throw new SecurityException("Calling uid "
1639 + Binder.getCallingUid()
1640 + " is not allowed to add to permission tree "
1641 + bp.name + " owned by uid " + bp.uid);
1642 }
1643 }
1644 throw new SecurityException("No permission tree found for " + permName);
1645 }
1646
1647 public boolean addPermission(PermissionInfo info) {
1648 synchronized (mPackages) {
1649 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1650 throw new SecurityException("Label must be specified in permission");
1651 }
1652 BasePermission tree = checkPermissionTreeLP(info.name);
1653 BasePermission bp = mSettings.mPermissions.get(info.name);
1654 boolean added = bp == null;
1655 if (added) {
1656 bp = new BasePermission(info.name, tree.sourcePackage,
1657 BasePermission.TYPE_DYNAMIC);
1658 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1659 throw new SecurityException(
1660 "Not allowed to modify non-dynamic permission "
1661 + info.name);
1662 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001663 bp.protectionLevel = info.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 bp.perm = new PackageParser.Permission(tree.perm.owner,
1665 new PermissionInfo(info));
1666 bp.perm.info.packageName = tree.perm.info.packageName;
1667 bp.uid = tree.uid;
1668 if (added) {
1669 mSettings.mPermissions.put(info.name, bp);
1670 }
1671 mSettings.writeLP();
1672 return added;
1673 }
1674 }
1675
1676 public void removePermission(String name) {
1677 synchronized (mPackages) {
1678 checkPermissionTreeLP(name);
1679 BasePermission bp = mSettings.mPermissions.get(name);
1680 if (bp != null) {
1681 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1682 throw new SecurityException(
1683 "Not allowed to modify non-dynamic permission "
1684 + name);
1685 }
1686 mSettings.mPermissions.remove(name);
1687 mSettings.writeLP();
1688 }
1689 }
1690 }
1691
Dianne Hackborn854060af2009-07-09 18:14:31 -07001692 public boolean isProtectedBroadcast(String actionName) {
1693 synchronized (mPackages) {
1694 return mProtectedBroadcasts.contains(actionName);
1695 }
1696 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 public int checkSignatures(String pkg1, String pkg2) {
1699 synchronized (mPackages) {
1700 PackageParser.Package p1 = mPackages.get(pkg1);
1701 PackageParser.Package p2 = mPackages.get(pkg2);
1702 if (p1 == null || p1.mExtras == null
1703 || p2 == null || p2.mExtras == null) {
1704 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1705 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001706 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 }
1708 }
1709
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001710 public int checkUidSignatures(int uid1, int uid2) {
1711 synchronized (mPackages) {
1712 Signature[] s1;
1713 Signature[] s2;
1714 Object obj = mSettings.getUserIdLP(uid1);
1715 if (obj != null) {
1716 if (obj instanceof SharedUserSetting) {
1717 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1718 } else if (obj instanceof PackageSetting) {
1719 s1 = ((PackageSetting)obj).signatures.mSignatures;
1720 } else {
1721 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1722 }
1723 } else {
1724 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1725 }
1726 obj = mSettings.getUserIdLP(uid2);
1727 if (obj != null) {
1728 if (obj instanceof SharedUserSetting) {
1729 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1730 } else if (obj instanceof PackageSetting) {
1731 s2 = ((PackageSetting)obj).signatures.mSignatures;
1732 } else {
1733 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1734 }
1735 } else {
1736 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1737 }
1738 return checkSignaturesLP(s1, s2);
1739 }
1740 }
1741
1742 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1743 if (s1 == null) {
1744 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1746 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1747 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001748 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1750 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001751 final int N1 = s1.length;
1752 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 for (int i=0; i<N1; i++) {
1754 boolean match = false;
1755 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001756 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 match = true;
1758 break;
1759 }
1760 }
1761 if (!match) {
1762 return PackageManager.SIGNATURE_NO_MATCH;
1763 }
1764 }
1765 return PackageManager.SIGNATURE_MATCH;
1766 }
1767
1768 public String[] getPackagesForUid(int uid) {
1769 synchronized (mPackages) {
1770 Object obj = mSettings.getUserIdLP(uid);
1771 if (obj instanceof SharedUserSetting) {
1772 SharedUserSetting sus = (SharedUserSetting)obj;
1773 final int N = sus.packages.size();
1774 String[] res = new String[N];
1775 Iterator<PackageSetting> it = sus.packages.iterator();
1776 int i=0;
1777 while (it.hasNext()) {
1778 res[i++] = it.next().name;
1779 }
1780 return res;
1781 } else if (obj instanceof PackageSetting) {
1782 PackageSetting ps = (PackageSetting)obj;
1783 return new String[] { ps.name };
1784 }
1785 }
1786 return null;
1787 }
1788
1789 public String getNameForUid(int uid) {
1790 synchronized (mPackages) {
1791 Object obj = mSettings.getUserIdLP(uid);
1792 if (obj instanceof SharedUserSetting) {
1793 SharedUserSetting sus = (SharedUserSetting)obj;
1794 return sus.name + ":" + sus.userId;
1795 } else if (obj instanceof PackageSetting) {
1796 PackageSetting ps = (PackageSetting)obj;
1797 return ps.name;
1798 }
1799 }
1800 return null;
1801 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 public int getUidForSharedUser(String sharedUserName) {
1804 if(sharedUserName == null) {
1805 return -1;
1806 }
1807 synchronized (mPackages) {
1808 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1809 if(suid == null) {
1810 return -1;
1811 }
1812 return suid.userId;
1813 }
1814 }
1815
1816 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1817 int flags) {
1818 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001819 return chooseBestActivity(intent, resolvedType, flags, query);
1820 }
1821
Mihai Predaeae850c2009-05-13 10:13:48 +02001822 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1823 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 if (query != null) {
1825 final int N = query.size();
1826 if (N == 1) {
1827 return query.get(0);
1828 } else if (N > 1) {
1829 // If there is more than one activity with the same priority,
1830 // then let the user decide between them.
1831 ResolveInfo r0 = query.get(0);
1832 ResolveInfo r1 = query.get(1);
1833 if (false) {
1834 System.out.println(r0.activityInfo.name +
1835 "=" + r0.priority + " vs " +
1836 r1.activityInfo.name +
1837 "=" + r1.priority);
1838 }
1839 // If the first activity has a higher priority, or a different
1840 // default, then it is always desireable to pick it.
1841 if (r0.priority != r1.priority
1842 || r0.preferredOrder != r1.preferredOrder
1843 || r0.isDefault != r1.isDefault) {
1844 return query.get(0);
1845 }
1846 // If we have saved a preference for a preferred activity for
1847 // this Intent, use that.
1848 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1849 flags, query, r0.priority);
1850 if (ri != null) {
1851 return ri;
1852 }
1853 return mResolveInfo;
1854 }
1855 }
1856 return null;
1857 }
1858
1859 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1860 int flags, List<ResolveInfo> query, int priority) {
1861 synchronized (mPackages) {
1862 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1863 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001864 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1866 if (prefs != null && prefs.size() > 0) {
1867 // First figure out how good the original match set is.
1868 // We will only allow preferred activities that came
1869 // from the same match quality.
1870 int match = 0;
1871 final int N = query.size();
1872 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1873 for (int j=0; j<N; j++) {
1874 ResolveInfo ri = query.get(j);
1875 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1876 + ": 0x" + Integer.toHexString(match));
1877 if (ri.match > match) match = ri.match;
1878 }
1879 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1880 + Integer.toHexString(match));
1881 match &= IntentFilter.MATCH_CATEGORY_MASK;
1882 final int M = prefs.size();
1883 for (int i=0; i<M; i++) {
1884 PreferredActivity pa = prefs.get(i);
1885 if (pa.mMatch != match) {
1886 continue;
1887 }
1888 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1889 if (DEBUG_PREFERRED) {
1890 Log.v(TAG, "Got preferred activity:");
1891 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1892 }
1893 if (ai != null) {
1894 for (int j=0; j<N; j++) {
1895 ResolveInfo ri = query.get(j);
1896 if (!ri.activityInfo.applicationInfo.packageName
1897 .equals(ai.applicationInfo.packageName)) {
1898 continue;
1899 }
1900 if (!ri.activityInfo.name.equals(ai.name)) {
1901 continue;
1902 }
1903
1904 // Okay we found a previously set preferred app.
1905 // If the result set is different from when this
1906 // was created, we need to clear it and re-ask the
1907 // user their preference.
1908 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001909 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 + intent + " type " + resolvedType);
1911 mSettings.mPreferredActivities.removeFilter(pa);
1912 return null;
1913 }
1914
1915 // Yay!
1916 return ri;
1917 }
1918 }
1919 }
1920 }
1921 }
1922 return null;
1923 }
1924
1925 public List<ResolveInfo> queryIntentActivities(Intent intent,
1926 String resolvedType, int flags) {
1927 ComponentName comp = intent.getComponent();
1928 if (comp != null) {
1929 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1930 ActivityInfo ai = getActivityInfo(comp, flags);
1931 if (ai != null) {
1932 ResolveInfo ri = new ResolveInfo();
1933 ri.activityInfo = ai;
1934 list.add(ri);
1935 }
1936 return list;
1937 }
1938
1939 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001940 String pkgName = intent.getPackage();
1941 if (pkgName == null) {
1942 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1943 resolvedType, flags);
1944 }
1945 PackageParser.Package pkg = mPackages.get(pkgName);
1946 if (pkg != null) {
1947 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1948 resolvedType, flags, pkg.activities);
1949 }
1950 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 }
1952 }
1953
1954 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1955 Intent[] specifics, String[] specificTypes, Intent intent,
1956 String resolvedType, int flags) {
1957 final String resultsAction = intent.getAction();
1958
1959 List<ResolveInfo> results = queryIntentActivities(
1960 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1961 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1962
1963 int specificsPos = 0;
1964 int N;
1965
1966 // todo: note that the algorithm used here is O(N^2). This
1967 // isn't a problem in our current environment, but if we start running
1968 // into situations where we have more than 5 or 10 matches then this
1969 // should probably be changed to something smarter...
1970
1971 // First we go through and resolve each of the specific items
1972 // that were supplied, taking care of removing any corresponding
1973 // duplicate items in the generic resolve list.
1974 if (specifics != null) {
1975 for (int i=0; i<specifics.length; i++) {
1976 final Intent sintent = specifics[i];
1977 if (sintent == null) {
1978 continue;
1979 }
1980
1981 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1982 String action = sintent.getAction();
1983 if (resultsAction != null && resultsAction.equals(action)) {
1984 // If this action was explicitly requested, then don't
1985 // remove things that have it.
1986 action = null;
1987 }
1988 ComponentName comp = sintent.getComponent();
1989 ResolveInfo ri = null;
1990 ActivityInfo ai = null;
1991 if (comp == null) {
1992 ri = resolveIntent(
1993 sintent,
1994 specificTypes != null ? specificTypes[i] : null,
1995 flags);
1996 if (ri == null) {
1997 continue;
1998 }
1999 if (ri == mResolveInfo) {
2000 // ACK! Must do something better with this.
2001 }
2002 ai = ri.activityInfo;
2003 comp = new ComponentName(ai.applicationInfo.packageName,
2004 ai.name);
2005 } else {
2006 ai = getActivityInfo(comp, flags);
2007 if (ai == null) {
2008 continue;
2009 }
2010 }
2011
2012 // Look for any generic query activities that are duplicates
2013 // of this specific one, and remove them from the results.
2014 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2015 N = results.size();
2016 int j;
2017 for (j=specificsPos; j<N; j++) {
2018 ResolveInfo sri = results.get(j);
2019 if ((sri.activityInfo.name.equals(comp.getClassName())
2020 && sri.activityInfo.applicationInfo.packageName.equals(
2021 comp.getPackageName()))
2022 || (action != null && sri.filter.matchAction(action))) {
2023 results.remove(j);
2024 if (Config.LOGV) Log.v(
2025 TAG, "Removing duplicate item from " + j
2026 + " due to specific " + specificsPos);
2027 if (ri == null) {
2028 ri = sri;
2029 }
2030 j--;
2031 N--;
2032 }
2033 }
2034
2035 // Add this specific item to its proper place.
2036 if (ri == null) {
2037 ri = new ResolveInfo();
2038 ri.activityInfo = ai;
2039 }
2040 results.add(specificsPos, ri);
2041 ri.specificIndex = i;
2042 specificsPos++;
2043 }
2044 }
2045
2046 // Now we go through the remaining generic results and remove any
2047 // duplicate actions that are found here.
2048 N = results.size();
2049 for (int i=specificsPos; i<N-1; i++) {
2050 final ResolveInfo rii = results.get(i);
2051 if (rii.filter == null) {
2052 continue;
2053 }
2054
2055 // Iterate over all of the actions of this result's intent
2056 // filter... typically this should be just one.
2057 final Iterator<String> it = rii.filter.actionsIterator();
2058 if (it == null) {
2059 continue;
2060 }
2061 while (it.hasNext()) {
2062 final String action = it.next();
2063 if (resultsAction != null && resultsAction.equals(action)) {
2064 // If this action was explicitly requested, then don't
2065 // remove things that have it.
2066 continue;
2067 }
2068 for (int j=i+1; j<N; j++) {
2069 final ResolveInfo rij = results.get(j);
2070 if (rij.filter != null && rij.filter.hasAction(action)) {
2071 results.remove(j);
2072 if (Config.LOGV) Log.v(
2073 TAG, "Removing duplicate item from " + j
2074 + " due to action " + action + " at " + i);
2075 j--;
2076 N--;
2077 }
2078 }
2079 }
2080
2081 // If the caller didn't request filter information, drop it now
2082 // so we don't have to marshall/unmarshall it.
2083 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2084 rii.filter = null;
2085 }
2086 }
2087
2088 // Filter out the caller activity if so requested.
2089 if (caller != null) {
2090 N = results.size();
2091 for (int i=0; i<N; i++) {
2092 ActivityInfo ainfo = results.get(i).activityInfo;
2093 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2094 && caller.getClassName().equals(ainfo.name)) {
2095 results.remove(i);
2096 break;
2097 }
2098 }
2099 }
2100
2101 // If the caller didn't request filter information,
2102 // drop them now so we don't have to
2103 // marshall/unmarshall it.
2104 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2105 N = results.size();
2106 for (int i=0; i<N; i++) {
2107 results.get(i).filter = null;
2108 }
2109 }
2110
2111 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2112 return results;
2113 }
2114
2115 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2116 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002117 ComponentName comp = intent.getComponent();
2118 if (comp != null) {
2119 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2120 ActivityInfo ai = getReceiverInfo(comp, flags);
2121 if (ai != null) {
2122 ResolveInfo ri = new ResolveInfo();
2123 ri.activityInfo = ai;
2124 list.add(ri);
2125 }
2126 return list;
2127 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002130 String pkgName = intent.getPackage();
2131 if (pkgName == null) {
2132 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2133 resolvedType, flags);
2134 }
2135 PackageParser.Package pkg = mPackages.get(pkgName);
2136 if (pkg != null) {
2137 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2138 resolvedType, flags, pkg.receivers);
2139 }
2140 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 }
2142 }
2143
2144 public ResolveInfo resolveService(Intent intent, String resolvedType,
2145 int flags) {
2146 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2147 flags);
2148 if (query != null) {
2149 if (query.size() >= 1) {
2150 // If there is more than one service with the same priority,
2151 // just arbitrarily pick the first one.
2152 return query.get(0);
2153 }
2154 }
2155 return null;
2156 }
2157
2158 public List<ResolveInfo> queryIntentServices(Intent intent,
2159 String resolvedType, int flags) {
2160 ComponentName comp = intent.getComponent();
2161 if (comp != null) {
2162 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2163 ServiceInfo si = getServiceInfo(comp, flags);
2164 if (si != null) {
2165 ResolveInfo ri = new ResolveInfo();
2166 ri.serviceInfo = si;
2167 list.add(ri);
2168 }
2169 return list;
2170 }
2171
2172 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002173 String pkgName = intent.getPackage();
2174 if (pkgName == null) {
2175 return (List<ResolveInfo>)mServices.queryIntent(intent,
2176 resolvedType, flags);
2177 }
2178 PackageParser.Package pkg = mPackages.get(pkgName);
2179 if (pkg != null) {
2180 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2181 resolvedType, flags, pkg.services);
2182 }
2183 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 }
2185 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 public List<PackageInfo> getInstalledPackages(int flags) {
2188 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2189
2190 synchronized (mPackages) {
2191 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2192 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2193 while (i.hasNext()) {
2194 final PackageSetting ps = i.next();
2195 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2196 if(psPkg != null) {
2197 finalList.add(psPkg);
2198 }
2199 }
2200 }
2201 else {
2202 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2203 while (i.hasNext()) {
2204 final PackageParser.Package p = i.next();
2205 if (p.applicationInfo != null) {
2206 PackageInfo pi = generatePackageInfo(p, flags);
2207 if(pi != null) {
2208 finalList.add(pi);
2209 }
2210 }
2211 }
2212 }
2213 }
2214 return finalList;
2215 }
2216
2217 public List<ApplicationInfo> getInstalledApplications(int flags) {
2218 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2219 synchronized(mPackages) {
2220 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2221 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2222 while (i.hasNext()) {
2223 final PackageSetting ps = i.next();
2224 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2225 if(ai != null) {
2226 finalList.add(ai);
2227 }
2228 }
2229 }
2230 else {
2231 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2232 while (i.hasNext()) {
2233 final PackageParser.Package p = i.next();
2234 if (p.applicationInfo != null) {
2235 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2236 if(ai != null) {
2237 finalList.add(ai);
2238 }
2239 }
2240 }
2241 }
2242 }
2243 return finalList;
2244 }
2245
2246 public List<ApplicationInfo> getPersistentApplications(int flags) {
2247 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2248
2249 synchronized (mPackages) {
2250 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2251 while (i.hasNext()) {
2252 PackageParser.Package p = i.next();
2253 if (p.applicationInfo != null
2254 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2255 && (!mSafeMode || (p.applicationInfo.flags
2256 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2257 finalList.add(p.applicationInfo);
2258 }
2259 }
2260 }
2261
2262 return finalList;
2263 }
2264
2265 public ProviderInfo resolveContentProvider(String name, int flags) {
2266 synchronized (mPackages) {
2267 final PackageParser.Provider provider = mProviders.get(name);
2268 return provider != null
2269 && mSettings.isEnabledLP(provider.info, flags)
2270 && (!mSafeMode || (provider.info.applicationInfo.flags
2271 &ApplicationInfo.FLAG_SYSTEM) != 0)
2272 ? PackageParser.generateProviderInfo(provider, flags)
2273 : null;
2274 }
2275 }
2276
Fred Quintana718d8a22009-04-29 17:53:20 -07002277 /**
2278 * @deprecated
2279 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 public void querySyncProviders(List outNames, List outInfo) {
2281 synchronized (mPackages) {
2282 Iterator<Map.Entry<String, PackageParser.Provider>> i
2283 = mProviders.entrySet().iterator();
2284
2285 while (i.hasNext()) {
2286 Map.Entry<String, PackageParser.Provider> entry = i.next();
2287 PackageParser.Provider p = entry.getValue();
2288
2289 if (p.syncable
2290 && (!mSafeMode || (p.info.applicationInfo.flags
2291 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2292 outNames.add(entry.getKey());
2293 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2294 }
2295 }
2296 }
2297 }
2298
2299 public List<ProviderInfo> queryContentProviders(String processName,
2300 int uid, int flags) {
2301 ArrayList<ProviderInfo> finalList = null;
2302
2303 synchronized (mPackages) {
2304 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2305 while (i.hasNext()) {
2306 PackageParser.Provider p = i.next();
2307 if (p.info.authority != null
2308 && (processName == null ||
2309 (p.info.processName.equals(processName)
2310 && p.info.applicationInfo.uid == uid))
2311 && mSettings.isEnabledLP(p.info, flags)
2312 && (!mSafeMode || (p.info.applicationInfo.flags
2313 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2314 if (finalList == null) {
2315 finalList = new ArrayList<ProviderInfo>(3);
2316 }
2317 finalList.add(PackageParser.generateProviderInfo(p,
2318 flags));
2319 }
2320 }
2321 }
2322
2323 if (finalList != null) {
2324 Collections.sort(finalList, mProviderInitOrderSorter);
2325 }
2326
2327 return finalList;
2328 }
2329
2330 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2331 int flags) {
2332 synchronized (mPackages) {
2333 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2334 return PackageParser.generateInstrumentationInfo(i, flags);
2335 }
2336 }
2337
2338 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2339 int flags) {
2340 ArrayList<InstrumentationInfo> finalList =
2341 new ArrayList<InstrumentationInfo>();
2342
2343 synchronized (mPackages) {
2344 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2345 while (i.hasNext()) {
2346 PackageParser.Instrumentation p = i.next();
2347 if (targetPackage == null
2348 || targetPackage.equals(p.info.targetPackage)) {
2349 finalList.add(PackageParser.generateInstrumentationInfo(p,
2350 flags));
2351 }
2352 }
2353 }
2354
2355 return finalList;
2356 }
2357
2358 private void scanDirLI(File dir, int flags, int scanMode) {
2359 Log.d(TAG, "Scanning app dir " + dir);
2360
2361 String[] files = dir.list();
2362
2363 int i;
2364 for (i=0; i<files.length; i++) {
2365 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002366 if (!isPackageFilename(files[i])) {
2367 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002368 continue;
2369 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002370 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002372 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002373 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2374 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002375 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002376 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002377 file.delete();
2378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 }
2380 }
2381
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002382 private static File getSettingsProblemFile() {
2383 File dataDir = Environment.getDataDirectory();
2384 File systemDir = new File(dataDir, "system");
2385 File fname = new File(systemDir, "uiderrors.txt");
2386 return fname;
2387 }
2388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 private static void reportSettingsProblem(int priority, String msg) {
2390 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002391 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 FileOutputStream out = new FileOutputStream(fname, true);
2393 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002394 SimpleDateFormat formatter = new SimpleDateFormat();
2395 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2396 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 pw.close();
2398 FileUtils.setPermissions(
2399 fname.toString(),
2400 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2401 -1, -1);
2402 } catch (java.io.IOException e) {
2403 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002404 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 }
2406
2407 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2408 PackageParser.Package pkg, File srcFile, int parseFlags) {
2409 if (GET_CERTIFICATES) {
2410 if (ps == null || !ps.codePath.equals(srcFile)
2411 || ps.getTimeStamp() != srcFile.lastModified()) {
2412 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2413 if (!pp.collectCertificates(pkg, parseFlags)) {
2414 mLastScanError = pp.getParseError();
2415 return false;
2416 }
2417 }
2418 }
2419 return true;
2420 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 /*
2423 * Scan a package and return the newly parsed package.
2424 * Returns null in case of errors and the error code is stored in mLastScanError
2425 */
2426 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002427 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002429 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002431 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002434 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 if (pkg == null) {
2436 mLastScanError = pp.getParseError();
2437 return null;
2438 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002439 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 PackageSetting updatedPkg;
2441 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002442 // Look to see if we already know about this package.
2443 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002444 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002445 // This package has been renamed to its original name. Let's
2446 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002447 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002448 }
2449 // If there was no original package, see one for the real package name.
2450 if (ps == null) {
2451 ps = mSettings.peekPackageLP(pkg.packageName);
2452 }
2453 // Check to see if this package could be hiding/updating a system
2454 // package. Must look for it either under the original or real
2455 // package name depending on our state.
2456 updatedPkg = mSettings.mDisabledSysPackages.get(
2457 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002459 // First check if this is a system package that may involve an update
2460 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2461 if (!ps.codePath.equals(scanFile)) {
2462 // The path has changed from what was last scanned... check the
2463 // version of the new path against what we have stored to determine
2464 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002465 if (pkg.mVersionCode < ps.versionCode) {
2466 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002467 // Ignore entry. Skip it.
2468 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2469 + "ignored: updated version " + ps.versionCode
2470 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002471 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2472 return null;
2473 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002474 // The current app on the system partion is better than
2475 // what we have updated to on the data partition; switch
2476 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002477 // At this point, its safely assumed that package installation for
2478 // apps in system partition will go through. If not there won't be a working
2479 // version of the app
2480 synchronized (mPackages) {
2481 // Just remove the loaded entries from package lists.
2482 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002483 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002484 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002485 + "reverting from " + ps.codePathString
2486 + ": new version " + pkg.mVersionCode
2487 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002488 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2489 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002490 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 }
2493 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002494 if (updatedPkg != null) {
2495 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2496 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2497 }
2498 // Verify certificates against what was last scanned
2499 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002500 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002501 return null;
2502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 // The apk is forward locked (not public) if its code and resources
2504 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002505 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002507 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002508 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002509
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002510 String codePath = null;
2511 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002512 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2513 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002514 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002515 } else {
2516 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002517 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002518 }
2519 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002520 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002521 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002522 codePath = pkg.mScanPath;
2523 // Set application objects path explicitly.
2524 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002526 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 }
2528
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002529 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2530 String destCodePath, String destResPath) {
2531 pkg.mPath = pkg.mScanPath = destCodePath;
2532 pkg.applicationInfo.sourceDir = destCodePath;
2533 pkg.applicationInfo.publicSourceDir = destResPath;
2534 }
2535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 private static String fixProcessName(String defProcessName,
2537 String processName, int uid) {
2538 if (processName == null) {
2539 return defProcessName;
2540 }
2541 return processName;
2542 }
2543
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002544 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2546 if (pkg.mSignatures != null) {
2547 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2548 updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002549 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 + " signatures do not match the previously installed version; ignoring!");
2551 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2552 return false;
2553 }
2554
2555 if (pkgSetting.sharedUser != null) {
2556 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2557 pkg.mSignatures, updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002558 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 + " has no signatures that match those in shared user "
2560 + pkgSetting.sharedUser.name + "; ignoring!");
2561 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2562 return false;
2563 }
2564 }
2565 } else {
2566 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2567 }
2568 return true;
2569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002570
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002571 public boolean performDexOpt(String packageName) {
2572 if (!mNoDexOpt) {
2573 return false;
2574 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002575
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002576 PackageParser.Package p;
2577 synchronized (mPackages) {
2578 p = mPackages.get(packageName);
2579 if (p == null || p.mDidDexOpt) {
2580 return false;
2581 }
2582 }
2583 synchronized (mInstallLock) {
2584 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2585 }
2586 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002587
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002588 static final int DEX_OPT_SKIPPED = 0;
2589 static final int DEX_OPT_PERFORMED = 1;
2590 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002591
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002592 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2593 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002594 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002595 String path = pkg.mScanPath;
2596 int ret = 0;
2597 try {
2598 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002599 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002600 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002601 pkg.mDidDexOpt = true;
2602 performed = true;
2603 }
2604 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002605 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002606 ret = -1;
2607 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002608 Slog.w(TAG, "Exception reading apk: " + path, e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002609 ret = -1;
2610 }
2611 if (ret < 0) {
2612 //error from installer
2613 return DEX_OPT_FAILED;
2614 }
2615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002616
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002617 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2618 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002619
2620 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2621 return Environment.isEncryptedFilesystemEnabled() &&
2622 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2623 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002624
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002625 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2626 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002627 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002628 + " to " + newPkg.packageName
2629 + ": old package not in system partition");
2630 return false;
2631 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002632 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002633 + " to " + newPkg.packageName
2634 + ": old package still exists");
2635 return false;
2636 }
2637 return true;
2638 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002639
2640 private File getDataPathForPackage(PackageParser.Package pkg) {
2641 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2642 File dataPath;
2643 if (useEncryptedFSDir) {
2644 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2645 } else {
2646 dataPath = new File(mAppDataDir, pkg.packageName);
2647 }
2648 return dataPath;
2649 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002650
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002651 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2652 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002653 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002654 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2655 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002656 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002657 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002658 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2659 return null;
2660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 mScanningPath = scanFile;
2662 if (pkg == null) {
2663 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2664 return null;
2665 }
2666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2668 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2669 }
2670
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002671 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 synchronized (mPackages) {
2673 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002674 Slog.w(TAG, "*************************************************");
2675 Slog.w(TAG, "Core android package being redefined. Skipping.");
2676 Slog.w(TAG, " file=" + mScanningPath);
2677 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2679 return null;
2680 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 // Set up information for our fall-back user intent resolution
2683 // activity.
2684 mPlatformPackage = pkg;
2685 pkg.mVersionCode = mSdkVersion;
2686 mAndroidApplication = pkg.applicationInfo;
2687 mResolveActivity.applicationInfo = mAndroidApplication;
2688 mResolveActivity.name = ResolverActivity.class.getName();
2689 mResolveActivity.packageName = mAndroidApplication.packageName;
2690 mResolveActivity.processName = mAndroidApplication.processName;
2691 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2692 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2693 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2694 mResolveActivity.exported = true;
2695 mResolveActivity.enabled = true;
2696 mResolveInfo.activityInfo = mResolveActivity;
2697 mResolveInfo.priority = 0;
2698 mResolveInfo.preferredOrder = 0;
2699 mResolveInfo.match = 0;
2700 mResolveComponentName = new ComponentName(
2701 mAndroidApplication.packageName, mResolveActivity.name);
2702 }
2703 }
2704
2705 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002706 TAG, "Scanning package " + pkg.packageName);
2707 if (mPackages.containsKey(pkg.packageName)
2708 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002709 Slog.w(TAG, "*************************************************");
2710 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002712 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2714 return null;
2715 }
2716
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002717 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002718 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2719 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 SharedUserSetting suid = null;
2722 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002723
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002724 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2725 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002726 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002727 pkg.mRealPackage = null;
2728 pkg.mAdoptPermissions = null;
2729 }
2730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 synchronized (mPackages) {
2732 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002733 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2734 if (mTmpSharedLibraries == null ||
2735 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2736 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2737 }
2738 int num = 0;
2739 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2740 for (int i=0; i<N; i++) {
2741 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002743 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002745 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2747 return null;
2748 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002749 mTmpSharedLibraries[num] = file;
2750 num++;
2751 }
2752 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2753 for (int i=0; i<N; i++) {
2754 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2755 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002756 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002757 + " desires unavailable shared library "
2758 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2759 } else {
2760 mTmpSharedLibraries[num] = file;
2761 num++;
2762 }
2763 }
2764 if (num > 0) {
2765 pkg.usesLibraryFiles = new String[num];
2766 System.arraycopy(mTmpSharedLibraries, 0,
2767 pkg.usesLibraryFiles, 0, num);
2768 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002769
Dianne Hackborn49237342009-08-27 20:08:01 -07002770 if (pkg.reqFeatures != null) {
2771 N = pkg.reqFeatures.size();
2772 for (int i=0; i<N; i++) {
2773 FeatureInfo fi = pkg.reqFeatures.get(i);
2774 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2775 // Don't care.
2776 continue;
2777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002778
Dianne Hackborn49237342009-08-27 20:08:01 -07002779 if (fi.name != null) {
2780 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002781 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002782 + " requires unavailable feature "
2783 + fi.name + "; failing!");
2784 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2785 return null;
2786 }
2787 }
2788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 }
2790 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 if (pkg.mSharedUserId != null) {
2793 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2794 pkg.applicationInfo.flags, true);
2795 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002796 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 + " for shared user failed");
2798 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2799 return null;
2800 }
2801 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2802 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2803 + suid.userId + "): packages=" + suid.packages);
2804 }
2805 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002806
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002807 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002808 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002809 Log.w(TAG, "WAITING FOR DEBUGGER");
2810 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002811 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2812 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002813 }
2814 }
2815
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002816 // Check if we are renaming from an original package name.
2817 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002818 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002819 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002820 // This package may need to be renamed to a previously
2821 // installed name. Let's check on that...
2822 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002823 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002824 // This package had originally been installed as the
2825 // original name, and we have already taken care of
2826 // transitioning to the new one. Just update the new
2827 // one to continue using the old name.
2828 realName = pkg.mRealPackage;
2829 if (!pkg.packageName.equals(renamed)) {
2830 // Callers into this function may have already taken
2831 // care of renaming the package; only do it here if
2832 // it is not already done.
2833 pkg.setPackageName(renamed);
2834 }
2835
Dianne Hackbornc1552392010-03-03 16:19:01 -08002836 } else {
2837 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2838 if ((origPackage=mSettings.peekPackageLP(
2839 pkg.mOriginalPackages.get(i))) != null) {
2840 // We do have the package already installed under its
2841 // original name... should we use it?
2842 if (!verifyPackageUpdate(origPackage, pkg)) {
2843 // New package is not compatible with original.
2844 origPackage = null;
2845 continue;
2846 } else if (origPackage.sharedUser != null) {
2847 // Make sure uid is compatible between packages.
2848 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002849 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002850 + " to " + pkg.packageName + ": old uid "
2851 + origPackage.sharedUser.name
2852 + " differs from " + pkg.mSharedUserId);
2853 origPackage = null;
2854 continue;
2855 }
2856 } else {
2857 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2858 + pkg.packageName + " to old name " + origPackage.name);
2859 }
2860 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002861 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002862 }
2863 }
2864 }
2865
2866 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002867 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002868 + " was transferred to another, but its .apk remains");
2869 }
2870
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002871 // Just create the setting, don't add it yet. For already existing packages
2872 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002873 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 destResourceFile, pkg.applicationInfo.flags, true, false);
2875 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002876 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2878 return null;
2879 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002880
2881 if (pkgSetting.origPackage != null) {
2882 // If we are first transitioning from an original package,
2883 // fix up the new package's name now. We need to do this after
2884 // looking up the package under its new name, so getPackageLP
2885 // can take care of fiddling things correctly.
2886 pkg.setPackageName(origPackage.name);
2887
2888 // File a report about this.
2889 String msg = "New package " + pkgSetting.realName
2890 + " renamed to replace old package " + pkgSetting.name;
2891 reportSettingsProblem(Log.WARN, msg);
2892
2893 // Make a note of it.
2894 mTransferedPackages.add(origPackage.name);
2895
2896 // No longer need to retain this.
2897 pkgSetting.origPackage = null;
2898 }
2899
2900 if (realName != null) {
2901 // Make a note of it.
2902 mTransferedPackages.add(pkg.packageName);
2903 }
2904
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002905 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 pkg.applicationInfo.uid = pkgSetting.userId;
2910 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002911
2912 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002914 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2916 return null;
2917 }
2918 // The signature has changed, but this package is in the system
2919 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002920 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 // However... if this package is part of a shared user, but it
2922 // doesn't match the signature of the shared user, let's fail.
2923 // What this means is that you can't change the signatures
2924 // associated with an overall shared user, which doesn't seem all
2925 // that unreasonable.
2926 if (pkgSetting.sharedUser != null) {
2927 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2928 pkg.mSignatures, false)) {
2929 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2930 return null;
2931 }
2932 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002933 // File a report about this.
2934 String msg = "System package " + pkg.packageName
2935 + " signature changed; retaining data.";
2936 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002938
The Android Open Source Project10592532009-03-18 17:39:46 -07002939 // Verify that this new package doesn't have any content providers
2940 // that conflict with existing packages. Only do this if the
2941 // package isn't already installed, since we don't want to break
2942 // things that are installed.
2943 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2944 int N = pkg.providers.size();
2945 int i;
2946 for (i=0; i<N; i++) {
2947 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002948 if (p.info.authority != null) {
2949 String names[] = p.info.authority.split(";");
2950 for (int j = 0; j < names.length; j++) {
2951 if (mProviders.containsKey(names[j])) {
2952 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002953 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002954 " (in package " + pkg.applicationInfo.packageName +
2955 ") is already used by "
2956 + ((other != null && other.getComponentName() != null)
2957 ? other.getComponentName().getPackageName() : "?"));
2958 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2959 return null;
2960 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002961 }
2962 }
2963 }
2964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 }
2966
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002967 final String pkgName = pkg.packageName;
2968
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002969 if (pkg.mAdoptPermissions != null) {
2970 // This package wants to adopt ownership of permissions from
2971 // another package.
2972 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2973 String origName = pkg.mAdoptPermissions.get(i);
2974 PackageSetting orig = mSettings.peekPackageLP(origName);
2975 if (orig != null) {
2976 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002977 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002978 + origName + " to " + pkg.packageName);
2979 mSettings.transferPermissions(origName, pkg.packageName);
2980 }
2981 }
2982 }
2983 }
2984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 long scanFileTime = scanFile.lastModified();
2986 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2987 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2988 pkg.applicationInfo.processName = fixProcessName(
2989 pkg.applicationInfo.packageName,
2990 pkg.applicationInfo.processName,
2991 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992
2993 File dataPath;
2994 if (mPlatformPackage == pkg) {
2995 // The system package is special.
2996 dataPath = new File (Environment.getDataDirectory(), "system");
2997 pkg.applicationInfo.dataDir = dataPath.getPath();
2998 } else {
2999 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003000 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003001 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003002
3003 boolean uidError = false;
3004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 if (dataPath.exists()) {
3006 mOutPermissions[1] = 0;
3007 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3008 if (mOutPermissions[1] == pkg.applicationInfo.uid
3009 || !Process.supportsProcesses()) {
3010 pkg.applicationInfo.dataDir = dataPath.getPath();
3011 } else {
3012 boolean recovered = false;
3013 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3014 // If this is a system app, we can at least delete its
3015 // current data so the application will still work.
3016 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003017 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003018 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 // Old data gone!
3020 String msg = "System package " + pkg.packageName
3021 + " has changed from uid: "
3022 + mOutPermissions[1] + " to "
3023 + pkg.applicationInfo.uid + "; old data erased";
3024 reportSettingsProblem(Log.WARN, msg);
3025 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003028 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 pkg.applicationInfo.uid);
3030 if (ret == -1) {
3031 // Ack should not happen!
3032 msg = "System package " + pkg.packageName
3033 + " could not have data directory re-created after delete.";
3034 reportSettingsProblem(Log.WARN, msg);
3035 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3036 return null;
3037 }
3038 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 if (!recovered) {
3041 mHasSystemUidErrors = true;
3042 }
3043 }
3044 if (!recovered) {
3045 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3046 + pkg.applicationInfo.uid + "/fs_"
3047 + mOutPermissions[1];
3048 String msg = "Package " + pkg.packageName
3049 + " has mismatched uid: "
3050 + mOutPermissions[1] + " on disk, "
3051 + pkg.applicationInfo.uid + " in settings";
3052 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003053 mSettings.mReadMessages.append(msg);
3054 mSettings.mReadMessages.append('\n');
3055 uidError = true;
3056 if (!pkgSetting.uidError) {
3057 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 }
3060 }
3061 }
3062 pkg.applicationInfo.dataDir = dataPath.getPath();
3063 } else {
3064 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3065 Log.v(TAG, "Want this data dir: " + dataPath);
3066 //invoke installer to do the actual installation
3067 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003068 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 pkg.applicationInfo.uid);
3070 if(ret < 0) {
3071 // Error from installer
3072 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3073 return null;
3074 }
3075 } else {
3076 dataPath.mkdirs();
3077 if (dataPath.exists()) {
3078 FileUtils.setPermissions(
3079 dataPath.toString(),
3080 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3081 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3082 }
3083 }
3084 if (dataPath.exists()) {
3085 pkg.applicationInfo.dataDir = dataPath.getPath();
3086 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003087 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 pkg.applicationInfo.dataDir = null;
3089 }
3090 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003091
3092 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 }
3094
3095 // Perform shared library installation and dex validation and
3096 // optimization, if this is not a system app.
3097 if (mInstaller != null) {
3098 String path = scanFile.getPath();
3099 if (scanFileNewer) {
3100 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003101 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3102 if (err != PackageManager.INSTALL_SUCCEEDED) {
3103 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 return null;
3105 }
3106 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003107 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003108
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003109 if ((scanMode&SCAN_NO_DEX) == 0) {
3110 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3112 return null;
3113 }
3114 }
3115 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117 if (mFactoryTest && pkg.requestedPermissions.contains(
3118 android.Manifest.permission.FACTORY_TEST)) {
3119 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3120 }
3121
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003122 // Request the ActivityManager to kill the process(only for existing packages)
3123 // so that we do not end up in a confused state while the user is still using the older
3124 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003125 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003126 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003127 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003128 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003131 // We don't expect installation to fail beyond this point,
3132 if ((scanMode&SCAN_MONITOR) != 0) {
3133 mAppDirs.put(pkg.mPath, pkg);
3134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003136 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003138 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003139 // Make sure we don't accidentally delete its data.
3140 mSettings.mPackagesToBeCleaned.remove(pkgName);
3141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 int N = pkg.providers.size();
3143 StringBuilder r = null;
3144 int i;
3145 for (i=0; i<N; i++) {
3146 PackageParser.Provider p = pkg.providers.get(i);
3147 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3148 p.info.processName, pkg.applicationInfo.uid);
3149 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3150 p.info.name), p);
3151 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003152 if (p.info.authority != null) {
3153 String names[] = p.info.authority.split(";");
3154 p.info.authority = null;
3155 for (int j = 0; j < names.length; j++) {
3156 if (j == 1 && p.syncable) {
3157 // We only want the first authority for a provider to possibly be
3158 // syncable, so if we already added this provider using a different
3159 // authority clear the syncable flag. We copy the provider before
3160 // changing it because the mProviders object contains a reference
3161 // to a provider that we don't want to change.
3162 // Only do this for the second authority since the resulting provider
3163 // object can be the same for all future authorities for this provider.
3164 p = new PackageParser.Provider(p);
3165 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003167 if (!mProviders.containsKey(names[j])) {
3168 mProviders.put(names[j], p);
3169 if (p.info.authority == null) {
3170 p.info.authority = names[j];
3171 } else {
3172 p.info.authority = p.info.authority + ";" + names[j];
3173 }
3174 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3175 Log.d(TAG, "Registered content provider: " + names[j] +
3176 ", className = " + p.info.name +
3177 ", isSyncable = " + p.info.isSyncable);
3178 } else {
3179 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003180 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003181 " (in package " + pkg.applicationInfo.packageName +
3182 "): name already used by "
3183 + ((other != null && other.getComponentName() != null)
3184 ? other.getComponentName().getPackageName() : "?"));
3185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 }
3187 }
3188 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3189 if (r == null) {
3190 r = new StringBuilder(256);
3191 } else {
3192 r.append(' ');
3193 }
3194 r.append(p.info.name);
3195 }
3196 }
3197 if (r != null) {
3198 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3199 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 N = pkg.services.size();
3202 r = null;
3203 for (i=0; i<N; i++) {
3204 PackageParser.Service s = pkg.services.get(i);
3205 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3206 s.info.processName, pkg.applicationInfo.uid);
3207 mServices.addService(s);
3208 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3209 if (r == null) {
3210 r = new StringBuilder(256);
3211 } else {
3212 r.append(' ');
3213 }
3214 r.append(s.info.name);
3215 }
3216 }
3217 if (r != null) {
3218 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3219 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 N = pkg.receivers.size();
3222 r = null;
3223 for (i=0; i<N; i++) {
3224 PackageParser.Activity a = pkg.receivers.get(i);
3225 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3226 a.info.processName, pkg.applicationInfo.uid);
3227 mReceivers.addActivity(a, "receiver");
3228 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3229 if (r == null) {
3230 r = new StringBuilder(256);
3231 } else {
3232 r.append(' ');
3233 }
3234 r.append(a.info.name);
3235 }
3236 }
3237 if (r != null) {
3238 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3239 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241 N = pkg.activities.size();
3242 r = null;
3243 for (i=0; i<N; i++) {
3244 PackageParser.Activity a = pkg.activities.get(i);
3245 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3246 a.info.processName, pkg.applicationInfo.uid);
3247 mActivities.addActivity(a, "activity");
3248 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3249 if (r == null) {
3250 r = new StringBuilder(256);
3251 } else {
3252 r.append(' ');
3253 }
3254 r.append(a.info.name);
3255 }
3256 }
3257 if (r != null) {
3258 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3259 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 N = pkg.permissionGroups.size();
3262 r = null;
3263 for (i=0; i<N; i++) {
3264 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3265 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3266 if (cur == null) {
3267 mPermissionGroups.put(pg.info.name, pg);
3268 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3269 if (r == null) {
3270 r = new StringBuilder(256);
3271 } else {
3272 r.append(' ');
3273 }
3274 r.append(pg.info.name);
3275 }
3276 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003277 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 + pg.info.packageName + " ignored: original from "
3279 + cur.info.packageName);
3280 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3281 if (r == null) {
3282 r = new StringBuilder(256);
3283 } else {
3284 r.append(' ');
3285 }
3286 r.append("DUP:");
3287 r.append(pg.info.name);
3288 }
3289 }
3290 }
3291 if (r != null) {
3292 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3293 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 N = pkg.permissions.size();
3296 r = null;
3297 for (i=0; i<N; i++) {
3298 PackageParser.Permission p = pkg.permissions.get(i);
3299 HashMap<String, BasePermission> permissionMap =
3300 p.tree ? mSettings.mPermissionTrees
3301 : mSettings.mPermissions;
3302 p.group = mPermissionGroups.get(p.info.group);
3303 if (p.info.group == null || p.group != null) {
3304 BasePermission bp = permissionMap.get(p.info.name);
3305 if (bp == null) {
3306 bp = new BasePermission(p.info.name, p.info.packageName,
3307 BasePermission.TYPE_NORMAL);
3308 permissionMap.put(p.info.name, bp);
3309 }
3310 if (bp.perm == null) {
3311 if (bp.sourcePackage == null
3312 || bp.sourcePackage.equals(p.info.packageName)) {
3313 BasePermission tree = findPermissionTreeLP(p.info.name);
3314 if (tree == null
3315 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003316 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 bp.perm = p;
3318 bp.uid = pkg.applicationInfo.uid;
3319 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3320 if (r == null) {
3321 r = new StringBuilder(256);
3322 } else {
3323 r.append(' ');
3324 }
3325 r.append(p.info.name);
3326 }
3327 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003328 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 + p.info.packageName + " ignored: base tree "
3330 + tree.name + " is from package "
3331 + tree.sourcePackage);
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: original from "
3336 + bp.sourcePackage);
3337 }
3338 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3339 if (r == null) {
3340 r = new StringBuilder(256);
3341 } else {
3342 r.append(' ');
3343 }
3344 r.append("DUP:");
3345 r.append(p.info.name);
3346 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003347 if (bp.perm == p) {
3348 bp.protectionLevel = p.info.protectionLevel;
3349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003351 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 + p.info.packageName + " ignored: no group "
3353 + p.group);
3354 }
3355 }
3356 if (r != null) {
3357 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3358 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 N = pkg.instrumentation.size();
3361 r = null;
3362 for (i=0; i<N; i++) {
3363 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3364 a.info.packageName = pkg.applicationInfo.packageName;
3365 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3366 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3367 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003368 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3370 if (r == null) {
3371 r = new StringBuilder(256);
3372 } else {
3373 r.append(' ');
3374 }
3375 r.append(a.info.name);
3376 }
3377 }
3378 if (r != null) {
3379 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3380 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003381
Dianne Hackborn854060af2009-07-09 18:14:31 -07003382 if (pkg.protectedBroadcasts != null) {
3383 N = pkg.protectedBroadcasts.size();
3384 for (i=0; i<N; i++) {
3385 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3386 }
3387 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 pkgSetting.setTimeStamp(scanFileTime);
3390 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 return pkg;
3393 }
3394
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003395 private void killApplication(String pkgName, int uid) {
3396 // Request the ActivityManager to kill the process(only for existing packages)
3397 // so that we do not end up in a confused state while the user is still using the older
3398 // version of the application while the new one gets installed.
3399 IActivityManager am = ActivityManagerNative.getDefault();
3400 if (am != null) {
3401 try {
3402 am.killApplicationWithUid(pkgName, uid);
3403 } catch (RemoteException e) {
3404 }
3405 }
3406 }
3407
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003408 // The following constants are returned by cachePackageSharedLibsForAbiLI
3409 // to indicate if native shared libraries were found in the package.
3410 // Values are:
3411 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3412 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3413 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3414 // in package (and not installed)
3415 //
3416 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3417 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3418 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003420 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3421 // and automatically copy them to /data/data/<appname>/lib if present.
3422 //
3423 // NOTE: this method may throw an IOException if the library cannot
3424 // be copied to its final destination, e.g. if there isn't enough
3425 // room left on the data partition, or a ZipException if the package
3426 // file is malformed.
3427 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003428 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3429 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003430 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3431 final String apkLib = "lib/";
3432 final int apkLibLen = apkLib.length();
3433 final int cpuAbiLen = cpuAbi.length();
3434 final String libPrefix = "lib";
3435 final int libPrefixLen = libPrefix.length();
3436 final String libSuffix = ".so";
3437 final int libSuffixLen = libSuffix.length();
3438 boolean hasNativeLibraries = false;
3439 boolean installedNativeLibraries = false;
3440
3441 // the minimum length of a valid native shared library of the form
3442 // lib/<something>/lib<name>.so.
3443 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3444
3445 ZipFile zipFile = new ZipFile(scanFile);
3446 Enumeration<ZipEntry> entries =
3447 (Enumeration<ZipEntry>) zipFile.entries();
3448
3449 while (entries.hasMoreElements()) {
3450 ZipEntry entry = entries.nextElement();
3451 // skip directories
3452 if (entry.isDirectory()) {
3453 continue;
3454 }
3455 String entryName = entry.getName();
3456
3457 // check that the entry looks like lib/<something>/lib<name>.so
3458 // here, but don't check the ABI just yet.
3459 //
3460 // - must be sufficiently long
3461 // - must end with libSuffix, i.e. ".so"
3462 // - must start with apkLib, i.e. "lib/"
3463 if (entryName.length() < minEntryLen ||
3464 !entryName.endsWith(libSuffix) ||
3465 !entryName.startsWith(apkLib) ) {
3466 continue;
3467 }
3468
3469 // file name must start with libPrefix, i.e. "lib"
3470 int lastSlash = entryName.lastIndexOf('/');
3471
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003472 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003473 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3474 continue;
3475 }
3476
3477 hasNativeLibraries = true;
3478
3479 // check the cpuAbi now, between lib/ and /lib<name>.so
3480 //
3481 if (lastSlash != apkLibLen + cpuAbiLen ||
3482 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3483 continue;
3484
3485 // extract the library file name, ensure it doesn't contain
3486 // weird characters. we're guaranteed here that it doesn't contain
3487 // a directory separator though.
3488 String libFileName = entryName.substring(lastSlash+1);
3489 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3490 continue;
3491 }
3492
3493 installedNativeLibraries = true;
3494
3495 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3496 File.separator + libFileName;
3497 File sharedLibraryFile = new File(sharedLibraryFilePath);
3498 if (! sharedLibraryFile.exists() ||
3499 sharedLibraryFile.length() != entry.getSize() ||
3500 sharedLibraryFile.lastModified() != entry.getTime()) {
3501 if (Config.LOGD) {
3502 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003504 if (mInstaller == null) {
3505 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003506 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003507 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003508 sharedLibraryFile);
3509 }
3510 }
3511 if (!hasNativeLibraries)
3512 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3513
3514 if (!installedNativeLibraries)
3515 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3516
3517 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3518 }
3519
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003520 // Find the gdbserver executable program in a package at
3521 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3522 //
3523 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3524 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3525 //
3526 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3527 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3528 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3529 final String GDBSERVER = "gdbserver";
3530 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3531
3532 ZipFile zipFile = new ZipFile(scanFile);
3533 Enumeration<ZipEntry> entries =
3534 (Enumeration<ZipEntry>) zipFile.entries();
3535
3536 while (entries.hasMoreElements()) {
3537 ZipEntry entry = entries.nextElement();
3538 // skip directories
3539 if (entry.isDirectory()) {
3540 continue;
3541 }
3542 String entryName = entry.getName();
3543
3544 if (!entryName.equals(apkGdbServerPath)) {
3545 continue;
3546 }
3547
3548 String installGdbServerPath = installGdbServerDir.getPath() +
3549 "/" + GDBSERVER;
3550 File installGdbServerFile = new File(installGdbServerPath);
3551 if (! installGdbServerFile.exists() ||
3552 installGdbServerFile.length() != entry.getSize() ||
3553 installGdbServerFile.lastModified() != entry.getTime()) {
3554 if (Config.LOGD) {
3555 Log.d(TAG, "Caching gdbserver " + entry.getName());
3556 }
3557 if (mInstaller == null) {
3558 installGdbServerDir.mkdir();
3559 }
3560 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3561 installGdbServerFile);
3562 }
3563 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3564 }
3565 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3566 }
3567
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003568 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3569 // and copy them to /data/data/<appname>/lib.
3570 //
3571 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3572 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3573 // one if ro.product.cpu.abi2 is defined.
3574 //
3575 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3576 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003577 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003578 try {
3579 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3580
3581 // some architectures are capable of supporting several CPU ABIs
3582 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3583 // this is indicated by the definition of the ro.product.cpu.abi2
3584 // system property.
3585 //
3586 // only scan the package twice in case of ABI mismatch
3587 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003588 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003589 if (cpuAbi2 != null) {
3590 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003592
3593 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003594 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003595 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003597
3598 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3599 cpuAbi = cpuAbi2;
3600 }
3601 }
3602
3603 // for debuggable packages, also extract gdbserver from lib/<abi>
3604 // into /data/data/<appname>/lib too.
3605 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3606 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3607 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3608 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3609 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003612 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003613 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003614 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003616 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003617 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003619 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 }
3621
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003622 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003624 File binaryDir,
3625 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 InputStream inputStream = zipFile.getInputStream(entry);
3627 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003628 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003630 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 // now need to be left as world readable and owned by the system.
3632 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3633 ! tempFile.setLastModified(entry.getTime()) ||
3634 FileUtils.setPermissions(tempFilePath,
3635 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003636 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003638 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 // Failed to properly write file.
3640 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003641 throw new IOException("Couldn't create cached binary "
3642 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 }
3644 } finally {
3645 inputStream.close();
3646 }
3647 }
3648
3649 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3650 if (chatty && Config.LOGD) Log.d(
3651 TAG, "Removing package " + pkg.applicationInfo.packageName );
3652
3653 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 mPackages.remove(pkg.applicationInfo.packageName);
3657 if (pkg.mPath != null) {
3658 mAppDirs.remove(pkg.mPath);
3659 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 PackageSetting ps = (PackageSetting)pkg.mExtras;
3662 if (ps != null && ps.sharedUser != null) {
3663 // XXX don't do this until the data is removed.
3664 if (false) {
3665 ps.sharedUser.packages.remove(ps);
3666 if (ps.sharedUser.packages.size() == 0) {
3667 // Remove.
3668 }
3669 }
3670 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 int N = pkg.providers.size();
3673 StringBuilder r = null;
3674 int i;
3675 for (i=0; i<N; i++) {
3676 PackageParser.Provider p = pkg.providers.get(i);
3677 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3678 p.info.name));
3679 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 /* The is another ContentProvider with this authority when
3682 * this app was installed so this authority is null,
3683 * Ignore it as we don't have to unregister the provider.
3684 */
3685 continue;
3686 }
3687 String names[] = p.info.authority.split(";");
3688 for (int j = 0; j < names.length; j++) {
3689 if (mProviders.get(names[j]) == p) {
3690 mProviders.remove(names[j]);
3691 if (chatty && Config.LOGD) Log.d(
3692 TAG, "Unregistered content provider: " + names[j] +
3693 ", className = " + p.info.name +
3694 ", isSyncable = " + p.info.isSyncable);
3695 }
3696 }
3697 if (chatty) {
3698 if (r == null) {
3699 r = new StringBuilder(256);
3700 } else {
3701 r.append(' ');
3702 }
3703 r.append(p.info.name);
3704 }
3705 }
3706 if (r != null) {
3707 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 N = pkg.services.size();
3711 r = null;
3712 for (i=0; i<N; i++) {
3713 PackageParser.Service s = pkg.services.get(i);
3714 mServices.removeService(s);
3715 if (chatty) {
3716 if (r == null) {
3717 r = new StringBuilder(256);
3718 } else {
3719 r.append(' ');
3720 }
3721 r.append(s.info.name);
3722 }
3723 }
3724 if (r != null) {
3725 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728 N = pkg.receivers.size();
3729 r = null;
3730 for (i=0; i<N; i++) {
3731 PackageParser.Activity a = pkg.receivers.get(i);
3732 mReceivers.removeActivity(a, "receiver");
3733 if (chatty) {
3734 if (r == null) {
3735 r = new StringBuilder(256);
3736 } else {
3737 r.append(' ');
3738 }
3739 r.append(a.info.name);
3740 }
3741 }
3742 if (r != null) {
3743 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 N = pkg.activities.size();
3747 r = null;
3748 for (i=0; i<N; i++) {
3749 PackageParser.Activity a = pkg.activities.get(i);
3750 mActivities.removeActivity(a, "activity");
3751 if (chatty) {
3752 if (r == null) {
3753 r = new StringBuilder(256);
3754 } else {
3755 r.append(' ');
3756 }
3757 r.append(a.info.name);
3758 }
3759 }
3760 if (r != null) {
3761 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3762 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 N = pkg.permissions.size();
3765 r = null;
3766 for (i=0; i<N; i++) {
3767 PackageParser.Permission p = pkg.permissions.get(i);
3768 boolean tree = false;
3769 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3770 if (bp == null) {
3771 tree = true;
3772 bp = mSettings.mPermissionTrees.get(p.info.name);
3773 }
3774 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003775 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 if (chatty) {
3777 if (r == null) {
3778 r = new StringBuilder(256);
3779 } else {
3780 r.append(' ');
3781 }
3782 r.append(p.info.name);
3783 }
3784 }
3785 }
3786 if (r != null) {
3787 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3788 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 N = pkg.instrumentation.size();
3791 r = null;
3792 for (i=0; i<N; i++) {
3793 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003794 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 if (chatty) {
3796 if (r == null) {
3797 r = new StringBuilder(256);
3798 } else {
3799 r.append(' ');
3800 }
3801 r.append(a.info.name);
3802 }
3803 }
3804 if (r != null) {
3805 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3806 }
3807 }
3808 }
3809
3810 private static final boolean isPackageFilename(String name) {
3811 return name != null && name.endsWith(".apk");
3812 }
3813
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003814 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3815 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3816 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3817 return true;
3818 }
3819 }
3820 return false;
3821 }
3822
3823 private void updatePermissionsLP(String changingPkg,
3824 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 // Make sure there are no dangling permission trees.
3826 Iterator<BasePermission> it = mSettings.mPermissionTrees
3827 .values().iterator();
3828 while (it.hasNext()) {
3829 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003830 if (bp.packageSetting == null) {
3831 // We may not yet have parsed the package, so just see if
3832 // we still know about its settings.
3833 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3834 }
3835 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003836 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 + " from package " + bp.sourcePackage);
3838 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003839 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3840 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3841 Slog.i(TAG, "Removing old permission tree: " + bp.name
3842 + " from package " + bp.sourcePackage);
3843 grantPermissions = true;
3844 it.remove();
3845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 }
3847 }
3848
3849 // Make sure all dynamic permissions have been assigned to a package,
3850 // and make sure there are no dangling permissions.
3851 it = mSettings.mPermissions.values().iterator();
3852 while (it.hasNext()) {
3853 BasePermission bp = it.next();
3854 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3855 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3856 + bp.name + " pkg=" + bp.sourcePackage
3857 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003858 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 BasePermission tree = findPermissionTreeLP(bp.name);
3860 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003861 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 bp.perm = new PackageParser.Permission(tree.perm.owner,
3863 new PermissionInfo(bp.pendingInfo));
3864 bp.perm.info.packageName = tree.perm.info.packageName;
3865 bp.perm.info.name = bp.name;
3866 bp.uid = tree.uid;
3867 }
3868 }
3869 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003870 if (bp.packageSetting == null) {
3871 // We may not yet have parsed the package, so just see if
3872 // we still know about its settings.
3873 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3874 }
3875 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003876 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 + " from package " + bp.sourcePackage);
3878 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003879 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3880 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3881 Slog.i(TAG, "Removing old permission: " + bp.name
3882 + " from package " + bp.sourcePackage);
3883 grantPermissions = true;
3884 it.remove();
3885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 }
3887 }
3888
3889 // Now update the permissions for all packages, in particular
3890 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003891 if (grantPermissions) {
3892 for (PackageParser.Package pkg : mPackages.values()) {
3893 if (pkg != pkgInfo) {
3894 grantPermissionsLP(pkg, false);
3895 }
3896 }
3897 }
3898
3899 if (pkgInfo != null) {
3900 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 }
3902 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3905 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3906 if (ps == null) {
3907 return;
3908 }
3909 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003910 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 if (replace) {
3913 ps.permissionsFixed = false;
3914 if (gp == ps) {
3915 gp.grantedPermissions.clear();
3916 gp.gids = mGlobalGids;
3917 }
3918 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 if (gp.gids == null) {
3921 gp.gids = mGlobalGids;
3922 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 final int N = pkg.requestedPermissions.size();
3925 for (int i=0; i<N; i++) {
3926 String name = pkg.requestedPermissions.get(i);
3927 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 if (false) {
3929 if (gp != ps) {
3930 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003931 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 }
3933 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003934 if (bp != null && bp.packageSetting != null) {
3935 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003937 boolean allowedSig = false;
3938 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3939 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 allowed = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003941 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3942 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3943 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003945 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003947 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3949 // For updated system applications, the signatureOrSystem permission
3950 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003951 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3953 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3954 if(sysPs.grantedPermissions.contains(perm)) {
3955 allowed = true;
3956 } else {
3957 allowed = false;
3958 }
3959 } else {
3960 allowed = true;
3961 }
3962 }
3963 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003964 if (allowed) {
3965 allowedSig = true;
3966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 } else {
3968 allowed = false;
3969 }
3970 if (false) {
3971 if (gp != ps) {
3972 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3973 }
3974 }
3975 if (allowed) {
3976 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3977 && ps.permissionsFixed) {
3978 // If this is an existing, non-system package, then
3979 // we can't add any new permissions to it.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003980 if (!allowedSig && !gp.loadedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003982 // Except... if this is a permission that was added
3983 // to the platform (note: need to only do this when
3984 // updating the platform).
3985 final int NP = PackageParser.NEW_PERMISSIONS.length;
3986 for (int ip=0; ip<NP; ip++) {
3987 final PackageParser.NewPermissionInfo npi
3988 = PackageParser.NEW_PERMISSIONS[ip];
3989 if (npi.name.equals(perm)
3990 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3991 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003992 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003993 + pkg.packageName);
3994 break;
3995 }
3996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 }
3998 }
3999 if (allowed) {
4000 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004001 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 gp.grantedPermissions.add(perm);
4003 gp.gids = appendInts(gp.gids, bp.gids);
4004 }
4005 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004006 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 + " to package " + pkg.packageName
4008 + " because it was previously installed without");
4009 }
4010 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004011 if (gp.grantedPermissions.remove(perm)) {
4012 changedPermission = true;
4013 gp.gids = removeInts(gp.gids, bp.gids);
4014 Slog.i(TAG, "Un-granting permission " + perm
4015 + " from package " + pkg.packageName
4016 + " (protectionLevel=" + bp.protectionLevel
4017 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4018 + ")");
4019 } else {
4020 Slog.w(TAG, "Not granting permission " + perm
4021 + " to package " + pkg.packageName
4022 + " (protectionLevel=" + bp.protectionLevel
4023 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4024 + ")");
4025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 }
4027 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004028 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 + " in package " + pkg.packageName);
4030 }
4031 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004032
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004033 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004034 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4035 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 // This is the first that we have heard about this package, so the
4037 // permissions we have now selected are fixed until explicitly
4038 // changed.
4039 ps.permissionsFixed = true;
4040 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
4041 }
4042 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 private final class ActivityIntentResolver
4045 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004046 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004048 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 }
4050
Mihai Preda074edef2009-05-18 17:13:31 +02004051 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004052 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004053 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4055 }
4056
Mihai Predaeae850c2009-05-13 10:13:48 +02004057 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4058 ArrayList<PackageParser.Activity> packageActivities) {
4059 if (packageActivities == null) {
4060 return null;
4061 }
4062 mFlags = flags;
4063 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4064 int N = packageActivities.size();
4065 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4066 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004067
4068 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004069 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004070 intentFilters = packageActivities.get(i).intents;
4071 if (intentFilters != null && intentFilters.size() > 0) {
4072 listCut.add(intentFilters);
4073 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004074 }
4075 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4076 }
4077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004079 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 if (SHOW_INFO || Config.LOGV) Log.v(
4081 TAG, " " + type + " " +
4082 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4083 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4084 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004085 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4087 if (SHOW_INFO || Config.LOGV) {
4088 Log.v(TAG, " IntentFilter:");
4089 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4090 }
4091 if (!intent.debugCheck()) {
4092 Log.w(TAG, "==> For Activity " + a.info.name);
4093 }
4094 addFilter(intent);
4095 }
4096 }
4097
4098 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004099 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 if (SHOW_INFO || Config.LOGV) Log.v(
4101 TAG, " " + type + " " +
4102 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4103 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4104 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004105 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4107 if (SHOW_INFO || Config.LOGV) {
4108 Log.v(TAG, " IntentFilter:");
4109 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4110 }
4111 removeFilter(intent);
4112 }
4113 }
4114
4115 @Override
4116 protected boolean allowFilterResult(
4117 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4118 ActivityInfo filterAi = filter.activity.info;
4119 for (int i=dest.size()-1; i>=0; i--) {
4120 ActivityInfo destAi = dest.get(i).activityInfo;
4121 if (destAi.name == filterAi.name
4122 && destAi.packageName == filterAi.packageName) {
4123 return false;
4124 }
4125 }
4126 return true;
4127 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004130 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4131 return info.activity.owner.packageName;
4132 }
4133
4134 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4136 int match) {
4137 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4138 return null;
4139 }
4140 final PackageParser.Activity activity = info.activity;
4141 if (mSafeMode && (activity.info.applicationInfo.flags
4142 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4143 return null;
4144 }
4145 final ResolveInfo res = new ResolveInfo();
4146 res.activityInfo = PackageParser.generateActivityInfo(activity,
4147 mFlags);
4148 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4149 res.filter = info;
4150 }
4151 res.priority = info.getPriority();
4152 res.preferredOrder = activity.owner.mPreferredOrder;
4153 //System.out.println("Result: " + res.activityInfo.className +
4154 // " = " + res.priority);
4155 res.match = match;
4156 res.isDefault = info.hasDefault;
4157 res.labelRes = info.labelRes;
4158 res.nonLocalizedLabel = info.nonLocalizedLabel;
4159 res.icon = info.icon;
4160 return res;
4161 }
4162
4163 @Override
4164 protected void sortResults(List<ResolveInfo> results) {
4165 Collections.sort(results, mResolvePrioritySorter);
4166 }
4167
4168 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004169 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004171 out.print(prefix); out.print(
4172 Integer.toHexString(System.identityHashCode(filter.activity)));
4173 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004174 out.print(filter.activity.getComponentShortName());
4175 out.print(" filter ");
4176 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177 }
4178
4179// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4180// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4181// final List<ResolveInfo> retList = Lists.newArrayList();
4182// while (i.hasNext()) {
4183// final ResolveInfo resolveInfo = i.next();
4184// if (isEnabledLP(resolveInfo.activityInfo)) {
4185// retList.add(resolveInfo);
4186// }
4187// }
4188// return retList;
4189// }
4190
4191 // Keys are String (activity class name), values are Activity.
4192 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4193 = new HashMap<ComponentName, PackageParser.Activity>();
4194 private int mFlags;
4195 }
4196
4197 private final class ServiceIntentResolver
4198 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004199 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004201 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202 }
4203
Mihai Preda074edef2009-05-18 17:13:31 +02004204 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004206 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4208 }
4209
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004210 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4211 ArrayList<PackageParser.Service> packageServices) {
4212 if (packageServices == null) {
4213 return null;
4214 }
4215 mFlags = flags;
4216 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4217 int N = packageServices.size();
4218 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4219 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4220
4221 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4222 for (int i = 0; i < N; ++i) {
4223 intentFilters = packageServices.get(i).intents;
4224 if (intentFilters != null && intentFilters.size() > 0) {
4225 listCut.add(intentFilters);
4226 }
4227 }
4228 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4229 }
4230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004231 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004232 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233 if (SHOW_INFO || Config.LOGV) Log.v(
4234 TAG, " " + (s.info.nonLocalizedLabel != null
4235 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4236 if (SHOW_INFO || Config.LOGV) Log.v(
4237 TAG, " Class=" + s.info.name);
4238 int NI = s.intents.size();
4239 int j;
4240 for (j=0; j<NI; j++) {
4241 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4242 if (SHOW_INFO || Config.LOGV) {
4243 Log.v(TAG, " IntentFilter:");
4244 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4245 }
4246 if (!intent.debugCheck()) {
4247 Log.w(TAG, "==> For Service " + s.info.name);
4248 }
4249 addFilter(intent);
4250 }
4251 }
4252
4253 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004254 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004255 if (SHOW_INFO || Config.LOGV) Log.v(
4256 TAG, " " + (s.info.nonLocalizedLabel != null
4257 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4258 if (SHOW_INFO || Config.LOGV) Log.v(
4259 TAG, " Class=" + s.info.name);
4260 int NI = s.intents.size();
4261 int j;
4262 for (j=0; j<NI; j++) {
4263 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4264 if (SHOW_INFO || Config.LOGV) {
4265 Log.v(TAG, " IntentFilter:");
4266 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4267 }
4268 removeFilter(intent);
4269 }
4270 }
4271
4272 @Override
4273 protected boolean allowFilterResult(
4274 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4275 ServiceInfo filterSi = filter.service.info;
4276 for (int i=dest.size()-1; i>=0; i--) {
4277 ServiceInfo destAi = dest.get(i).serviceInfo;
4278 if (destAi.name == filterSi.name
4279 && destAi.packageName == filterSi.packageName) {
4280 return false;
4281 }
4282 }
4283 return true;
4284 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004286 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004287 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4288 return info.service.owner.packageName;
4289 }
4290
4291 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4293 int match) {
4294 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4295 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4296 return null;
4297 }
4298 final PackageParser.Service service = info.service;
4299 if (mSafeMode && (service.info.applicationInfo.flags
4300 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4301 return null;
4302 }
4303 final ResolveInfo res = new ResolveInfo();
4304 res.serviceInfo = PackageParser.generateServiceInfo(service,
4305 mFlags);
4306 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4307 res.filter = filter;
4308 }
4309 res.priority = info.getPriority();
4310 res.preferredOrder = service.owner.mPreferredOrder;
4311 //System.out.println("Result: " + res.activityInfo.className +
4312 // " = " + res.priority);
4313 res.match = match;
4314 res.isDefault = info.hasDefault;
4315 res.labelRes = info.labelRes;
4316 res.nonLocalizedLabel = info.nonLocalizedLabel;
4317 res.icon = info.icon;
4318 return res;
4319 }
4320
4321 @Override
4322 protected void sortResults(List<ResolveInfo> results) {
4323 Collections.sort(results, mResolvePrioritySorter);
4324 }
4325
4326 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004327 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004329 out.print(prefix); out.print(
4330 Integer.toHexString(System.identityHashCode(filter.service)));
4331 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004332 out.print(filter.service.getComponentShortName());
4333 out.print(" filter ");
4334 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 }
4336
4337// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4338// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4339// final List<ResolveInfo> retList = Lists.newArrayList();
4340// while (i.hasNext()) {
4341// final ResolveInfo resolveInfo = (ResolveInfo) i;
4342// if (isEnabledLP(resolveInfo.serviceInfo)) {
4343// retList.add(resolveInfo);
4344// }
4345// }
4346// return retList;
4347// }
4348
4349 // Keys are String (activity class name), values are Activity.
4350 private final HashMap<ComponentName, PackageParser.Service> mServices
4351 = new HashMap<ComponentName, PackageParser.Service>();
4352 private int mFlags;
4353 };
4354
4355 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4356 new Comparator<ResolveInfo>() {
4357 public int compare(ResolveInfo r1, ResolveInfo r2) {
4358 int v1 = r1.priority;
4359 int v2 = r2.priority;
4360 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4361 if (v1 != v2) {
4362 return (v1 > v2) ? -1 : 1;
4363 }
4364 v1 = r1.preferredOrder;
4365 v2 = r2.preferredOrder;
4366 if (v1 != v2) {
4367 return (v1 > v2) ? -1 : 1;
4368 }
4369 if (r1.isDefault != r2.isDefault) {
4370 return r1.isDefault ? -1 : 1;
4371 }
4372 v1 = r1.match;
4373 v2 = r2.match;
4374 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4375 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4376 }
4377 };
4378
4379 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4380 new Comparator<ProviderInfo>() {
4381 public int compare(ProviderInfo p1, ProviderInfo p2) {
4382 final int v1 = p1.initOrder;
4383 final int v2 = p2.initOrder;
4384 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4385 }
4386 };
4387
4388 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4389 IActivityManager am = ActivityManagerNative.getDefault();
4390 if (am != null) {
4391 try {
4392 final Intent intent = new Intent(action,
4393 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4394 if (extras != null) {
4395 intent.putExtras(extras);
4396 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004397 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004398 am.broadcastIntent(
4399 null, intent,
4400 null, null, 0, null, null, null, false, false);
4401 } catch (RemoteException ex) {
4402 }
4403 }
4404 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004405
4406 public String nextPackageToClean(String lastPackage) {
4407 synchronized (mPackages) {
4408 if (!mMediaMounted) {
4409 // If the external storage is no longer mounted at this point,
4410 // the caller may not have been able to delete all of this
4411 // packages files and can not delete any more. Bail.
4412 return null;
4413 }
4414 if (lastPackage != null) {
4415 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4416 }
4417 return mSettings.mPackagesToBeCleaned.size() > 0
4418 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4419 }
4420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004421
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004422 void schedulePackageCleaning(String packageName) {
4423 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4424 }
4425
4426 void startCleaningPackages() {
4427 synchronized (mPackages) {
4428 if (!mMediaMounted) {
4429 return;
4430 }
4431 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4432 return;
4433 }
4434 }
4435 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4436 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4437 IActivityManager am = ActivityManagerNative.getDefault();
4438 if (am != null) {
4439 try {
4440 am.startService(null, intent, null);
4441 } catch (RemoteException e) {
4442 }
4443 }
4444 }
4445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004446 private final class AppDirObserver extends FileObserver {
4447 public AppDirObserver(String path, int mask, boolean isrom) {
4448 super(path, mask);
4449 mRootDir = path;
4450 mIsRom = isrom;
4451 }
4452
4453 public void onEvent(int event, String path) {
4454 String removedPackage = null;
4455 int removedUid = -1;
4456 String addedPackage = null;
4457 int addedUid = -1;
4458
4459 synchronized (mInstallLock) {
4460 String fullPathStr = null;
4461 File fullPath = null;
4462 if (path != null) {
4463 fullPath = new File(mRootDir, path);
4464 fullPathStr = fullPath.getPath();
4465 }
4466
4467 if (Config.LOGV) Log.v(
4468 TAG, "File " + fullPathStr + " changed: "
4469 + Integer.toHexString(event));
4470
4471 if (!isPackageFilename(path)) {
4472 if (Config.LOGV) Log.v(
4473 TAG, "Ignoring change of non-package file: " + fullPathStr);
4474 return;
4475 }
4476
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004477 // Ignore packages that are being installed or
4478 // have just been installed.
4479 if (ignoreCodePath(fullPathStr)) {
4480 return;
4481 }
4482 PackageParser.Package p = null;
4483 synchronized (mPackages) {
4484 p = mAppDirs.get(fullPathStr);
4485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004486 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004487 if (p != null) {
4488 removePackageLI(p, true);
4489 removedPackage = p.applicationInfo.packageName;
4490 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 }
4492 }
4493
4494 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004496 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004497 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4498 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499 PackageParser.PARSE_CHATTY |
4500 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004501 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 if (p != null) {
4503 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004504 updatePermissionsLP(p.packageName, p,
4505 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 }
4507 addedPackage = p.applicationInfo.packageName;
4508 addedUid = p.applicationInfo.uid;
4509 }
4510 }
4511 }
4512
4513 synchronized (mPackages) {
4514 mSettings.writeLP();
4515 }
4516 }
4517
4518 if (removedPackage != null) {
4519 Bundle extras = new Bundle(1);
4520 extras.putInt(Intent.EXTRA_UID, removedUid);
4521 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4522 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4523 }
4524 if (addedPackage != null) {
4525 Bundle extras = new Bundle(1);
4526 extras.putInt(Intent.EXTRA_UID, addedUid);
4527 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4528 }
4529 }
4530
4531 private final String mRootDir;
4532 private final boolean mIsRom;
4533 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 /* Called when a downloaded package installation has been confirmed by the user */
4536 public void installPackage(
4537 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004538 installPackage(packageURI, observer, flags, null);
4539 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004540
Jacek Surazski65e13172009-04-28 15:26:38 +02004541 /* Called when a downloaded package installation has been confirmed by the user */
4542 public void installPackage(
4543 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4544 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 mContext.enforceCallingOrSelfPermission(
4546 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004547
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004548 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004549 msg.obj = new InstallParams(packageURI, observer, flags,
4550 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004551 mHandler.sendMessage(msg);
4552 }
4553
Christopher Tate1bb69062010-02-19 17:02:12 -08004554 public void finishPackageInstall(int token) {
4555 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4556 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4557 mHandler.sendMessage(msg);
4558 }
4559
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004560 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 // Queue up an async operation since the package installation may take a little while.
4562 mHandler.post(new Runnable() {
4563 public void run() {
4564 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004565 // Result object to be returned
4566 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004567 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004568 res.uid = -1;
4569 res.pkg = null;
4570 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004571 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004572 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004573 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004574 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004575 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004576 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004578
4579 // A restore should be performed at this point if (a) the install
4580 // succeeded, (b) the operation is not an update, and (c) the new
4581 // package has a backupAgent defined.
4582 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004583 boolean doRestore = (!update
4584 && res.pkg != null
4585 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004586
4587 // Set up the post-install work request bookkeeping. This will be used
4588 // and cleaned up by the post-install event handling regardless of whether
4589 // there's a restore pass performed. Token values are >= 1.
4590 int token;
4591 if (mNextInstallToken < 0) mNextInstallToken = 1;
4592 token = mNextInstallToken++;
4593
4594 PostInstallData data = new PostInstallData(args, res);
4595 mRunningInstalls.put(token, data);
4596 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4597
4598 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4599 // Pass responsibility to the Backup Manager. It will perform a
4600 // restore if appropriate, then pass responsibility back to the
4601 // Package Manager to run the post-install observer callbacks
4602 // and broadcasts.
4603 IBackupManager bm = IBackupManager.Stub.asInterface(
4604 ServiceManager.getService(Context.BACKUP_SERVICE));
4605 if (bm != null) {
4606 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4607 + " to BM for possible restore");
4608 try {
4609 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4610 } catch (RemoteException e) {
4611 // can't happen; the backup manager is local
4612 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004613 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004614 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004615 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004616 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004617 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004618 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004620 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004621
4622 if (!doRestore) {
4623 // No restore possible, or the Backup Manager was mysteriously not
4624 // available -- just fire the post-install work request directly.
4625 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4626 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4627 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004629 }
4630 });
4631 }
4632
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004633 abstract class HandlerParams {
4634 final static int MAX_RETRIES = 4;
4635 int retry = 0;
4636 final void startCopy() {
4637 try {
4638 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4639 retry++;
4640 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004641 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004642 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4643 handleServiceError();
4644 return;
4645 } else {
4646 handleStartCopy();
4647 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4648 mHandler.sendEmptyMessage(MCS_UNBIND);
4649 }
4650 } catch (RemoteException e) {
4651 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4652 mHandler.sendEmptyMessage(MCS_RECONNECT);
4653 }
4654 handleReturnCode();
4655 }
4656
4657 final void serviceError() {
4658 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4659 handleServiceError();
4660 handleReturnCode();
4661 }
4662 abstract void handleStartCopy() throws RemoteException;
4663 abstract void handleServiceError();
4664 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004665 }
4666
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004667 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004668 final IPackageInstallObserver observer;
4669 int flags;
4670 final Uri packageURI;
4671 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004672 private InstallArgs mArgs;
4673 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004674 InstallParams(Uri packageURI,
4675 IPackageInstallObserver observer, int flags,
4676 String installerPackageName) {
4677 this.packageURI = packageURI;
4678 this.flags = flags;
4679 this.observer = observer;
4680 this.installerPackageName = installerPackageName;
4681 }
4682
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004683 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4684 String packageName = pkgLite.packageName;
4685 int installLocation = pkgLite.installLocation;
4686 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4687 synchronized (mPackages) {
4688 PackageParser.Package pkg = mPackages.get(packageName);
4689 if (pkg != null) {
4690 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4691 // Check for updated system application.
4692 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4693 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004694 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004695 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4696 }
4697 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4698 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004699 if (onSd) {
4700 // Install flag overrides everything.
4701 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4702 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004703 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004704 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4705 // Application explicitly specified internal.
4706 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4707 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4708 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004709 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004710 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004711 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4712 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4713 }
4714 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004715 }
4716 }
4717 } else {
4718 // Invalid install. Return error code
4719 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4720 }
4721 }
4722 }
4723 // All the special cases have been taken care of.
4724 // Return result based on recommended install location.
4725 if (onSd) {
4726 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4727 }
4728 return pkgLite.recommendedInstallLocation;
4729 }
4730
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004731 /*
4732 * Invoke remote method to get package information and install
4733 * location values. Override install location based on default
4734 * policy if needed and then create install arguments based
4735 * on the install location.
4736 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004737 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004738 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004739 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4740 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004741 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4742 if (onInt && onSd) {
4743 // Check if both bits are set.
4744 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4745 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4746 } else if (fwdLocked && onSd) {
4747 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004748 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004749 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004750 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004751 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004752 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004753 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004754 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4755 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4756 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4757 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4758 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004759 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4760 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4761 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004762 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4763 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004764 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004765 // Override with defaults if needed.
4766 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004767 if (!onSd && !onInt) {
4768 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004769 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4770 // Set the flag to install on external media.
4771 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004772 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004773 } else {
4774 // Make sure the flag for installing on external
4775 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004776 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004777 flags &= ~PackageManager.INSTALL_EXTERNAL;
4778 }
4779 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004780 }
4781 }
4782 // Create the file args now.
4783 mArgs = createInstallArgs(this);
4784 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4785 // Create copy only if we are not in an erroneous state.
4786 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004787 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004788 }
4789 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004790 }
4791
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004792 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004793 void handleReturnCode() {
4794 processPendingInstall(mArgs, mRet);
4795 }
4796
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004797 @Override
4798 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004799 mArgs = createInstallArgs(this);
4800 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004801 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004802 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004803
4804 /*
4805 * Utility class used in movePackage api.
4806 * srcArgs and targetArgs are not set for invalid flags and make
4807 * sure to do null checks when invoking methods on them.
4808 * We probably want to return ErrorPrams for both failed installs
4809 * and moves.
4810 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004811 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004812 final IPackageMoveObserver observer;
4813 final int flags;
4814 final String packageName;
4815 final InstallArgs srcArgs;
4816 final InstallArgs targetArgs;
4817 int mRet;
4818 MoveParams(InstallArgs srcArgs,
4819 IPackageMoveObserver observer,
4820 int flags, String packageName) {
4821 this.srcArgs = srcArgs;
4822 this.observer = observer;
4823 this.flags = flags;
4824 this.packageName = packageName;
4825 if (srcArgs != null) {
4826 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4827 targetArgs = createInstallArgs(packageUri, flags, packageName);
4828 } else {
4829 targetArgs = null;
4830 }
4831 }
4832
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004833 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004834 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4835 // Check for storage space on target medium
4836 if (!targetArgs.checkFreeStorage(mContainerService)) {
4837 Log.w(TAG, "Insufficient storage to install");
4838 return;
4839 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004840 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004841 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004842 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004843 if (DEBUG_SD_INSTALL) {
4844 StringBuilder builder = new StringBuilder();
4845 if (srcArgs != null) {
4846 builder.append("src: ");
4847 builder.append(srcArgs.getCodePath());
4848 }
4849 if (targetArgs != null) {
4850 builder.append(" target : ");
4851 builder.append(targetArgs.getCodePath());
4852 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004853 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004854 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004855 }
4856
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004857 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 void handleReturnCode() {
4859 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004860 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4861 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4862 currentStatus = PackageManager.MOVE_SUCCEEDED;
4863 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4864 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4865 }
4866 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004867 }
4868
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004869 @Override
4870 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004871 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004872 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004873 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004874
4875 private InstallArgs createInstallArgs(InstallParams params) {
4876 if (installOnSd(params.flags)) {
4877 return new SdInstallArgs(params);
4878 } else {
4879 return new FileInstallArgs(params);
4880 }
4881 }
4882
4883 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4884 if (installOnSd(flags)) {
4885 return new SdInstallArgs(fullCodePath, fullResourcePath);
4886 } else {
4887 return new FileInstallArgs(fullCodePath, fullResourcePath);
4888 }
4889 }
4890
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004891 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4892 if (installOnSd(flags)) {
4893 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4894 return new SdInstallArgs(packageURI, cid);
4895 } else {
4896 return new FileInstallArgs(packageURI, pkgName);
4897 }
4898 }
4899
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004900 static abstract class InstallArgs {
4901 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004902 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004903 final int flags;
4904 final Uri packageURI;
4905 final String installerPackageName;
4906
4907 InstallArgs(Uri packageURI,
4908 IPackageInstallObserver observer, int flags,
4909 String installerPackageName) {
4910 this.packageURI = packageURI;
4911 this.flags = flags;
4912 this.observer = observer;
4913 this.installerPackageName = installerPackageName;
4914 }
4915
4916 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004917 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004918 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004919 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004920 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004921 abstract String getCodePath();
4922 abstract String getResourcePath();
4923 // Need installer lock especially for dex file removal.
4924 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004925 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004926 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004927 }
4928
4929 class FileInstallArgs extends InstallArgs {
4930 File installDir;
4931 String codeFileName;
4932 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004933 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004934
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004935 FileInstallArgs(InstallParams params) {
4936 super(params.packageURI, params.observer,
4937 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004938 }
4939
4940 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4941 super(null, null, 0, null);
4942 File codeFile = new File(fullCodePath);
4943 installDir = codeFile.getParentFile();
4944 codeFileName = fullCodePath;
4945 resourceFileName = fullResourcePath;
4946 }
4947
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004948 FileInstallArgs(Uri packageURI, String pkgName) {
4949 super(packageURI, null, 0, null);
4950 boolean fwdLocked = isFwdLocked(flags);
4951 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4952 String apkName = getNextCodePath(null, pkgName, ".apk");
4953 codeFileName = new File(installDir, apkName + ".apk").getPath();
4954 resourceFileName = getResourcePathFromCodePath();
4955 }
4956
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004957 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4958 return imcs.checkFreeStorage(false, packageURI);
4959 }
4960
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004961 String getCodePath() {
4962 return codeFileName;
4963 }
4964
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004965 void createCopyFile() {
4966 boolean fwdLocked = isFwdLocked(flags);
4967 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4968 codeFileName = createTempPackageFile(installDir).getPath();
4969 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004970 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004971 }
4972
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004973 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004974 if (temp) {
4975 // Generate temp file name
4976 createCopyFile();
4977 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004978 // Get a ParcelFileDescriptor to write to the output file
4979 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004980 if (!created) {
4981 try {
4982 codeFile.createNewFile();
4983 // Set permissions
4984 if (!setPermissions()) {
4985 // Failed setting permissions.
4986 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4987 }
4988 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004989 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004990 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4991 }
4992 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004993 ParcelFileDescriptor out = null;
4994 try {
4995 out = ParcelFileDescriptor.open(codeFile,
4996 ParcelFileDescriptor.MODE_READ_WRITE);
4997 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004998 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004999 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5000 }
5001 // Copy the resource now
5002 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5003 try {
5004 if (imcs.copyResource(packageURI, out)) {
5005 ret = PackageManager.INSTALL_SUCCEEDED;
5006 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005007 } finally {
5008 try { if (out != null) out.close(); } catch (IOException e) {}
5009 }
5010 return ret;
5011 }
5012
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005013 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005014 if (status != PackageManager.INSTALL_SUCCEEDED) {
5015 cleanUp();
5016 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005017 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005018 }
5019
5020 boolean doRename(int status, final String pkgName, String oldCodePath) {
5021 if (status != PackageManager.INSTALL_SUCCEEDED) {
5022 cleanUp();
5023 return false;
5024 } else {
5025 // Rename based on packageName
5026 File codeFile = new File(getCodePath());
5027 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5028 File desFile = new File(installDir, apkName + ".apk");
5029 if (!codeFile.renameTo(desFile)) {
5030 return false;
5031 }
5032 // Reset paths since the file has been renamed.
5033 codeFileName = desFile.getPath();
5034 resourceFileName = getResourcePathFromCodePath();
5035 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005036 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005037 // Failed setting permissions.
5038 return false;
5039 }
5040 return true;
5041 }
5042 }
5043
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005044 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005045 if (status != PackageManager.INSTALL_SUCCEEDED) {
5046 cleanUp();
5047 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005048 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005049 }
5050
5051 String getResourcePath() {
5052 return resourceFileName;
5053 }
5054
5055 String getResourcePathFromCodePath() {
5056 String codePath = getCodePath();
5057 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5058 String apkNameOnly = getApkName(codePath);
5059 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5060 } else {
5061 return codePath;
5062 }
5063 }
5064
5065 private boolean cleanUp() {
5066 boolean ret = true;
5067 String sourceDir = getCodePath();
5068 String publicSourceDir = getResourcePath();
5069 if (sourceDir != null) {
5070 File sourceFile = new File(sourceDir);
5071 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005072 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005073 ret = false;
5074 }
5075 // Delete application's code and resources
5076 sourceFile.delete();
5077 }
5078 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5079 final File publicSourceFile = new File(publicSourceDir);
5080 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005081 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005082 }
5083 if (publicSourceFile.exists()) {
5084 publicSourceFile.delete();
5085 }
5086 }
5087 return ret;
5088 }
5089
5090 void cleanUpResourcesLI() {
5091 String sourceDir = getCodePath();
5092 if (cleanUp() && mInstaller != null) {
5093 int retCode = mInstaller.rmdex(sourceDir);
5094 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005095 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005096 + " at location "
5097 + sourceDir + ", retcode=" + retCode);
5098 // we don't consider this to be a failure of the core package deletion
5099 }
5100 }
5101 }
5102
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005103 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005104 // TODO Do this in a more elegant way later on. for now just a hack
5105 if (!isFwdLocked(flags)) {
5106 final int filePermissions =
5107 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5108 |FileUtils.S_IROTH;
5109 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5110 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005111 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005112 getCodePath()
5113 + ". The return code was: " + retCode);
5114 // TODO Define new internal error
5115 return false;
5116 }
5117 return true;
5118 }
5119 return true;
5120 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005121
5122 boolean doPostDeleteLI(boolean delete) {
5123 cleanUpResourcesLI();
5124 return true;
5125 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005126 }
5127
5128 class SdInstallArgs extends InstallArgs {
5129 String cid;
5130 String cachePath;
5131 static final String RES_FILE_NAME = "pkg.apk";
5132
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005133 SdInstallArgs(InstallParams params) {
5134 super(params.packageURI, params.observer,
5135 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005136 }
5137
5138 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005139 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005140 // Extract cid from fullCodePath
5141 int eidx = fullCodePath.lastIndexOf("/");
5142 String subStr1 = fullCodePath.substring(0, eidx);
5143 int sidx = subStr1.lastIndexOf("/");
5144 cid = subStr1.substring(sidx+1, eidx);
5145 cachePath = subStr1;
5146 }
5147
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005148 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005149 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5150 this.cid = cid;
5151 }
5152
5153 SdInstallArgs(Uri packageURI, String cid) {
5154 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005155 this.cid = cid;
5156 }
5157
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005158 void createCopyFile() {
5159 cid = getTempContainerId();
5160 }
5161
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005162 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5163 return imcs.checkFreeStorage(true, packageURI);
5164 }
5165
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005166 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005167 if (temp) {
5168 createCopyFile();
5169 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005170 cachePath = imcs.copyResourceToContainer(
5171 packageURI, cid,
5172 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005173 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5174 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005175 }
5176
5177 @Override
5178 String getCodePath() {
5179 return cachePath + "/" + RES_FILE_NAME;
5180 }
5181
5182 @Override
5183 String getResourcePath() {
5184 return cachePath + "/" + RES_FILE_NAME;
5185 }
5186
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005187 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005188 if (status != PackageManager.INSTALL_SUCCEEDED) {
5189 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005190 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005191 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005192 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005193 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005194 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005195 if (cachePath == null) {
5196 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5197 }
5198 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005199 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005200 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005201 }
5202
5203 boolean doRename(int status, final String pkgName,
5204 String oldCodePath) {
5205 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005206 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005207 if (PackageHelper.isContainerMounted(cid)) {
5208 // Unmount the container
5209 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005210 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005211 return false;
5212 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005213 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005214 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005215 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005216 return false;
5217 }
5218 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005219 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005220 newCachePath = PackageHelper.mountSdDir(newCacheId,
5221 getEncryptKey(), Process.SYSTEM_UID);
5222 } else {
5223 newCachePath = PackageHelper.getSdDir(newCacheId);
5224 }
5225 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005226 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005227 return false;
5228 }
5229 Log.i(TAG, "Succesfully renamed " + cid +
5230 " at path: " + cachePath + " to " + newCacheId +
5231 " at new path: " + newCachePath);
5232 cid = newCacheId;
5233 cachePath = newCachePath;
5234 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005235 }
5236
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005237 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005238 if (status != PackageManager.INSTALL_SUCCEEDED) {
5239 cleanUp();
5240 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005241 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005242 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005243 PackageHelper.mountSdDir(cid,
5244 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005245 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005246 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005247 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005248 }
5249
5250 private void cleanUp() {
5251 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005252 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005253 }
5254
5255 void cleanUpResourcesLI() {
5256 String sourceFile = getCodePath();
5257 // Remove dex file
5258 if (mInstaller != null) {
5259 int retCode = mInstaller.rmdex(sourceFile.toString());
5260 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005261 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005262 + " at location "
5263 + sourceFile.toString() + ", retcode=" + retCode);
5264 // we don't consider this to be a failure of the core package deletion
5265 }
5266 }
5267 cleanUp();
5268 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005269
5270 boolean matchContainer(String app) {
5271 if (cid.startsWith(app)) {
5272 return true;
5273 }
5274 return false;
5275 }
5276
5277 String getPackageName() {
5278 int idx = cid.lastIndexOf("-");
5279 if (idx == -1) {
5280 return cid;
5281 }
5282 return cid.substring(0, idx);
5283 }
5284
5285 boolean doPostDeleteLI(boolean delete) {
5286 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005287 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005288 if (mounted) {
5289 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005290 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005291 }
5292 if (ret && delete) {
5293 cleanUpResourcesLI();
5294 }
5295 return ret;
5296 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005297 };
5298
5299 // Utility method used to create code paths based on package name and available index.
5300 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5301 String idxStr = "";
5302 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005303 // Fall back to default value of idx=1 if prefix is not
5304 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005305 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005306 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005307 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005308 if (subStr.endsWith(suffix)) {
5309 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005310 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005311 // If oldCodePath already contains prefix find out the
5312 // ending index to either increment or decrement.
5313 int sidx = subStr.lastIndexOf(prefix);
5314 if (sidx != -1) {
5315 subStr = subStr.substring(sidx + prefix.length());
5316 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005317 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5318 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005319 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005320 try {
5321 idx = Integer.parseInt(subStr);
5322 if (idx <= 1) {
5323 idx++;
5324 } else {
5325 idx--;
5326 }
5327 } catch(NumberFormatException e) {
5328 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005329 }
5330 }
5331 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005332 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005333 return prefix + idxStr;
5334 }
5335
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005336 // Utility method used to ignore ADD/REMOVE events
5337 // by directory observer.
5338 private static boolean ignoreCodePath(String fullPathStr) {
5339 String apkName = getApkName(fullPathStr);
5340 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5341 if (idx != -1 && ((idx+1) < apkName.length())) {
5342 // Make sure the package ends with a numeral
5343 String version = apkName.substring(idx+1);
5344 try {
5345 Integer.parseInt(version);
5346 return true;
5347 } catch (NumberFormatException e) {}
5348 }
5349 return false;
5350 }
5351
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005352 // Utility method that returns the relative package path with respect
5353 // to the installation directory. Like say for /data/data/com.test-1.apk
5354 // string com.test-1 is returned.
5355 static String getApkName(String codePath) {
5356 if (codePath == null) {
5357 return null;
5358 }
5359 int sidx = codePath.lastIndexOf("/");
5360 int eidx = codePath.lastIndexOf(".");
5361 if (eidx == -1) {
5362 eidx = codePath.length();
5363 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005364 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005365 return null;
5366 }
5367 return codePath.substring(sidx+1, eidx);
5368 }
5369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005370 class PackageInstalledInfo {
5371 String name;
5372 int uid;
5373 PackageParser.Package pkg;
5374 int returnCode;
5375 PackageRemovedInfo removedInfo;
5376 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378 /*
5379 * Install a non-existing package.
5380 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005381 private void installNewPackageLI(PackageParser.Package pkg,
5382 int parseFlags,
5383 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005384 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005385 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005386 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005387
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005388 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389 res.name = pkgName;
5390 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005391 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005392 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005393 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005394 + " without first uninstalling.");
5395 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5396 return;
5397 }
5398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005399 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005400 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005401 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005402 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005403 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5404 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5405 }
5406 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005407 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005408 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 res);
5410 // delete the partially installed application. the data directory will have to be
5411 // restored if it was already existing
5412 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5413 // remove package from internal structures. Note that we want deletePackageX to
5414 // delete the package data and cache directories that it created in
5415 // scanPackageLocked, unless those directories existed before we even tried to
5416 // install.
5417 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005418 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5420 res.removedInfo);
5421 }
5422 }
5423 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005424
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005425 private void replacePackageLI(PackageParser.Package pkg,
5426 int parseFlags,
5427 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005428 String installerPackageName, PackageInstalledInfo res) {
5429
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005430 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005431 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005432 // First find the old package info and check signatures
5433 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005434 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005435 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005436 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005437 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5438 return;
5439 }
5440 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005441 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005442 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005443 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005444 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005445 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 }
5447 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005449 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005450 PackageParser.Package pkg,
5451 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005452 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005453 PackageParser.Package newPackage = null;
5454 String pkgName = deletedPackage.packageName;
5455 boolean deletedPkg = true;
5456 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005457
Jacek Surazski65e13172009-04-28 15:26:38 +02005458 String oldInstallerPackageName = null;
5459 synchronized (mPackages) {
5460 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5461 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005462
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005463 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005465 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 res.removedInfo)) {
5467 // If the existing package was'nt successfully deleted
5468 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5469 deletedPkg = false;
5470 } else {
5471 // Successfully deleted the old package. Now proceed with re-installation
5472 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005473 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005475 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5477 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005478 }
5479 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005480 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005481 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005482 res);
5483 updatedSettings = true;
5484 }
5485 }
5486
5487 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5488 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005489 // were keeping around in case we needed them (see below) can now be deleted.
5490 // This info will be set on the res.removedInfo to clean up later on as post
5491 // install action.
5492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 //update signature on the new package setting
5494 //this should always succeed, since we checked the
5495 //signature earlier.
5496 synchronized(mPackages) {
5497 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5498 parseFlags, true);
5499 }
5500 } else {
5501 // remove package from internal structures. Note that we want deletePackageX to
5502 // delete the package data and cache directories that it created in
5503 // scanPackageLocked, unless those directories existed before we even tried to
5504 // install.
5505 if(updatedSettings) {
5506 deletePackageLI(
5507 pkgName, true,
5508 PackageManager.DONT_DELETE_DATA,
5509 res.removedInfo);
5510 }
5511 // Since we failed to install the new package we need to restore the old
5512 // package that we deleted.
5513 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005514 File restoreFile = new File(deletedPackage.mPath);
5515 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005516 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005517 return;
5518 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005519 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5520 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005521 // Parse old package
5522 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5523 scanPackageLI(restoreFile, parseFlags, scanMode);
5524 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005525 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5526 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005527 mSettings.writeLP();
5528 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005529 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005530 Slog.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 }
5533 }
5534 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005537 PackageParser.Package pkg,
5538 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005539 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 PackageParser.Package newPackage = null;
5541 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005542 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 PackageParser.PARSE_IS_SYSTEM;
5544 String packageName = deletedPackage.packageName;
5545 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5546 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005547 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548 return;
5549 }
5550 PackageParser.Package oldPkg;
5551 PackageSetting oldPkgSetting;
5552 synchronized (mPackages) {
5553 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005554 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005555 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5556 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005557 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 return;
5559 }
5560 }
5561 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5562 res.removedInfo.removedPackage = packageName;
5563 // Remove existing system package
5564 removePackageLI(oldPkg, true);
5565 synchronized (mPackages) {
5566 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5567 }
5568
5569 // Successfully disabled the old package. Now proceed with re-installation
5570 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5571 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005572 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005574 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5576 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5577 }
5578 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005579 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005580 updatedSettings = true;
5581 }
5582
5583 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5584 //update signature on the new package setting
5585 //this should always succeed, since we checked the
5586 //signature earlier.
5587 synchronized(mPackages) {
5588 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5589 parseFlags, true);
5590 }
5591 } else {
5592 // Re installation failed. Restore old information
5593 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005594 if (newPackage != null) {
5595 removePackageLI(newPackage, true);
5596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005597 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005598 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005600 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 // Restore the old system information in Settings
5602 synchronized(mPackages) {
5603 if(updatedSettings) {
5604 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005605 mSettings.setInstallerPackageName(packageName,
5606 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 }
5608 mSettings.writeLP();
5609 }
5610 }
5611 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005612
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005613 // Utility method used to move dex files during install.
5614 private int moveDexFiles(PackageParser.Package newPackage) {
5615 int retCode;
5616 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5617 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5618 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005619 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005620 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5621 }
5622 }
5623 return PackageManager.INSTALL_SUCCEEDED;
5624 }
5625
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005626 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005627 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005628 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005629 synchronized (mPackages) {
5630 //write settings. the installStatus will be incomplete at this stage.
5631 //note that the new package setting would have already been
5632 //added to mPackages. It hasn't been persisted yet.
5633 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5634 mSettings.writeLP();
5635 }
5636
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005637 if ((res.returnCode = moveDexFiles(newPackage))
5638 != PackageManager.INSTALL_SUCCEEDED) {
5639 // Discontinue if moving dex files failed.
5640 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005642 if((res.returnCode = setPermissionsLI(newPackage))
5643 != PackageManager.INSTALL_SUCCEEDED) {
5644 if (mInstaller != null) {
5645 mInstaller.rmdex(newPackage.mScanPath);
5646 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005647 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005648 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005649 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005652 updatePermissionsLP(newPackage.packageName, newPackage,
5653 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 res.name = pkgName;
5655 res.uid = newPackage.applicationInfo.uid;
5656 res.pkg = newPackage;
5657 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005658 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5660 //to update install status
5661 mSettings.writeLP();
5662 }
5663 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005664
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005665 private void installPackageLI(InstallArgs args,
5666 boolean newInstall, PackageInstalledInfo res) {
5667 int pFlags = args.flags;
5668 String installerPackageName = args.installerPackageName;
5669 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005670 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005671 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005672 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005673 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5674 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005675 // Result object to be returned
5676 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5677
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005678 // Retrieve PackageSettings and parse package
5679 int parseFlags = PackageParser.PARSE_CHATTY |
5680 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5681 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5682 parseFlags |= mDefParseFlags;
5683 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5684 pp.setSeparateProcesses(mSeparateProcesses);
5685 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5686 null, mMetrics, parseFlags);
5687 if (pkg == null) {
5688 res.returnCode = pp.getParseError();
5689 return;
5690 }
5691 String pkgName = res.name = pkg.packageName;
5692 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5693 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5694 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5695 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005697 }
5698 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5699 res.returnCode = pp.getParseError();
5700 return;
5701 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005702 // Get rid of all references to package scan path via parser.
5703 pp = null;
5704 String oldCodePath = null;
5705 boolean systemApp = false;
5706 synchronized (mPackages) {
5707 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005708 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5709 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005710 if (pkg.mOriginalPackages != null
5711 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005712 && mPackages.containsKey(oldName)) {
5713 // This package is derived from an original package,
5714 // and this device has been updating from that original
5715 // name. We must continue using the original name, so
5716 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005717 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005718 pkgName = pkg.packageName;
5719 replace = true;
5720 } else if (mPackages.containsKey(pkgName)) {
5721 // This package, under its official name, already exists
5722 // on the device; we should replace it.
5723 replace = true;
5724 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005725 }
5726 PackageSetting ps = mSettings.mPackages.get(pkgName);
5727 if (ps != null) {
5728 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5729 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5730 systemApp = (ps.pkg.applicationInfo.flags &
5731 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005732 }
5733 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005734 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005735
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005736 if (systemApp && onSd) {
5737 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005738 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005739 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5740 return;
5741 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005742
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005743 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5744 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5745 return;
5746 }
5747 // Set application objects path explicitly after the rename
5748 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005749 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005750 replacePackageLI(pkg, parseFlags, scanMode,
5751 installerPackageName, res);
5752 } else {
5753 installNewPackageLI(pkg, parseFlags, scanMode,
5754 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 }
5756 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005757
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005758 private int setPermissionsLI(PackageParser.Package newPackage) {
5759 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005760 int retCode = 0;
5761 // TODO Gross hack but fix later. Ideally move this to be a post installation
5762 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005763 if ((newPackage.applicationInfo.flags
5764 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5765 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005766 try {
5767 extractPublicFiles(newPackage, destResourceFile);
5768 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005769 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 -08005770 " forward-locked app.");
5771 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5772 } finally {
5773 //TODO clean up the extracted public files
5774 }
5775 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005776 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 newPackage.applicationInfo.uid);
5778 } else {
5779 final int filePermissions =
5780 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005781 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 newPackage.applicationInfo.uid);
5783 }
5784 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005785 // The permissions on the resource file was set when it was copied for
5786 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005790 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005791 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005793 // TODO Define new internal error
5794 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 }
5796 return PackageManager.INSTALL_SUCCEEDED;
5797 }
5798
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005799 private boolean isForwardLocked(PackageParser.Package pkg) {
5800 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005801 }
5802
5803 private void extractPublicFiles(PackageParser.Package newPackage,
5804 File publicZipFile) throws IOException {
5805 final ZipOutputStream publicZipOutStream =
5806 new ZipOutputStream(new FileOutputStream(publicZipFile));
5807 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5808
5809 // Copy manifest, resources.arsc and res directory to public zip
5810
5811 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5812 while (privateZipEntries.hasMoreElements()) {
5813 final ZipEntry zipEntry = privateZipEntries.nextElement();
5814 final String zipEntryName = zipEntry.getName();
5815 if ("AndroidManifest.xml".equals(zipEntryName)
5816 || "resources.arsc".equals(zipEntryName)
5817 || zipEntryName.startsWith("res/")) {
5818 try {
5819 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5820 } catch (IOException e) {
5821 try {
5822 publicZipOutStream.close();
5823 throw e;
5824 } finally {
5825 publicZipFile.delete();
5826 }
5827 }
5828 }
5829 }
5830
5831 publicZipOutStream.close();
5832 FileUtils.setPermissions(
5833 publicZipFile.getAbsolutePath(),
5834 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5835 -1, -1);
5836 }
5837
5838 private static void copyZipEntry(ZipEntry zipEntry,
5839 ZipFile inZipFile,
5840 ZipOutputStream outZipStream) throws IOException {
5841 byte[] buffer = new byte[4096];
5842 int num;
5843
5844 ZipEntry newEntry;
5845 if (zipEntry.getMethod() == ZipEntry.STORED) {
5846 // Preserve the STORED method of the input entry.
5847 newEntry = new ZipEntry(zipEntry);
5848 } else {
5849 // Create a new entry so that the compressed len is recomputed.
5850 newEntry = new ZipEntry(zipEntry.getName());
5851 }
5852 outZipStream.putNextEntry(newEntry);
5853
5854 InputStream data = inZipFile.getInputStream(zipEntry);
5855 while ((num = data.read(buffer)) > 0) {
5856 outZipStream.write(buffer, 0, num);
5857 }
5858 outZipStream.flush();
5859 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 private void deleteTempPackageFiles() {
5862 FilenameFilter filter = new FilenameFilter() {
5863 public boolean accept(File dir, String name) {
5864 return name.startsWith("vmdl") && name.endsWith(".tmp");
5865 }
5866 };
5867 String tmpFilesList[] = mAppInstallDir.list(filter);
5868 if(tmpFilesList == null) {
5869 return;
5870 }
5871 for(int i = 0; i < tmpFilesList.length; i++) {
5872 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5873 tmpFile.delete();
5874 }
5875 }
5876
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005877 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005878 File tmpPackageFile;
5879 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005880 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005882 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883 return null;
5884 }
5885 try {
5886 FileUtils.setPermissions(
5887 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5888 -1, -1);
5889 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005890 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005891 return null;
5892 }
5893 return tmpPackageFile;
5894 }
5895
5896 public void deletePackage(final String packageName,
5897 final IPackageDeleteObserver observer,
5898 final int flags) {
5899 mContext.enforceCallingOrSelfPermission(
5900 android.Manifest.permission.DELETE_PACKAGES, null);
5901 // Queue up an async operation since the package deletion may take a little while.
5902 mHandler.post(new Runnable() {
5903 public void run() {
5904 mHandler.removeCallbacks(this);
5905 final boolean succeded = deletePackageX(packageName, true, true, flags);
5906 if (observer != null) {
5907 try {
5908 observer.packageDeleted(succeded);
5909 } catch (RemoteException e) {
5910 Log.i(TAG, "Observer no longer exists.");
5911 } //end catch
5912 } //end if
5913 } //end run
5914 });
5915 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005917 /**
5918 * This method is an internal method that could be get invoked either
5919 * to delete an installed package or to clean up a failed installation.
5920 * After deleting an installed package, a broadcast is sent to notify any
5921 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005922 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 * installation wouldn't have sent the initial broadcast either
5924 * The key steps in deleting a package are
5925 * deleting the package information in internal structures like mPackages,
5926 * deleting the packages base directories through installd
5927 * updating mSettings to reflect current status
5928 * persisting settings for later use
5929 * sending a broadcast if necessary
5930 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5932 boolean deleteCodeAndResources, int flags) {
5933 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005934 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005935
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005936 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5937 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5938 try {
5939 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005940 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005941 return false;
5942 }
5943 } catch (RemoteException e) {
5944 }
5945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 synchronized (mInstallLock) {
5947 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5948 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005950 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005951 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5952 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5953
5954 // If the removed package was a system update, the old system packaged
5955 // was re-enabled; we need to broadcast this information
5956 if (systemUpdate) {
5957 Bundle extras = new Bundle(1);
5958 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5959 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5960
5961 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5962 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005964 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005965 // Force a gc here.
5966 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005967 // Delete the resources here after sending the broadcast to let
5968 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005969 if (info.args != null) {
5970 synchronized (mInstallLock) {
5971 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005972 }
5973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 return res;
5975 }
5976
5977 static class PackageRemovedInfo {
5978 String removedPackage;
5979 int uid = -1;
5980 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005981 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005982 // Clean up resources deleted packages.
5983 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 void sendBroadcast(boolean fullRemove, boolean replacing) {
5986 Bundle extras = new Bundle(1);
5987 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5988 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5989 if (replacing) {
5990 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5991 }
5992 if (removedPackage != null) {
5993 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5994 }
5995 if (removedUid >= 0) {
5996 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5997 }
5998 }
5999 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 /*
6002 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6003 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006004 * 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 -08006005 * delete a partially installed application.
6006 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006007 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 int flags) {
6009 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006010 if (outInfo != null) {
6011 outInfo.removedPackage = packageName;
6012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 removePackageLI(p, true);
6014 // Retrieve object to delete permissions for shared user later on
6015 PackageSetting deletedPs;
6016 synchronized (mPackages) {
6017 deletedPs = mSettings.mPackages.get(packageName);
6018 }
6019 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006020 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006021 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006022 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006023 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006024 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 + packageName + ", retcode=" + retCode);
6026 // we don't consider this to be a failure of the core package deletion
6027 }
6028 } else {
6029 //for emulator
6030 PackageParser.Package pkg = mPackages.get(packageName);
6031 File dataDir = new File(pkg.applicationInfo.dataDir);
6032 dataDir.delete();
6033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006034 }
6035 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006036 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006037 schedulePackageCleaning(packageName);
6038
6039 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6040 if (outInfo != null) {
6041 outInfo.removedUid = mSettings.removePackageLP(packageName);
6042 }
6043 if (deletedPs != null) {
6044 updatePermissionsLP(deletedPs.name, null, false, false);
6045 if (deletedPs.sharedUser != null) {
6046 // remove permissions associated with package
6047 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6048 }
6049 }
6050 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006051 // remove from preferred activities.
6052 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6053 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6054 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6055 removed.add(pa);
6056 }
6057 }
6058 for (PreferredActivity pa : removed) {
6059 mSettings.mPreferredActivities.removeFilter(pa);
6060 }
6061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006062 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006063 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 }
6065 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006067 /*
6068 * Tries to delete system package.
6069 */
6070 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006071 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006072 ApplicationInfo applicationInfo = p.applicationInfo;
6073 //applicable for non-partially installed applications only
6074 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006075 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 return false;
6077 }
6078 PackageSetting ps = null;
6079 // Confirm if the system package has been updated
6080 // An updated system app can be deleted. This will also have to restore
6081 // the system pkg from system partition
6082 synchronized (mPackages) {
6083 ps = mSettings.getDisabledSystemPkg(p.packageName);
6084 }
6085 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006086 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087 return false;
6088 } else {
6089 Log.i(TAG, "Deleting system pkg from data partition");
6090 }
6091 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006092 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006093 boolean deleteCodeAndResources = false;
6094 if (ps.versionCode < p.mVersionCode) {
6095 // Delete code and resources for downgrades
6096 deleteCodeAndResources = true;
6097 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6098 flags &= ~PackageManager.DONT_DELETE_DATA;
6099 }
6100 } else {
6101 // Preserve data by setting flag
6102 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6103 flags |= PackageManager.DONT_DELETE_DATA;
6104 }
6105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006106 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6107 if (!ret) {
6108 return false;
6109 }
6110 synchronized (mPackages) {
6111 // Reinstate the old system package
6112 mSettings.enableSystemPackageLP(p.packageName);
6113 }
6114 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006115 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006117 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006120 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 return false;
6122 }
6123 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006124 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 mSettings.writeLP();
6126 }
6127 return true;
6128 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006130 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6131 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6132 ApplicationInfo applicationInfo = p.applicationInfo;
6133 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006134 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 return false;
6136 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006137 if (outInfo != null) {
6138 outInfo.uid = applicationInfo.uid;
6139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006140
6141 // Delete package data from internal structures and also remove data if flag is set
6142 removePackageDataLI(p, outInfo, flags);
6143
6144 // Delete application code and resources
6145 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006146 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006147 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006148 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006149 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6150 PackageManager.INSTALL_FORWARD_LOCK : 0;
6151 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006152 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006153 }
6154 return true;
6155 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 /*
6158 * This method handles package deletion in general
6159 */
6160 private boolean deletePackageLI(String packageName,
6161 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6162 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006163 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 return false;
6165 }
6166 PackageParser.Package p;
6167 boolean dataOnly = false;
6168 synchronized (mPackages) {
6169 p = mPackages.get(packageName);
6170 if (p == null) {
6171 //this retrieves partially installed apps
6172 dataOnly = true;
6173 PackageSetting ps = mSettings.mPackages.get(packageName);
6174 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006175 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006176 return false;
6177 }
6178 p = ps.pkg;
6179 }
6180 }
6181 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006182 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183 return false;
6184 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 if (dataOnly) {
6187 // Delete application data first
6188 removePackageDataLI(p, outInfo, flags);
6189 return true;
6190 }
6191 // At this point the package should have ApplicationInfo associated with it
6192 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006193 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 return false;
6195 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006196 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6198 Log.i(TAG, "Removing system package:"+p.packageName);
6199 // When an updated system application is deleted we delete the existing resources as well and
6200 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006201 ret = deleteSystemPackageLI(p, flags, outInfo);
6202 } else {
6203 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006204 // Kill application pre-emptively especially for apps on sd.
6205 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006206 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006208 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 public void clearApplicationUserData(final String packageName,
6212 final IPackageDataObserver observer) {
6213 mContext.enforceCallingOrSelfPermission(
6214 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6215 // Queue up an async operation since the package deletion may take a little while.
6216 mHandler.post(new Runnable() {
6217 public void run() {
6218 mHandler.removeCallbacks(this);
6219 final boolean succeeded;
6220 synchronized (mInstallLock) {
6221 succeeded = clearApplicationUserDataLI(packageName);
6222 }
6223 if (succeeded) {
6224 // invoke DeviceStorageMonitor's update method to clear any notifications
6225 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6226 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6227 if (dsm != null) {
6228 dsm.updateMemory();
6229 }
6230 }
6231 if(observer != null) {
6232 try {
6233 observer.onRemoveCompleted(packageName, succeeded);
6234 } catch (RemoteException e) {
6235 Log.i(TAG, "Observer no longer exists.");
6236 }
6237 } //end if observer
6238 } //end run
6239 });
6240 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 private boolean clearApplicationUserDataLI(String packageName) {
6243 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006244 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 return false;
6246 }
6247 PackageParser.Package p;
6248 boolean dataOnly = false;
6249 synchronized (mPackages) {
6250 p = mPackages.get(packageName);
6251 if(p == null) {
6252 dataOnly = true;
6253 PackageSetting ps = mSettings.mPackages.get(packageName);
6254 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006255 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 return false;
6257 }
6258 p = ps.pkg;
6259 }
6260 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006261 boolean useEncryptedFSDir = false;
6262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 if(!dataOnly) {
6264 //need to check this only for fully installed applications
6265 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006266 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 return false;
6268 }
6269 final ApplicationInfo applicationInfo = p.applicationInfo;
6270 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006271 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 return false;
6273 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006274 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006275 }
6276 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006277 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006279 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 + packageName);
6281 return false;
6282 }
6283 }
6284 return true;
6285 }
6286
6287 public void deleteApplicationCacheFiles(final String packageName,
6288 final IPackageDataObserver observer) {
6289 mContext.enforceCallingOrSelfPermission(
6290 android.Manifest.permission.DELETE_CACHE_FILES, null);
6291 // Queue up an async operation since the package deletion may take a little while.
6292 mHandler.post(new Runnable() {
6293 public void run() {
6294 mHandler.removeCallbacks(this);
6295 final boolean succeded;
6296 synchronized (mInstallLock) {
6297 succeded = deleteApplicationCacheFilesLI(packageName);
6298 }
6299 if(observer != null) {
6300 try {
6301 observer.onRemoveCompleted(packageName, succeded);
6302 } catch (RemoteException e) {
6303 Log.i(TAG, "Observer no longer exists.");
6304 }
6305 } //end if observer
6306 } //end run
6307 });
6308 }
6309
6310 private boolean deleteApplicationCacheFilesLI(String packageName) {
6311 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006312 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 return false;
6314 }
6315 PackageParser.Package p;
6316 synchronized (mPackages) {
6317 p = mPackages.get(packageName);
6318 }
6319 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006320 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 return false;
6322 }
6323 final ApplicationInfo applicationInfo = p.applicationInfo;
6324 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006325 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006326 return false;
6327 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006328 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006330 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006332 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 + packageName);
6334 return false;
6335 }
6336 }
6337 return true;
6338 }
6339
6340 public void getPackageSizeInfo(final String packageName,
6341 final IPackageStatsObserver observer) {
6342 mContext.enforceCallingOrSelfPermission(
6343 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6344 // Queue up an async operation since the package deletion may take a little while.
6345 mHandler.post(new Runnable() {
6346 public void run() {
6347 mHandler.removeCallbacks(this);
6348 PackageStats lStats = new PackageStats(packageName);
6349 final boolean succeded;
6350 synchronized (mInstallLock) {
6351 succeded = getPackageSizeInfoLI(packageName, lStats);
6352 }
6353 if(observer != null) {
6354 try {
6355 observer.onGetStatsCompleted(lStats, succeded);
6356 } catch (RemoteException e) {
6357 Log.i(TAG, "Observer no longer exists.");
6358 }
6359 } //end if observer
6360 } //end run
6361 });
6362 }
6363
6364 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6365 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006366 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 return false;
6368 }
6369 PackageParser.Package p;
6370 boolean dataOnly = false;
6371 synchronized (mPackages) {
6372 p = mPackages.get(packageName);
6373 if(p == null) {
6374 dataOnly = true;
6375 PackageSetting ps = mSettings.mPackages.get(packageName);
6376 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006377 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 return false;
6379 }
6380 p = ps.pkg;
6381 }
6382 }
6383 String publicSrcDir = null;
6384 if(!dataOnly) {
6385 final ApplicationInfo applicationInfo = p.applicationInfo;
6386 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006387 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006388 return false;
6389 }
6390 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6391 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006392 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 if (mInstaller != null) {
6394 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006395 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 if (res < 0) {
6397 return false;
6398 } else {
6399 return true;
6400 }
6401 }
6402 return true;
6403 }
6404
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 public void addPackageToPreferred(String packageName) {
6407 mContext.enforceCallingOrSelfPermission(
6408 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006409 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 }
6411
6412 public void removePackageFromPreferred(String packageName) {
6413 mContext.enforceCallingOrSelfPermission(
6414 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006415 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 }
6417
6418 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006419 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 }
6421
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006422 int getUidTargetSdkVersionLockedLP(int uid) {
6423 Object obj = mSettings.getUserIdLP(uid);
6424 if (obj instanceof SharedUserSetting) {
6425 SharedUserSetting sus = (SharedUserSetting)obj;
6426 final int N = sus.packages.size();
6427 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6428 Iterator<PackageSetting> it = sus.packages.iterator();
6429 int i=0;
6430 while (it.hasNext()) {
6431 PackageSetting ps = it.next();
6432 if (ps.pkg != null) {
6433 int v = ps.pkg.applicationInfo.targetSdkVersion;
6434 if (v < vers) vers = v;
6435 }
6436 }
6437 return vers;
6438 } else if (obj instanceof PackageSetting) {
6439 PackageSetting ps = (PackageSetting)obj;
6440 if (ps.pkg != null) {
6441 return ps.pkg.applicationInfo.targetSdkVersion;
6442 }
6443 }
6444 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6445 }
6446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 public void addPreferredActivity(IntentFilter filter, int match,
6448 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006450 if (mContext.checkCallingOrSelfPermission(
6451 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6452 != PackageManager.PERMISSION_GRANTED) {
6453 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6454 < Build.VERSION_CODES.FROYO) {
6455 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6456 + Binder.getCallingUid());
6457 return;
6458 }
6459 mContext.enforceCallingOrSelfPermission(
6460 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6461 }
6462
6463 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6465 mSettings.mPreferredActivities.addFilter(
6466 new PreferredActivity(filter, match, set, activity));
6467 mSettings.writeLP();
6468 }
6469 }
6470
Satish Sampath8dbe6122009-06-02 23:35:54 +01006471 public void replacePreferredActivity(IntentFilter filter, int match,
6472 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006473 if (filter.countActions() != 1) {
6474 throw new IllegalArgumentException(
6475 "replacePreferredActivity expects filter to have only 1 action.");
6476 }
6477 if (filter.countCategories() != 1) {
6478 throw new IllegalArgumentException(
6479 "replacePreferredActivity expects filter to have only 1 category.");
6480 }
6481 if (filter.countDataAuthorities() != 0
6482 || filter.countDataPaths() != 0
6483 || filter.countDataSchemes() != 0
6484 || filter.countDataTypes() != 0) {
6485 throw new IllegalArgumentException(
6486 "replacePreferredActivity expects filter to have no data authorities, " +
6487 "paths, schemes or types.");
6488 }
6489 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006490 if (mContext.checkCallingOrSelfPermission(
6491 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6492 != PackageManager.PERMISSION_GRANTED) {
6493 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6494 < Build.VERSION_CODES.FROYO) {
6495 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6496 + Binder.getCallingUid());
6497 return;
6498 }
6499 mContext.enforceCallingOrSelfPermission(
6500 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6501 }
6502
Satish Sampath8dbe6122009-06-02 23:35:54 +01006503 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6504 String action = filter.getAction(0);
6505 String category = filter.getCategory(0);
6506 while (it.hasNext()) {
6507 PreferredActivity pa = it.next();
6508 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6509 it.remove();
6510 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6511 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6512 }
6513 }
6514 addPreferredActivity(filter, match, set, activity);
6515 }
6516 }
6517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006520 int uid = Binder.getCallingUid();
6521 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006522 if (pkg == null || pkg.applicationInfo.uid != uid) {
6523 if (mContext.checkCallingOrSelfPermission(
6524 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6525 != PackageManager.PERMISSION_GRANTED) {
6526 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6527 < Build.VERSION_CODES.FROYO) {
6528 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6529 + Binder.getCallingUid());
6530 return;
6531 }
6532 mContext.enforceCallingOrSelfPermission(
6533 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6534 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006535 }
6536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 if (clearPackagePreferredActivitiesLP(packageName)) {
6538 mSettings.writeLP();
6539 }
6540 }
6541 }
6542
6543 boolean clearPackagePreferredActivitiesLP(String packageName) {
6544 boolean changed = false;
6545 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6546 while (it.hasNext()) {
6547 PreferredActivity pa = it.next();
6548 if (pa.mActivity.getPackageName().equals(packageName)) {
6549 it.remove();
6550 changed = true;
6551 }
6552 }
6553 return changed;
6554 }
6555
6556 public int getPreferredActivities(List<IntentFilter> outFilters,
6557 List<ComponentName> outActivities, String packageName) {
6558
6559 int num = 0;
6560 synchronized (mPackages) {
6561 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6562 while (it.hasNext()) {
6563 PreferredActivity pa = it.next();
6564 if (packageName == null
6565 || pa.mActivity.getPackageName().equals(packageName)) {
6566 if (outFilters != null) {
6567 outFilters.add(new IntentFilter(pa));
6568 }
6569 if (outActivities != null) {
6570 outActivities.add(pa.mActivity);
6571 }
6572 }
6573 }
6574 }
6575
6576 return num;
6577 }
6578
6579 public void setApplicationEnabledSetting(String appPackageName,
6580 int newState, int flags) {
6581 setEnabledSetting(appPackageName, null, newState, flags);
6582 }
6583
6584 public void setComponentEnabledSetting(ComponentName componentName,
6585 int newState, int flags) {
6586 setEnabledSetting(componentName.getPackageName(),
6587 componentName.getClassName(), newState, flags);
6588 }
6589
6590 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006591 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6593 || newState == COMPONENT_ENABLED_STATE_ENABLED
6594 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6595 throw new IllegalArgumentException("Invalid new component state: "
6596 + newState);
6597 }
6598 PackageSetting pkgSetting;
6599 final int uid = Binder.getCallingUid();
6600 final int permission = mContext.checkCallingPermission(
6601 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6602 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006603 boolean sendNow = false;
6604 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006605 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006607 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006609 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006611 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006613 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 }
6615 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006616 "Unknown component: " + packageName
6617 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 }
6619 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6620 throw new SecurityException(
6621 "Permission Denial: attempt to change component state from pid="
6622 + Binder.getCallingPid()
6623 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6624 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006625 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006626 // We're dealing with an application/package level state change
6627 pkgSetting.enabled = newState;
6628 } else {
6629 // We're dealing with a component level state change
6630 switch (newState) {
6631 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006632 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 break;
6634 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006635 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006636 break;
6637 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006638 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 break;
6640 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006641 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006642 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006643 }
6644 }
6645 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006646 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006647 components = mPendingBroadcasts.get(packageName);
6648 boolean newPackage = components == null;
6649 if (newPackage) {
6650 components = new ArrayList<String>();
6651 }
6652 if (!components.contains(componentName)) {
6653 components.add(componentName);
6654 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006655 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6656 sendNow = true;
6657 // Purge entry from pending broadcast list if another one exists already
6658 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006659 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006660 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006661 if (newPackage) {
6662 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006663 }
6664 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6665 // Schedule a message
6666 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6667 }
6668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 long callingId = Binder.clearCallingIdentity();
6672 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006673 if (sendNow) {
6674 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006675 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677 } finally {
6678 Binder.restoreCallingIdentity(callingId);
6679 }
6680 }
6681
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006682 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006683 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6684 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6685 + " components=" + componentNames);
6686 Bundle extras = new Bundle(4);
6687 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6688 String nameList[] = new String[componentNames.size()];
6689 componentNames.toArray(nameList);
6690 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006691 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6692 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006693 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006694 }
6695
Jacek Surazski65e13172009-04-28 15:26:38 +02006696 public String getInstallerPackageName(String packageName) {
6697 synchronized (mPackages) {
6698 PackageSetting pkg = mSettings.mPackages.get(packageName);
6699 if (pkg == null) {
6700 throw new IllegalArgumentException("Unknown package: " + packageName);
6701 }
6702 return pkg.installerPackageName;
6703 }
6704 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 public int getApplicationEnabledSetting(String appPackageName) {
6707 synchronized (mPackages) {
6708 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6709 if (pkg == null) {
6710 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6711 }
6712 return pkg.enabled;
6713 }
6714 }
6715
6716 public int getComponentEnabledSetting(ComponentName componentName) {
6717 synchronized (mPackages) {
6718 final String packageNameStr = componentName.getPackageName();
6719 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6720 if (pkg == null) {
6721 throw new IllegalArgumentException("Unknown component: " + componentName);
6722 }
6723 final String classNameStr = componentName.getClassName();
6724 return pkg.currentEnabledStateLP(classNameStr);
6725 }
6726 }
6727
6728 public void enterSafeMode() {
6729 if (!mSystemReady) {
6730 mSafeMode = true;
6731 }
6732 }
6733
6734 public void systemReady() {
6735 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006736
6737 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006738 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006739 mContext.getContentResolver(),
6740 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006741 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006742 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006743 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 }
6746
6747 public boolean isSafeMode() {
6748 return mSafeMode;
6749 }
6750
6751 public boolean hasSystemUidErrors() {
6752 return mHasSystemUidErrors;
6753 }
6754
6755 static String arrayToString(int[] array) {
6756 StringBuffer buf = new StringBuffer(128);
6757 buf.append('[');
6758 if (array != null) {
6759 for (int i=0; i<array.length; i++) {
6760 if (i > 0) buf.append(", ");
6761 buf.append(array[i]);
6762 }
6763 }
6764 buf.append(']');
6765 return buf.toString();
6766 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 @Override
6769 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6770 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6771 != PackageManager.PERMISSION_GRANTED) {
6772 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6773 + Binder.getCallingPid()
6774 + ", uid=" + Binder.getCallingUid()
6775 + " without permission "
6776 + android.Manifest.permission.DUMP);
6777 return;
6778 }
6779
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006780 String packageName = null;
6781
6782 int opti = 0;
6783 while (opti < args.length) {
6784 String opt = args[opti];
6785 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6786 break;
6787 }
6788 opti++;
6789 if ("-a".equals(opt)) {
6790 // Right now we only know how to print all.
6791 } else if ("-h".equals(opt)) {
6792 pw.println("Package manager dump options:");
6793 pw.println(" [-h] [cmd] ...");
6794 pw.println(" cmd may be one of:");
6795 pw.println(" [package.name]: info about given package");
6796 return;
6797 } else {
6798 pw.println("Unknown argument: " + opt + "; use -h for help");
6799 }
6800 }
6801
6802 // Is the caller requesting to dump a particular piece of data?
6803 if (opti < args.length) {
6804 String cmd = args[opti];
6805 opti++;
6806 // Is this a package name?
6807 if ("android".equals(cmd) || cmd.contains(".")) {
6808 packageName = cmd;
6809 }
6810 }
6811
6812 boolean printedTitle = false;
6813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006814 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006815 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6816 printedTitle = true;
6817 }
6818 if (mReceivers.dump(pw, printedTitle
6819 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6820 " ", packageName)) {
6821 printedTitle = true;
6822 }
6823 if (mServices.dump(pw, printedTitle
6824 ? "\nService Resolver Table:" : "Service Resolver Table:",
6825 " ", packageName)) {
6826 printedTitle = true;
6827 }
6828 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6829 ? "\nPreferred Activities:" : "Preferred Activities:",
6830 " ", packageName)) {
6831 printedTitle = true;
6832 }
6833 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006834 {
6835 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006836 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6837 continue;
6838 }
6839 if (!printedSomething) {
6840 if (printedTitle) pw.println(" ");
6841 pw.println("Permissions:");
6842 printedSomething = true;
6843 printedTitle = true;
6844 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006845 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6846 pw.print(Integer.toHexString(System.identityHashCode(p)));
6847 pw.println("):");
6848 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6849 pw.print(" uid="); pw.print(p.uid);
6850 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006851 pw.print(" type="); pw.print(p.type);
6852 pw.print(" prot="); pw.println(p.protectionLevel);
6853 if (p.packageSetting != null) {
6854 pw.print(" packageSetting="); pw.println(p.packageSetting);
6855 }
6856 if (p.perm != null) {
6857 pw.print(" perm="); pw.println(p.perm);
6858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006859 }
6860 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006861 printedSomething = false;
6862 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 {
6864 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006865 if (packageName != null && !packageName.equals(ps.realName)
6866 && !packageName.equals(ps.name)) {
6867 continue;
6868 }
6869 if (!printedSomething) {
6870 if (printedTitle) pw.println(" ");
6871 pw.println("Packages:");
6872 printedSomething = true;
6873 printedTitle = true;
6874 }
6875 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006876 pw.print(" Package [");
6877 pw.print(ps.realName != null ? ps.realName : ps.name);
6878 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006879 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6880 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006881 if (ps.realName != null) {
6882 pw.print(" compat name="); pw.println(ps.name);
6883 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006884 pw.print(" userId="); pw.print(ps.userId);
6885 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6886 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6887 pw.print(" pkg="); pw.println(ps.pkg);
6888 pw.print(" codePath="); pw.println(ps.codePathString);
6889 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006890 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006891 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006892 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006893 pw.print(" supportsScreens=[");
6894 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006895 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006896 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006897 if (!first) pw.print(", ");
6898 first = false;
6899 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006900 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006901 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006902 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006903 if (!first) pw.print(", ");
6904 first = false;
6905 pw.print("large");
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_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006909 if (!first) pw.print(", ");
6910 first = false;
6911 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006913 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006914 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006915 if (!first) pw.print(", ");
6916 first = false;
6917 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006918 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006919 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006920 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6921 if (!first) pw.print(", ");
6922 first = false;
6923 pw.print("anyDensity");
6924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006925 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006926 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006927 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6928 pw.print(" signatures="); pw.println(ps.signatures);
6929 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6930 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6931 pw.print(" installStatus="); pw.print(ps.installStatus);
6932 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006933 if (ps.disabledComponents.size() > 0) {
6934 pw.println(" disabledComponents:");
6935 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006936 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006937 }
6938 }
6939 if (ps.enabledComponents.size() > 0) {
6940 pw.println(" enabledComponents:");
6941 for (String s : ps.enabledComponents) {
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 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006945 if (ps.grantedPermissions.size() > 0) {
6946 pw.println(" grantedPermissions:");
6947 for (String s : ps.grantedPermissions) {
6948 pw.print(" "); pw.println(s);
6949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006950 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006951 if (ps.loadedPermissions.size() > 0) {
6952 pw.println(" loadedPermissions:");
6953 for (String s : ps.loadedPermissions) {
6954 pw.print(" "); pw.println(s);
6955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006956 }
6957 }
6958 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006959 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006960 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006961 for (HashMap.Entry<String, String> e
6962 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006963 if (packageName != null && !packageName.equals(e.getKey())
6964 && !packageName.equals(e.getValue())) {
6965 continue;
6966 }
6967 if (!printedSomething) {
6968 if (printedTitle) pw.println(" ");
6969 pw.println("Renamed packages:");
6970 printedSomething = true;
6971 printedTitle = true;
6972 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006973 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6974 pw.println(e.getValue());
6975 }
6976 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006977 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006978 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006979 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006980 if (packageName != null && !packageName.equals(ps.realName)
6981 && !packageName.equals(ps.name)) {
6982 continue;
6983 }
6984 if (!printedSomething) {
6985 if (printedTitle) pw.println(" ");
6986 pw.println("Hidden system packages:");
6987 printedSomething = true;
6988 printedTitle = true;
6989 }
6990 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006991 pw.print(ps.realName != null ? ps.realName : ps.name);
6992 pw.print("] (");
6993 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6994 pw.println("):");
6995 if (ps.realName != null) {
6996 pw.print(" compat name="); pw.println(ps.name);
6997 }
6998 pw.print(" userId="); pw.println(ps.userId);
6999 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7000 pw.print(" codePath="); pw.println(ps.codePathString);
7001 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7002 }
7003 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007004 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007005 {
7006 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007007 if (packageName != null && su != packageSharedUser) {
7008 continue;
7009 }
7010 if (!printedSomething) {
7011 if (printedTitle) pw.println(" ");
7012 pw.println("Shared users:");
7013 printedSomething = true;
7014 printedTitle = true;
7015 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007016 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7017 pw.print(Integer.toHexString(System.identityHashCode(su)));
7018 pw.println("):");
7019 pw.print(" userId="); pw.print(su.userId);
7020 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 pw.println(" grantedPermissions:");
7022 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007023 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007024 }
7025 pw.println(" loadedPermissions:");
7026 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007027 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 }
7029 }
7030 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007031
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007032 if (packageName == null) {
7033 if (printedTitle) pw.println(" ");
7034 printedTitle = true;
7035 pw.println("Settings parse messages:");
7036 pw.println(mSettings.mReadMessages.toString());
7037
7038 pw.println(" ");
7039 pw.println("Package warning messages:");
7040 File fname = getSettingsProblemFile();
7041 FileInputStream in;
7042 try {
7043 in = new FileInputStream(fname);
7044 int avail = in.available();
7045 byte[] data = new byte[avail];
7046 in.read(data);
7047 pw.println(new String(data));
7048 } catch (FileNotFoundException e) {
7049 } catch (IOException e) {
7050 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007052 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007053
7054 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007055 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007056 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007057 if (packageName != null && !packageName.equals(p.info.packageName)) {
7058 continue;
7059 }
7060 if (!printedSomething) {
7061 if (printedTitle) pw.println(" ");
7062 pw.println("Registered ContentProviders:");
7063 printedSomething = true;
7064 printedTitle = true;
7065 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007066 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007067 pw.println(p.toString());
7068 }
7069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007070 }
7071
7072 static final class BasePermission {
7073 final static int TYPE_NORMAL = 0;
7074 final static int TYPE_BUILTIN = 1;
7075 final static int TYPE_DYNAMIC = 2;
7076
7077 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007078 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007079 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007080 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007081 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007082 PackageParser.Permission perm;
7083 PermissionInfo pendingInfo;
7084 int uid;
7085 int[] gids;
7086
7087 BasePermission(String _name, String _sourcePackage, int _type) {
7088 name = _name;
7089 sourcePackage = _sourcePackage;
7090 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007091 // Default to most conservative protection level.
7092 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7093 }
7094
7095 public String toString() {
7096 return "BasePermission{"
7097 + Integer.toHexString(System.identityHashCode(this))
7098 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007099 }
7100 }
7101
7102 static class PackageSignatures {
7103 private Signature[] mSignatures;
7104
7105 PackageSignatures(Signature[] sigs) {
7106 assignSignatures(sigs);
7107 }
7108
7109 PackageSignatures() {
7110 }
7111
7112 void writeXml(XmlSerializer serializer, String tagName,
7113 ArrayList<Signature> pastSignatures) throws IOException {
7114 if (mSignatures == null) {
7115 return;
7116 }
7117 serializer.startTag(null, tagName);
7118 serializer.attribute(null, "count",
7119 Integer.toString(mSignatures.length));
7120 for (int i=0; i<mSignatures.length; i++) {
7121 serializer.startTag(null, "cert");
7122 final Signature sig = mSignatures[i];
7123 final int sigHash = sig.hashCode();
7124 final int numPast = pastSignatures.size();
7125 int j;
7126 for (j=0; j<numPast; j++) {
7127 Signature pastSig = pastSignatures.get(j);
7128 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7129 serializer.attribute(null, "index", Integer.toString(j));
7130 break;
7131 }
7132 }
7133 if (j >= numPast) {
7134 pastSignatures.add(sig);
7135 serializer.attribute(null, "index", Integer.toString(numPast));
7136 serializer.attribute(null, "key", sig.toCharsString());
7137 }
7138 serializer.endTag(null, "cert");
7139 }
7140 serializer.endTag(null, tagName);
7141 }
7142
7143 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7144 throws IOException, XmlPullParserException {
7145 String countStr = parser.getAttributeValue(null, "count");
7146 if (countStr == null) {
7147 reportSettingsProblem(Log.WARN,
7148 "Error in package manager settings: <signatures> has"
7149 + " no count at " + parser.getPositionDescription());
7150 XmlUtils.skipCurrentTag(parser);
7151 }
7152 final int count = Integer.parseInt(countStr);
7153 mSignatures = new Signature[count];
7154 int pos = 0;
7155
7156 int outerDepth = parser.getDepth();
7157 int type;
7158 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7159 && (type != XmlPullParser.END_TAG
7160 || parser.getDepth() > outerDepth)) {
7161 if (type == XmlPullParser.END_TAG
7162 || type == XmlPullParser.TEXT) {
7163 continue;
7164 }
7165
7166 String tagName = parser.getName();
7167 if (tagName.equals("cert")) {
7168 if (pos < count) {
7169 String index = parser.getAttributeValue(null, "index");
7170 if (index != null) {
7171 try {
7172 int idx = Integer.parseInt(index);
7173 String key = parser.getAttributeValue(null, "key");
7174 if (key == null) {
7175 if (idx >= 0 && idx < pastSignatures.size()) {
7176 Signature sig = pastSignatures.get(idx);
7177 if (sig != null) {
7178 mSignatures[pos] = pastSignatures.get(idx);
7179 pos++;
7180 } else {
7181 reportSettingsProblem(Log.WARN,
7182 "Error in package manager settings: <cert> "
7183 + "index " + index + " is not defined at "
7184 + parser.getPositionDescription());
7185 }
7186 } else {
7187 reportSettingsProblem(Log.WARN,
7188 "Error in package manager settings: <cert> "
7189 + "index " + index + " is out of bounds at "
7190 + parser.getPositionDescription());
7191 }
7192 } else {
7193 while (pastSignatures.size() <= idx) {
7194 pastSignatures.add(null);
7195 }
7196 Signature sig = new Signature(key);
7197 pastSignatures.set(idx, sig);
7198 mSignatures[pos] = sig;
7199 pos++;
7200 }
7201 } catch (NumberFormatException e) {
7202 reportSettingsProblem(Log.WARN,
7203 "Error in package manager settings: <cert> "
7204 + "index " + index + " is not a number at "
7205 + parser.getPositionDescription());
7206 }
7207 } else {
7208 reportSettingsProblem(Log.WARN,
7209 "Error in package manager settings: <cert> has"
7210 + " no index at " + parser.getPositionDescription());
7211 }
7212 } else {
7213 reportSettingsProblem(Log.WARN,
7214 "Error in package manager settings: too "
7215 + "many <cert> tags, expected " + count
7216 + " at " + parser.getPositionDescription());
7217 }
7218 } else {
7219 reportSettingsProblem(Log.WARN,
7220 "Unknown element under <cert>: "
7221 + parser.getName());
7222 }
7223 XmlUtils.skipCurrentTag(parser);
7224 }
7225
7226 if (pos < count) {
7227 // Should never happen -- there is an error in the written
7228 // settings -- but if it does we don't want to generate
7229 // a bad array.
7230 Signature[] newSigs = new Signature[pos];
7231 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7232 mSignatures = newSigs;
7233 }
7234 }
7235
7236 /**
7237 * If any of the given 'sigs' is contained in the existing signatures,
7238 * then completely replace the current signatures with the ones in
7239 * 'sigs'. This is used for updating an existing package to a newly
7240 * installed version.
7241 */
7242 boolean updateSignatures(Signature[] sigs, boolean update) {
7243 if (mSignatures == null) {
7244 if (update) {
7245 assignSignatures(sigs);
7246 }
7247 return true;
7248 }
7249 if (sigs == null) {
7250 return false;
7251 }
7252
7253 for (int i=0; i<sigs.length; i++) {
7254 Signature sig = sigs[i];
7255 for (int j=0; j<mSignatures.length; j++) {
7256 if (mSignatures[j].equals(sig)) {
7257 if (update) {
7258 assignSignatures(sigs);
7259 }
7260 return true;
7261 }
7262 }
7263 }
7264 return false;
7265 }
7266
7267 /**
7268 * If any of the given 'sigs' is contained in the existing signatures,
7269 * then add in any new signatures found in 'sigs'. This is used for
7270 * including a new package into an existing shared user id.
7271 */
7272 boolean mergeSignatures(Signature[] sigs, boolean update) {
7273 if (mSignatures == null) {
7274 if (update) {
7275 assignSignatures(sigs);
7276 }
7277 return true;
7278 }
7279 if (sigs == null) {
7280 return false;
7281 }
7282
7283 Signature[] added = null;
7284 int addedCount = 0;
7285 boolean haveMatch = false;
7286 for (int i=0; i<sigs.length; i++) {
7287 Signature sig = sigs[i];
7288 boolean found = false;
7289 for (int j=0; j<mSignatures.length; j++) {
7290 if (mSignatures[j].equals(sig)) {
7291 found = true;
7292 haveMatch = true;
7293 break;
7294 }
7295 }
7296
7297 if (!found) {
7298 if (added == null) {
7299 added = new Signature[sigs.length];
7300 }
7301 added[i] = sig;
7302 addedCount++;
7303 }
7304 }
7305
7306 if (!haveMatch) {
7307 // Nothing matched -- reject the new signatures.
7308 return false;
7309 }
7310 if (added == null) {
7311 // Completely matched -- nothing else to do.
7312 return true;
7313 }
7314
7315 // Add additional signatures in.
7316 if (update) {
7317 Signature[] total = new Signature[addedCount+mSignatures.length];
7318 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
7319 int j = mSignatures.length;
7320 for (int i=0; i<added.length; i++) {
7321 if (added[i] != null) {
7322 total[j] = added[i];
7323 j++;
7324 }
7325 }
7326 mSignatures = total;
7327 }
7328 return true;
7329 }
7330
7331 private void assignSignatures(Signature[] sigs) {
7332 if (sigs == null) {
7333 mSignatures = null;
7334 return;
7335 }
7336 mSignatures = new Signature[sigs.length];
7337 for (int i=0; i<sigs.length; i++) {
7338 mSignatures[i] = sigs[i];
7339 }
7340 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342 @Override
7343 public String toString() {
7344 StringBuffer buf = new StringBuffer(128);
7345 buf.append("PackageSignatures{");
7346 buf.append(Integer.toHexString(System.identityHashCode(this)));
7347 buf.append(" [");
7348 if (mSignatures != null) {
7349 for (int i=0; i<mSignatures.length; i++) {
7350 if (i > 0) buf.append(", ");
7351 buf.append(Integer.toHexString(
7352 System.identityHashCode(mSignatures[i])));
7353 }
7354 }
7355 buf.append("]}");
7356 return buf.toString();
7357 }
7358 }
7359
7360 static class PreferredActivity extends IntentFilter {
7361 final int mMatch;
7362 final String[] mSetPackages;
7363 final String[] mSetClasses;
7364 final String[] mSetComponents;
7365 final ComponentName mActivity;
7366 final String mShortActivity;
7367 String mParseError;
7368
7369 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7370 ComponentName activity) {
7371 super(filter);
7372 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7373 mActivity = activity;
7374 mShortActivity = activity.flattenToShortString();
7375 mParseError = null;
7376 if (set != null) {
7377 final int N = set.length;
7378 String[] myPackages = new String[N];
7379 String[] myClasses = new String[N];
7380 String[] myComponents = new String[N];
7381 for (int i=0; i<N; i++) {
7382 ComponentName cn = set[i];
7383 if (cn == null) {
7384 mSetPackages = null;
7385 mSetClasses = null;
7386 mSetComponents = null;
7387 return;
7388 }
7389 myPackages[i] = cn.getPackageName().intern();
7390 myClasses[i] = cn.getClassName().intern();
7391 myComponents[i] = cn.flattenToShortString().intern();
7392 }
7393 mSetPackages = myPackages;
7394 mSetClasses = myClasses;
7395 mSetComponents = myComponents;
7396 } else {
7397 mSetPackages = null;
7398 mSetClasses = null;
7399 mSetComponents = null;
7400 }
7401 }
7402
7403 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7404 IOException {
7405 mShortActivity = parser.getAttributeValue(null, "name");
7406 mActivity = ComponentName.unflattenFromString(mShortActivity);
7407 if (mActivity == null) {
7408 mParseError = "Bad activity name " + mShortActivity;
7409 }
7410 String matchStr = parser.getAttributeValue(null, "match");
7411 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7412 String setCountStr = parser.getAttributeValue(null, "set");
7413 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7414
7415 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7416 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7417 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7418
7419 int setPos = 0;
7420
7421 int outerDepth = parser.getDepth();
7422 int type;
7423 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7424 && (type != XmlPullParser.END_TAG
7425 || parser.getDepth() > outerDepth)) {
7426 if (type == XmlPullParser.END_TAG
7427 || type == XmlPullParser.TEXT) {
7428 continue;
7429 }
7430
7431 String tagName = parser.getName();
7432 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7433 // + parser.getDepth() + " tag=" + tagName);
7434 if (tagName.equals("set")) {
7435 String name = parser.getAttributeValue(null, "name");
7436 if (name == null) {
7437 if (mParseError == null) {
7438 mParseError = "No name in set tag in preferred activity "
7439 + mShortActivity;
7440 }
7441 } else if (setPos >= setCount) {
7442 if (mParseError == null) {
7443 mParseError = "Too many set tags in preferred activity "
7444 + mShortActivity;
7445 }
7446 } else {
7447 ComponentName cn = ComponentName.unflattenFromString(name);
7448 if (cn == null) {
7449 if (mParseError == null) {
7450 mParseError = "Bad set name " + name + " in preferred activity "
7451 + mShortActivity;
7452 }
7453 } else {
7454 myPackages[setPos] = cn.getPackageName();
7455 myClasses[setPos] = cn.getClassName();
7456 myComponents[setPos] = name;
7457 setPos++;
7458 }
7459 }
7460 XmlUtils.skipCurrentTag(parser);
7461 } else if (tagName.equals("filter")) {
7462 //Log.i(TAG, "Starting to parse filter...");
7463 readFromXml(parser);
7464 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7465 // + parser.getDepth() + " tag=" + parser.getName());
7466 } else {
7467 reportSettingsProblem(Log.WARN,
7468 "Unknown element under <preferred-activities>: "
7469 + parser.getName());
7470 XmlUtils.skipCurrentTag(parser);
7471 }
7472 }
7473
7474 if (setPos != setCount) {
7475 if (mParseError == null) {
7476 mParseError = "Not enough set tags (expected " + setCount
7477 + " but found " + setPos + ") in " + mShortActivity;
7478 }
7479 }
7480
7481 mSetPackages = myPackages;
7482 mSetClasses = myClasses;
7483 mSetComponents = myComponents;
7484 }
7485
7486 public void writeToXml(XmlSerializer serializer) throws IOException {
7487 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7488 serializer.attribute(null, "name", mShortActivity);
7489 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7490 serializer.attribute(null, "set", Integer.toString(NS));
7491 for (int s=0; s<NS; s++) {
7492 serializer.startTag(null, "set");
7493 serializer.attribute(null, "name", mSetComponents[s]);
7494 serializer.endTag(null, "set");
7495 }
7496 serializer.startTag(null, "filter");
7497 super.writeToXml(serializer);
7498 serializer.endTag(null, "filter");
7499 }
7500
7501 boolean sameSet(List<ResolveInfo> query, int priority) {
7502 if (mSetPackages == null) return false;
7503 final int NQ = query.size();
7504 final int NS = mSetPackages.length;
7505 int numMatch = 0;
7506 for (int i=0; i<NQ; i++) {
7507 ResolveInfo ri = query.get(i);
7508 if (ri.priority != priority) continue;
7509 ActivityInfo ai = ri.activityInfo;
7510 boolean good = false;
7511 for (int j=0; j<NS; j++) {
7512 if (mSetPackages[j].equals(ai.packageName)
7513 && mSetClasses[j].equals(ai.name)) {
7514 numMatch++;
7515 good = true;
7516 break;
7517 }
7518 }
7519 if (!good) return false;
7520 }
7521 return numMatch == NS;
7522 }
7523 }
7524
7525 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007526 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007528 HashSet<String> grantedPermissions = new HashSet<String>();
7529 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007531 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007534 setFlags(pkgFlags);
7535 }
7536
7537 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007538 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007539 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08007540 (pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) |
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08007541 (pkgFlags & ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 }
7543 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007545 /**
7546 * Settings base class for pending and resolved classes.
7547 */
7548 static class PackageSettingBase extends GrantedPermissions {
7549 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007550 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007551 File codePath;
7552 String codePathString;
7553 File resourcePath;
7554 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007555 private long timeStamp;
7556 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007557 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007558
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007559 boolean uidError;
7560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007561 PackageSignatures signatures = new PackageSignatures();
7562
7563 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007565 /* Explicitly disabled components */
7566 HashSet<String> disabledComponents = new HashSet<String>(0);
7567 /* Explicitly enabled components */
7568 HashSet<String> enabledComponents = new HashSet<String>(0);
7569 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7570 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007571
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007572 PackageSettingBase origPackage;
7573
Jacek Surazski65e13172009-04-28 15:26:38 +02007574 /* package name of the app that installed this package */
7575 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007576
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007577 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007578 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007579 super(pkgFlags);
7580 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007581 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007582 init(codePath, resourcePath, pVersionCode);
7583 }
7584
7585 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007586 this.codePath = codePath;
7587 this.codePathString = codePath.toString();
7588 this.resourcePath = resourcePath;
7589 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007590 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007591 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007592
Jacek Surazski65e13172009-04-28 15:26:38 +02007593 public void setInstallerPackageName(String packageName) {
7594 installerPackageName = packageName;
7595 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007596
Jacek Surazski65e13172009-04-28 15:26:38 +02007597 String getInstallerPackageName() {
7598 return installerPackageName;
7599 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007601 public void setInstallStatus(int newStatus) {
7602 installStatus = newStatus;
7603 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007605 public int getInstallStatus() {
7606 return installStatus;
7607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007609 public void setTimeStamp(long newStamp) {
7610 if (newStamp != timeStamp) {
7611 timeStamp = newStamp;
7612 timeStampString = Long.toString(newStamp);
7613 }
7614 }
7615
7616 public void setTimeStamp(long newStamp, String newStampStr) {
7617 timeStamp = newStamp;
7618 timeStampString = newStampStr;
7619 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007621 public long getTimeStamp() {
7622 return timeStamp;
7623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007625 public String getTimeStampStr() {
7626 return timeStampString;
7627 }
7628
7629 public void copyFrom(PackageSettingBase base) {
7630 grantedPermissions = base.grantedPermissions;
7631 gids = base.gids;
7632 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007634 timeStamp = base.timeStamp;
7635 timeStampString = base.timeStampString;
7636 signatures = base.signatures;
7637 permissionsFixed = base.permissionsFixed;
7638 disabledComponents = base.disabledComponents;
7639 enabledComponents = base.enabledComponents;
7640 enabled = base.enabled;
7641 installStatus = base.installStatus;
7642 }
7643
7644 void enableComponentLP(String componentClassName) {
7645 disabledComponents.remove(componentClassName);
7646 enabledComponents.add(componentClassName);
7647 }
7648
7649 void disableComponentLP(String componentClassName) {
7650 enabledComponents.remove(componentClassName);
7651 disabledComponents.add(componentClassName);
7652 }
7653
7654 void restoreComponentLP(String componentClassName) {
7655 enabledComponents.remove(componentClassName);
7656 disabledComponents.remove(componentClassName);
7657 }
7658
7659 int currentEnabledStateLP(String componentName) {
7660 if (enabledComponents.contains(componentName)) {
7661 return COMPONENT_ENABLED_STATE_ENABLED;
7662 } else if (disabledComponents.contains(componentName)) {
7663 return COMPONENT_ENABLED_STATE_DISABLED;
7664 } else {
7665 return COMPONENT_ENABLED_STATE_DEFAULT;
7666 }
7667 }
7668 }
7669
7670 /**
7671 * Settings data for a particular package we know about.
7672 */
7673 static final class PackageSetting extends PackageSettingBase {
7674 int userId;
7675 PackageParser.Package pkg;
7676 SharedUserSetting sharedUser;
7677
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007678 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007679 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007680 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007681 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007683 @Override
7684 public String toString() {
7685 return "PackageSetting{"
7686 + Integer.toHexString(System.identityHashCode(this))
7687 + " " + name + "/" + userId + "}";
7688 }
7689 }
7690
7691 /**
7692 * Settings data for a particular shared user ID we know about.
7693 */
7694 static final class SharedUserSetting extends GrantedPermissions {
7695 final String name;
7696 int userId;
7697 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7698 final PackageSignatures signatures = new PackageSignatures();
7699
7700 SharedUserSetting(String _name, int _pkgFlags) {
7701 super(_pkgFlags);
7702 name = _name;
7703 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007705 @Override
7706 public String toString() {
7707 return "SharedUserSetting{"
7708 + Integer.toHexString(System.identityHashCode(this))
7709 + " " + name + "/" + userId + "}";
7710 }
7711 }
7712
7713 /**
7714 * Holds information about dynamic settings.
7715 */
7716 private static final class Settings {
7717 private final File mSettingsFilename;
7718 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007719 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007720 private final HashMap<String, PackageSetting> mPackages =
7721 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722 // List of replaced system applications
7723 final HashMap<String, PackageSetting> mDisabledSysPackages =
7724 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726 // The user's preferred activities associated with particular intent
7727 // filters.
7728 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7729 new IntentResolver<PreferredActivity, PreferredActivity>() {
7730 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007731 protected String packageForFilter(PreferredActivity filter) {
7732 return filter.mActivity.getPackageName();
7733 }
7734 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007735 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007737 out.print(prefix); out.print(
7738 Integer.toHexString(System.identityHashCode(filter)));
7739 out.print(' ');
7740 out.print(filter.mActivity.flattenToShortString());
7741 out.print(" match=0x");
7742 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007743 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007744 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007745 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007746 out.print(prefix); out.print(" ");
7747 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 }
7749 }
7750 }
7751 };
7752 private final HashMap<String, SharedUserSetting> mSharedUsers =
7753 new HashMap<String, SharedUserSetting>();
7754 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7755 private final SparseArray<Object> mOtherUserIds =
7756 new SparseArray<Object>();
7757
7758 // For reading/writing settings file.
7759 private final ArrayList<Signature> mPastSignatures =
7760 new ArrayList<Signature>();
7761
7762 // Mapping from permission names to info about them.
7763 final HashMap<String, BasePermission> mPermissions =
7764 new HashMap<String, BasePermission>();
7765
7766 // Mapping from permission tree names to info about them.
7767 final HashMap<String, BasePermission> mPermissionTrees =
7768 new HashMap<String, BasePermission>();
7769
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007770 // Packages that have been uninstalled and still need their external
7771 // storage data deleted.
7772 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7773
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007774 // Packages that have been renamed since they were first installed.
7775 // Keys are the new names of the packages, values are the original
7776 // names. The packages appear everwhere else under their original
7777 // names.
7778 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 private final StringBuilder mReadMessages = new StringBuilder();
7781
7782 private static final class PendingPackage extends PackageSettingBase {
7783 final int sharedId;
7784
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007785 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007786 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007787 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 this.sharedId = sharedId;
7789 }
7790 }
7791 private final ArrayList<PendingPackage> mPendingPackages
7792 = new ArrayList<PendingPackage>();
7793
7794 Settings() {
7795 File dataDir = Environment.getDataDirectory();
7796 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007797 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7798 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007799 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007800 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 FileUtils.setPermissions(systemDir.toString(),
7802 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7803 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7804 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007805 FileUtils.setPermissions(systemSecureDir.toString(),
7806 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7807 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7808 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 mSettingsFilename = new File(systemDir, "packages.xml");
7810 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007811 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007812 }
7813
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007814 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007815 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816 int pkgFlags, boolean create, boolean add) {
7817 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007818 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007819 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007820 return p;
7821 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007822
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007823 PackageSetting peekPackageLP(String name) {
7824 return mPackages.get(name);
7825 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 PackageSetting p = mPackages.get(name);
7827 if (p != null && p.codePath.getPath().equals(codePath)) {
7828 return p;
7829 }
7830 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007831 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007832 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007834 void setInstallStatus(String pkgName, int status) {
7835 PackageSetting p = mPackages.get(pkgName);
7836 if(p != null) {
7837 if(p.getInstallStatus() != status) {
7838 p.setInstallStatus(status);
7839 }
7840 }
7841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007842
Jacek Surazski65e13172009-04-28 15:26:38 +02007843 void setInstallerPackageName(String pkgName,
7844 String installerPkgName) {
7845 PackageSetting p = mPackages.get(pkgName);
7846 if(p != null) {
7847 p.setInstallerPackageName(installerPkgName);
7848 }
7849 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007850
Jacek Surazski65e13172009-04-28 15:26:38 +02007851 String getInstallerPackageName(String pkgName) {
7852 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007853 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007854 }
7855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 int getInstallStatus(String pkgName) {
7857 PackageSetting p = mPackages.get(pkgName);
7858 if(p != null) {
7859 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 return -1;
7862 }
7863
7864 SharedUserSetting getSharedUserLP(String name,
7865 int pkgFlags, boolean create) {
7866 SharedUserSetting s = mSharedUsers.get(name);
7867 if (s == null) {
7868 if (!create) {
7869 return null;
7870 }
7871 s = new SharedUserSetting(name, pkgFlags);
7872 if (MULTIPLE_APPLICATION_UIDS) {
7873 s.userId = newUserIdLP(s);
7874 } else {
7875 s.userId = FIRST_APPLICATION_UID;
7876 }
7877 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7878 // < 0 means we couldn't assign a userid; fall out and return
7879 // s, which is currently null
7880 if (s.userId >= 0) {
7881 mSharedUsers.put(name, s);
7882 }
7883 }
7884
7885 return s;
7886 }
7887
7888 int disableSystemPackageLP(String name) {
7889 PackageSetting p = mPackages.get(name);
7890 if(p == null) {
7891 Log.w(TAG, "Package:"+name+" is not an installed package");
7892 return -1;
7893 }
7894 PackageSetting dp = mDisabledSysPackages.get(name);
7895 // always make sure the system package code and resource paths dont change
7896 if(dp == null) {
7897 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7898 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7899 }
7900 mDisabledSysPackages.put(name, p);
7901 }
7902 return removePackageLP(name);
7903 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 PackageSetting enableSystemPackageLP(String name) {
7906 PackageSetting p = mDisabledSysPackages.get(name);
7907 if(p == null) {
7908 Log.w(TAG, "Package:"+name+" is not disabled");
7909 return null;
7910 }
7911 // Reset flag in ApplicationInfo object
7912 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7913 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7914 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007915 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007916 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007917 mDisabledSysPackages.remove(name);
7918 return ret;
7919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007920
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007921 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007922 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007923 PackageSetting p = mPackages.get(name);
7924 if (p != null) {
7925 if (p.userId == uid) {
7926 return p;
7927 }
7928 reportSettingsProblem(Log.ERROR,
7929 "Adding duplicate package, keeping first: " + name);
7930 return null;
7931 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007932 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007933 p.userId = uid;
7934 if (addUserIdLP(uid, p, name)) {
7935 mPackages.put(name, p);
7936 return p;
7937 }
7938 return null;
7939 }
7940
7941 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7942 SharedUserSetting s = mSharedUsers.get(name);
7943 if (s != null) {
7944 if (s.userId == uid) {
7945 return s;
7946 }
7947 reportSettingsProblem(Log.ERROR,
7948 "Adding duplicate shared user, keeping first: " + name);
7949 return null;
7950 }
7951 s = new SharedUserSetting(name, pkgFlags);
7952 s.userId = uid;
7953 if (addUserIdLP(uid, s, name)) {
7954 mSharedUsers.put(name, s);
7955 return s;
7956 }
7957 return null;
7958 }
7959
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007960 // Transfer ownership of permissions from one package to another.
7961 private void transferPermissions(String origPkg, String newPkg) {
7962 // Transfer ownership of permissions to the new package.
7963 for (int i=0; i<2; i++) {
7964 HashMap<String, BasePermission> permissions =
7965 i == 0 ? mPermissionTrees : mPermissions;
7966 for (BasePermission bp : permissions.values()) {
7967 if (origPkg.equals(bp.sourcePackage)) {
7968 if (DEBUG_UPGRADE) Log.v(TAG,
7969 "Moving permission " + bp.name
7970 + " from pkg " + bp.sourcePackage
7971 + " to " + newPkg);
7972 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007973 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007974 bp.perm = null;
7975 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007976 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007977 }
7978 bp.uid = 0;
7979 bp.gids = null;
7980 }
7981 }
7982 }
7983 }
7984
7985 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007986 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007987 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007988 PackageSetting p = mPackages.get(name);
7989 if (p != null) {
7990 if (!p.codePath.equals(codePath)) {
7991 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007992 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007993 // This is an updated system app with versions in both system
7994 // and data partition. Just let the most recent version
7995 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007996 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007997 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007998 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007999 // Just a change in the code path is not an issue, but
8000 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008001 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008002 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008003 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008004 }
8005 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008006 reportSettingsProblem(Log.WARN,
8007 "Package " + name + " shared user changed from "
8008 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8009 + " to "
8010 + (sharedUser != null ? sharedUser.name : "<nothing>")
8011 + "; replacing with new");
8012 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008013 } else {
8014 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8015 // If what we are scanning is a system package, then
8016 // make it so, regardless of whether it was previously
8017 // installed only in the data partition.
8018 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008020 }
8021 }
8022 if (p == null) {
8023 // Create a new PackageSettings entry. this can end up here because
8024 // of code path mismatch or user id mismatch of an updated system partition
8025 if (!create) {
8026 return null;
8027 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008028 if (origPackage != null) {
8029 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008030 p = new PackageSetting(origPackage.name, name, codePath,
8031 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008032 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8033 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008034 // Note that we will retain the new package's signature so
8035 // that we can keep its data.
8036 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008037 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008038 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008039 p.sharedUser = origPackage.sharedUser;
8040 p.userId = origPackage.userId;
8041 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008042 mRenamedPackages.put(name, origPackage.name);
8043 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008044 // Update new package state.
8045 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008046 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008047 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008048 p.setTimeStamp(codePath.lastModified());
8049 p.sharedUser = sharedUser;
8050 if (sharedUser != null) {
8051 p.userId = sharedUser.userId;
8052 } else if (MULTIPLE_APPLICATION_UIDS) {
8053 // Clone the setting here for disabled system packages
8054 PackageSetting dis = mDisabledSysPackages.get(name);
8055 if (dis != null) {
8056 // For disabled packages a new setting is created
8057 // from the existing user id. This still has to be
8058 // added to list of user id's
8059 // Copy signatures from previous setting
8060 if (dis.signatures.mSignatures != null) {
8061 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8062 }
8063 p.userId = dis.userId;
8064 // Clone permissions
8065 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
8066 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
8067 // Clone component info
8068 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8069 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8070 // Add new setting to list of user ids
8071 addUserIdLP(p.userId, p, name);
8072 } else {
8073 // Assign new user id
8074 p.userId = newUserIdLP(p);
8075 }
8076 } else {
8077 p.userId = FIRST_APPLICATION_UID;
8078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008079 }
8080 if (p.userId < 0) {
8081 reportSettingsProblem(Log.WARN,
8082 "Package " + name + " could not be assigned a valid uid");
8083 return null;
8084 }
8085 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008086 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008088 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 }
8090 }
8091 return p;
8092 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008093
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008094 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008095 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008096 String codePath = pkg.applicationInfo.sourceDir;
8097 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008098 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008099 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008100 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008101 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008102 p.codePath = new File(codePath);
8103 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008104 }
8105 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008106 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008107 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008108 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008109 p.resourcePath = new File(resourcePath);
8110 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008111 }
8112 // Update version code if needed
8113 if (pkg.mVersionCode != p.versionCode) {
8114 p.versionCode = pkg.mVersionCode;
8115 }
8116 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8117 }
8118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008119 // Utility method that adds a PackageSetting to mPackages and
8120 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008121 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008122 SharedUserSetting sharedUser) {
8123 mPackages.put(name, p);
8124 if (sharedUser != null) {
8125 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8126 reportSettingsProblem(Log.ERROR,
8127 "Package " + p.name + " was user "
8128 + p.sharedUser + " but is now " + sharedUser
8129 + "; I am not changing its files so it will probably fail!");
8130 p.sharedUser.packages.remove(p);
8131 } else if (p.userId != sharedUser.userId) {
8132 reportSettingsProblem(Log.ERROR,
8133 "Package " + p.name + " was user id " + p.userId
8134 + " but is now user " + sharedUser
8135 + " with id " + sharedUser.userId
8136 + "; I am not changing its files so it will probably fail!");
8137 }
8138
8139 sharedUser.packages.add(p);
8140 p.sharedUser = sharedUser;
8141 p.userId = sharedUser.userId;
8142 }
8143 }
8144
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008145 /*
8146 * Update the shared user setting when a package using
8147 * specifying the shared user id is removed. The gids
8148 * associated with each permission of the deleted package
8149 * are removed from the shared user's gid list only if its
8150 * not in use by other permissions of packages in the
8151 * shared user setting.
8152 */
8153 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008154 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008155 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008156 return;
8157 }
8158 // No sharedUserId
8159 if (deletedPs.sharedUser == null) {
8160 return;
8161 }
8162 SharedUserSetting sus = deletedPs.sharedUser;
8163 // Update permissions
8164 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8165 boolean used = false;
8166 if (!sus.grantedPermissions.contains (eachPerm)) {
8167 continue;
8168 }
8169 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008170 if (pkg.pkg != null &&
8171 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
8172 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 used = true;
8174 break;
8175 }
8176 }
8177 if (!used) {
8178 // can safely delete this permission from list
8179 sus.grantedPermissions.remove(eachPerm);
8180 sus.loadedPermissions.remove(eachPerm);
8181 }
8182 }
8183 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008184 int newGids[] = globalGids;
8185 for (String eachPerm : sus.grantedPermissions) {
8186 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008187 if (bp != null) {
8188 newGids = appendInts(newGids, bp.gids);
8189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008190 }
8191 sus.gids = newGids;
8192 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008194 private int removePackageLP(String name) {
8195 PackageSetting p = mPackages.get(name);
8196 if (p != null) {
8197 mPackages.remove(name);
8198 if (p.sharedUser != null) {
8199 p.sharedUser.packages.remove(p);
8200 if (p.sharedUser.packages.size() == 0) {
8201 mSharedUsers.remove(p.sharedUser.name);
8202 removeUserIdLP(p.sharedUser.userId);
8203 return p.sharedUser.userId;
8204 }
8205 } else {
8206 removeUserIdLP(p.userId);
8207 return p.userId;
8208 }
8209 }
8210 return -1;
8211 }
8212
8213 private boolean addUserIdLP(int uid, Object obj, Object name) {
8214 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8215 return false;
8216 }
8217
8218 if (uid >= FIRST_APPLICATION_UID) {
8219 int N = mUserIds.size();
8220 final int index = uid - FIRST_APPLICATION_UID;
8221 while (index >= N) {
8222 mUserIds.add(null);
8223 N++;
8224 }
8225 if (mUserIds.get(index) != null) {
8226 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008227 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008228 + " name=" + name);
8229 return false;
8230 }
8231 mUserIds.set(index, obj);
8232 } else {
8233 if (mOtherUserIds.get(uid) != null) {
8234 reportSettingsProblem(Log.ERROR,
8235 "Adding duplicate shared id: " + uid
8236 + " name=" + name);
8237 return false;
8238 }
8239 mOtherUserIds.put(uid, obj);
8240 }
8241 return true;
8242 }
8243
8244 public Object getUserIdLP(int uid) {
8245 if (uid >= FIRST_APPLICATION_UID) {
8246 int N = mUserIds.size();
8247 final int index = uid - FIRST_APPLICATION_UID;
8248 return index < N ? mUserIds.get(index) : null;
8249 } else {
8250 return mOtherUserIds.get(uid);
8251 }
8252 }
8253
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008254 private Set<String> findPackagesWithFlag(int flag) {
8255 Set<String> ret = new HashSet<String>();
8256 for (PackageSetting ps : mPackages.values()) {
8257 // Has to match atleast all the flag bits set on flag
8258 if ((ps.pkgFlags & flag) == flag) {
8259 ret.add(ps.name);
8260 }
8261 }
8262 return ret;
8263 }
8264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008265 private void removeUserIdLP(int uid) {
8266 if (uid >= FIRST_APPLICATION_UID) {
8267 int N = mUserIds.size();
8268 final int index = uid - FIRST_APPLICATION_UID;
8269 if (index < N) mUserIds.set(index, null);
8270 } else {
8271 mOtherUserIds.remove(uid);
8272 }
8273 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008275 void writeLP() {
8276 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8277
8278 // Keep the old settings around until we know the new ones have
8279 // been successfully written.
8280 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008281 // Presence of backup settings file indicates that we failed
8282 // to persist settings earlier. So preserve the older
8283 // backup for future reference since the current settings
8284 // might have been corrupted.
8285 if (!mBackupSettingsFilename.exists()) {
8286 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008287 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008288 return;
8289 }
8290 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008291 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008292 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008294 }
8295
8296 mPastSignatures.clear();
8297
8298 try {
8299 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8300
8301 //XmlSerializer serializer = XmlUtils.serializerInstance();
8302 XmlSerializer serializer = new FastXmlSerializer();
8303 serializer.setOutput(str, "utf-8");
8304 serializer.startDocument(null, true);
8305 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8306
8307 serializer.startTag(null, "packages");
8308
8309 serializer.startTag(null, "permission-trees");
8310 for (BasePermission bp : mPermissionTrees.values()) {
8311 writePermission(serializer, bp);
8312 }
8313 serializer.endTag(null, "permission-trees");
8314
8315 serializer.startTag(null, "permissions");
8316 for (BasePermission bp : mPermissions.values()) {
8317 writePermission(serializer, bp);
8318 }
8319 serializer.endTag(null, "permissions");
8320
8321 for (PackageSetting pkg : mPackages.values()) {
8322 writePackage(serializer, pkg);
8323 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008325 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8326 writeDisabledSysPackage(serializer, pkg);
8327 }
8328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008329 serializer.startTag(null, "preferred-activities");
8330 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8331 serializer.startTag(null, "item");
8332 pa.writeToXml(serializer);
8333 serializer.endTag(null, "item");
8334 }
8335 serializer.endTag(null, "preferred-activities");
8336
8337 for (SharedUserSetting usr : mSharedUsers.values()) {
8338 serializer.startTag(null, "shared-user");
8339 serializer.attribute(null, "name", usr.name);
8340 serializer.attribute(null, "userId",
8341 Integer.toString(usr.userId));
8342 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8343 serializer.startTag(null, "perms");
8344 for (String name : usr.grantedPermissions) {
8345 serializer.startTag(null, "item");
8346 serializer.attribute(null, "name", name);
8347 serializer.endTag(null, "item");
8348 }
8349 serializer.endTag(null, "perms");
8350 serializer.endTag(null, "shared-user");
8351 }
8352
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008353 if (mPackagesToBeCleaned.size() > 0) {
8354 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8355 serializer.startTag(null, "cleaning-package");
8356 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8357 serializer.endTag(null, "cleaning-package");
8358 }
8359 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008360
8361 if (mRenamedPackages.size() > 0) {
8362 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8363 serializer.startTag(null, "renamed-package");
8364 serializer.attribute(null, "new", e.getKey());
8365 serializer.attribute(null, "old", e.getValue());
8366 serializer.endTag(null, "renamed-package");
8367 }
8368 }
8369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008370 serializer.endTag(null, "packages");
8371
8372 serializer.endDocument();
8373
8374 str.flush();
8375 str.close();
8376
8377 // New settings successfully written, old ones are no longer
8378 // needed.
8379 mBackupSettingsFilename.delete();
8380 FileUtils.setPermissions(mSettingsFilename.toString(),
8381 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8382 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8383 |FileUtils.S_IROTH,
8384 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008385
8386 // Write package list file now, use a JournaledFile.
8387 //
8388 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8389 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8390
8391 str = new FileOutputStream(journal.chooseForWrite());
8392 try {
8393 StringBuilder sb = new StringBuilder();
8394 for (PackageSetting pkg : mPackages.values()) {
8395 ApplicationInfo ai = pkg.pkg.applicationInfo;
8396 String dataPath = ai.dataDir;
8397 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8398
8399 // Avoid any application that has a space in its path
8400 // or that is handled by the system.
8401 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8402 continue;
8403
8404 // we store on each line the following information for now:
8405 //
8406 // pkgName - package name
8407 // userId - application-specific user id
8408 // debugFlag - 0 or 1 if the package is debuggable.
8409 // dataPath - path to package's data path
8410 //
8411 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8412 //
8413 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8414 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8415 // system/core/run-as/run-as.c
8416 //
8417 sb.setLength(0);
8418 sb.append(ai.packageName);
8419 sb.append(" ");
8420 sb.append((int)ai.uid);
8421 sb.append(isDebug ? " 1 " : " 0 ");
8422 sb.append(dataPath);
8423 sb.append("\n");
8424 str.write(sb.toString().getBytes());
8425 }
8426 str.flush();
8427 str.close();
8428 journal.commit();
8429 }
8430 catch (Exception e) {
8431 journal.rollback();
8432 }
8433
8434 FileUtils.setPermissions(mPackageListFilename.toString(),
8435 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8436 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8437 |FileUtils.S_IROTH,
8438 -1, -1);
8439
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008440 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008441
8442 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008443 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 -08008444 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008445 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 -08008446 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008447 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008448 if (mSettingsFilename.exists()) {
8449 if (!mSettingsFilename.delete()) {
8450 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8451 }
8452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008453 //Debug.stopMethodTracing();
8454 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008455
8456 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008457 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458 serializer.startTag(null, "updated-package");
8459 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008460 if (pkg.realName != null) {
8461 serializer.attribute(null, "realName", pkg.realName);
8462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008463 serializer.attribute(null, "codePath", pkg.codePathString);
8464 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008465 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008466 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8467 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8468 }
8469 if (pkg.sharedUser == null) {
8470 serializer.attribute(null, "userId",
8471 Integer.toString(pkg.userId));
8472 } else {
8473 serializer.attribute(null, "sharedUserId",
8474 Integer.toString(pkg.userId));
8475 }
8476 serializer.startTag(null, "perms");
8477 if (pkg.sharedUser == null) {
8478 // If this is a shared user, the permissions will
8479 // be written there. We still need to write an
8480 // empty permissions list so permissionsFixed will
8481 // be set.
8482 for (final String name : pkg.grantedPermissions) {
8483 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008484 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008485 // We only need to write signature or system permissions but this wont
8486 // match the semantics of grantedPermissions. So write all permissions.
8487 serializer.startTag(null, "item");
8488 serializer.attribute(null, "name", name);
8489 serializer.endTag(null, "item");
8490 }
8491 }
8492 }
8493 serializer.endTag(null, "perms");
8494 serializer.endTag(null, "updated-package");
8495 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008496
8497 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008498 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008499 serializer.startTag(null, "package");
8500 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008501 if (pkg.realName != null) {
8502 serializer.attribute(null, "realName", pkg.realName);
8503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008504 serializer.attribute(null, "codePath", pkg.codePathString);
8505 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8506 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8507 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008508 serializer.attribute(null, "flags",
8509 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008510 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008511 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008512 if (pkg.sharedUser == null) {
8513 serializer.attribute(null, "userId",
8514 Integer.toString(pkg.userId));
8515 } else {
8516 serializer.attribute(null, "sharedUserId",
8517 Integer.toString(pkg.userId));
8518 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008519 if (pkg.uidError) {
8520 serializer.attribute(null, "uidError", "true");
8521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008522 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8523 serializer.attribute(null, "enabled",
8524 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8525 ? "true" : "false");
8526 }
8527 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8528 serializer.attribute(null, "installStatus", "false");
8529 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008530 if (pkg.installerPackageName != null) {
8531 serializer.attribute(null, "installer", pkg.installerPackageName);
8532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8534 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8535 serializer.startTag(null, "perms");
8536 if (pkg.sharedUser == null) {
8537 // If this is a shared user, the permissions will
8538 // be written there. We still need to write an
8539 // empty permissions list so permissionsFixed will
8540 // be set.
8541 for (final String name : pkg.grantedPermissions) {
8542 serializer.startTag(null, "item");
8543 serializer.attribute(null, "name", name);
8544 serializer.endTag(null, "item");
8545 }
8546 }
8547 serializer.endTag(null, "perms");
8548 }
8549 if (pkg.disabledComponents.size() > 0) {
8550 serializer.startTag(null, "disabled-components");
8551 for (final String name : pkg.disabledComponents) {
8552 serializer.startTag(null, "item");
8553 serializer.attribute(null, "name", name);
8554 serializer.endTag(null, "item");
8555 }
8556 serializer.endTag(null, "disabled-components");
8557 }
8558 if (pkg.enabledComponents.size() > 0) {
8559 serializer.startTag(null, "enabled-components");
8560 for (final String name : pkg.enabledComponents) {
8561 serializer.startTag(null, "item");
8562 serializer.attribute(null, "name", name);
8563 serializer.endTag(null, "item");
8564 }
8565 serializer.endTag(null, "enabled-components");
8566 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008568 serializer.endTag(null, "package");
8569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008571 void writePermission(XmlSerializer serializer, BasePermission bp)
8572 throws XmlPullParserException, java.io.IOException {
8573 if (bp.type != BasePermission.TYPE_BUILTIN
8574 && bp.sourcePackage != null) {
8575 serializer.startTag(null, "item");
8576 serializer.attribute(null, "name", bp.name);
8577 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008578 if (bp.protectionLevel !=
8579 PermissionInfo.PROTECTION_NORMAL) {
8580 serializer.attribute(null, "protection",
8581 Integer.toString(bp.protectionLevel));
8582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008583 if (DEBUG_SETTINGS) Log.v(TAG,
8584 "Writing perm: name=" + bp.name + " type=" + bp.type);
8585 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8586 PermissionInfo pi = bp.perm != null ? bp.perm.info
8587 : bp.pendingInfo;
8588 if (pi != null) {
8589 serializer.attribute(null, "type", "dynamic");
8590 if (pi.icon != 0) {
8591 serializer.attribute(null, "icon",
8592 Integer.toString(pi.icon));
8593 }
8594 if (pi.nonLocalizedLabel != null) {
8595 serializer.attribute(null, "label",
8596 pi.nonLocalizedLabel.toString());
8597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008598 }
8599 }
8600 serializer.endTag(null, "item");
8601 }
8602 }
8603
8604 String getReadMessagesLP() {
8605 return mReadMessages.toString();
8606 }
8607
Oscar Montemayora8529f62009-11-18 10:14:20 -08008608 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008609 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8610 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008611 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612 while(its.hasNext()) {
8613 String key = its.next();
8614 PackageSetting ps = mPackages.get(key);
8615 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008616 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008617 }
8618 }
8619 return ret;
8620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 boolean readLP() {
8623 FileInputStream str = null;
8624 if (mBackupSettingsFilename.exists()) {
8625 try {
8626 str = new FileInputStream(mBackupSettingsFilename);
8627 mReadMessages.append("Reading from backup settings file\n");
8628 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008629 if (mSettingsFilename.exists()) {
8630 // If both the backup and settings file exist, we
8631 // ignore the settings since it might have been
8632 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008633 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008634 mSettingsFilename.delete();
8635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008636 } catch (java.io.IOException e) {
8637 // We'll try for the normal settings file.
8638 }
8639 }
8640
8641 mPastSignatures.clear();
8642
8643 try {
8644 if (str == null) {
8645 if (!mSettingsFilename.exists()) {
8646 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008647 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008648 return false;
8649 }
8650 str = new FileInputStream(mSettingsFilename);
8651 }
8652 XmlPullParser parser = Xml.newPullParser();
8653 parser.setInput(str, null);
8654
8655 int type;
8656 while ((type=parser.next()) != XmlPullParser.START_TAG
8657 && type != XmlPullParser.END_DOCUMENT) {
8658 ;
8659 }
8660
8661 if (type != XmlPullParser.START_TAG) {
8662 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008663 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664 return false;
8665 }
8666
8667 int outerDepth = parser.getDepth();
8668 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8669 && (type != XmlPullParser.END_TAG
8670 || parser.getDepth() > outerDepth)) {
8671 if (type == XmlPullParser.END_TAG
8672 || type == XmlPullParser.TEXT) {
8673 continue;
8674 }
8675
8676 String tagName = parser.getName();
8677 if (tagName.equals("package")) {
8678 readPackageLP(parser);
8679 } else if (tagName.equals("permissions")) {
8680 readPermissionsLP(mPermissions, parser);
8681 } else if (tagName.equals("permission-trees")) {
8682 readPermissionsLP(mPermissionTrees, parser);
8683 } else if (tagName.equals("shared-user")) {
8684 readSharedUserLP(parser);
8685 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008686 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008687 } else if (tagName.equals("preferred-activities")) {
8688 readPreferredActivitiesLP(parser);
8689 } else if(tagName.equals("updated-package")) {
8690 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008691 } else if (tagName.equals("cleaning-package")) {
8692 String name = parser.getAttributeValue(null, "name");
8693 if (name != null) {
8694 mPackagesToBeCleaned.add(name);
8695 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008696 } else if (tagName.equals("renamed-package")) {
8697 String nname = parser.getAttributeValue(null, "new");
8698 String oname = parser.getAttributeValue(null, "old");
8699 if (nname != null && oname != null) {
8700 mRenamedPackages.put(nname, oname);
8701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008702 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008703 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008704 + parser.getName());
8705 XmlUtils.skipCurrentTag(parser);
8706 }
8707 }
8708
8709 str.close();
8710
8711 } catch(XmlPullParserException e) {
8712 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008713 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714
8715 } catch(java.io.IOException e) {
8716 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008717 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008718
8719 }
8720
8721 int N = mPendingPackages.size();
8722 for (int i=0; i<N; i++) {
8723 final PendingPackage pp = mPendingPackages.get(i);
8724 Object idObj = getUserIdLP(pp.sharedId);
8725 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008726 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008727 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008728 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008729 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008730 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008731 + pp.name);
8732 continue;
8733 }
8734 p.copyFrom(pp);
8735 } else if (idObj != null) {
8736 String msg = "Bad package setting: package " + pp.name
8737 + " has shared uid " + pp.sharedId
8738 + " that is not a shared uid\n";
8739 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008740 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008741 } else {
8742 String msg = "Bad package setting: package " + pp.name
8743 + " has shared uid " + pp.sharedId
8744 + " that is not defined\n";
8745 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008746 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008747 }
8748 }
8749 mPendingPackages.clear();
8750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008751 mReadMessages.append("Read completed successfully: "
8752 + mPackages.size() + " packages, "
8753 + mSharedUsers.size() + " shared uids\n");
8754
8755 return true;
8756 }
8757
8758 private int readInt(XmlPullParser parser, String ns, String name,
8759 int defValue) {
8760 String v = parser.getAttributeValue(ns, name);
8761 try {
8762 if (v == null) {
8763 return defValue;
8764 }
8765 return Integer.parseInt(v);
8766 } catch (NumberFormatException e) {
8767 reportSettingsProblem(Log.WARN,
8768 "Error in package manager settings: attribute " +
8769 name + " has bad integer value " + v + " at "
8770 + parser.getPositionDescription());
8771 }
8772 return defValue;
8773 }
8774
8775 private void readPermissionsLP(HashMap<String, BasePermission> out,
8776 XmlPullParser parser)
8777 throws IOException, XmlPullParserException {
8778 int outerDepth = parser.getDepth();
8779 int type;
8780 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8781 && (type != XmlPullParser.END_TAG
8782 || parser.getDepth() > outerDepth)) {
8783 if (type == XmlPullParser.END_TAG
8784 || type == XmlPullParser.TEXT) {
8785 continue;
8786 }
8787
8788 String tagName = parser.getName();
8789 if (tagName.equals("item")) {
8790 String name = parser.getAttributeValue(null, "name");
8791 String sourcePackage = parser.getAttributeValue(null, "package");
8792 String ptype = parser.getAttributeValue(null, "type");
8793 if (name != null && sourcePackage != null) {
8794 boolean dynamic = "dynamic".equals(ptype);
8795 BasePermission bp = new BasePermission(name, sourcePackage,
8796 dynamic
8797 ? BasePermission.TYPE_DYNAMIC
8798 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008799 bp.protectionLevel = readInt(parser, null, "protection",
8800 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008801 if (dynamic) {
8802 PermissionInfo pi = new PermissionInfo();
8803 pi.packageName = sourcePackage.intern();
8804 pi.name = name.intern();
8805 pi.icon = readInt(parser, null, "icon", 0);
8806 pi.nonLocalizedLabel = parser.getAttributeValue(
8807 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008808 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008809 bp.pendingInfo = pi;
8810 }
8811 out.put(bp.name, bp);
8812 } else {
8813 reportSettingsProblem(Log.WARN,
8814 "Error in package manager settings: permissions has"
8815 + " no name at " + parser.getPositionDescription());
8816 }
8817 } else {
8818 reportSettingsProblem(Log.WARN,
8819 "Unknown element reading permissions: "
8820 + parser.getName() + " at "
8821 + parser.getPositionDescription());
8822 }
8823 XmlUtils.skipCurrentTag(parser);
8824 }
8825 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008827 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008828 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008829 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008830 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008831 String codePathStr = parser.getAttributeValue(null, "codePath");
8832 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008833 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008834 resourcePathStr = codePathStr;
8835 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008836 String version = parser.getAttributeValue(null, "version");
8837 int versionCode = 0;
8838 if (version != null) {
8839 try {
8840 versionCode = Integer.parseInt(version);
8841 } catch (NumberFormatException e) {
8842 }
8843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845 int pkgFlags = 0;
8846 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008847 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008848 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008849 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008850 String timeStampStr = parser.getAttributeValue(null, "ts");
8851 if (timeStampStr != null) {
8852 try {
8853 long timeStamp = Long.parseLong(timeStampStr);
8854 ps.setTimeStamp(timeStamp, timeStampStr);
8855 } catch (NumberFormatException e) {
8856 }
8857 }
8858 String idStr = parser.getAttributeValue(null, "userId");
8859 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8860 if(ps.userId <= 0) {
8861 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8862 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8863 }
8864 int outerDepth = parser.getDepth();
8865 int type;
8866 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8867 && (type != XmlPullParser.END_TAG
8868 || parser.getDepth() > outerDepth)) {
8869 if (type == XmlPullParser.END_TAG
8870 || type == XmlPullParser.TEXT) {
8871 continue;
8872 }
8873
8874 String tagName = parser.getName();
8875 if (tagName.equals("perms")) {
8876 readGrantedPermissionsLP(parser,
8877 ps.grantedPermissions);
8878 } else {
8879 reportSettingsProblem(Log.WARN,
8880 "Unknown element under <updated-package>: "
8881 + parser.getName());
8882 XmlUtils.skipCurrentTag(parser);
8883 }
8884 }
8885 mDisabledSysPackages.put(name, ps);
8886 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008888 private void readPackageLP(XmlPullParser parser)
8889 throws XmlPullParserException, IOException {
8890 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008891 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 String idStr = null;
8893 String sharedIdStr = null;
8894 String codePathStr = null;
8895 String resourcePathStr = null;
8896 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008897 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008898 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008899 int pkgFlags = 0;
8900 String timeStampStr;
8901 long timeStamp = 0;
8902 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008903 String version = null;
8904 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008905 try {
8906 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008907 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008908 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008909 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008910 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8911 codePathStr = parser.getAttributeValue(null, "codePath");
8912 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008913 version = parser.getAttributeValue(null, "version");
8914 if (version != null) {
8915 try {
8916 versionCode = Integer.parseInt(version);
8917 } catch (NumberFormatException e) {
8918 }
8919 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008920 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008921
8922 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008923 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008924 try {
8925 pkgFlags = Integer.parseInt(systemStr);
8926 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927 }
8928 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008929 // For backward compatibility
8930 systemStr = parser.getAttributeValue(null, "system");
8931 if (systemStr != null) {
8932 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8933 } else {
8934 // Old settings that don't specify system... just treat
8935 // them as system, good enough.
8936 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008938 }
8939 timeStampStr = parser.getAttributeValue(null, "ts");
8940 if (timeStampStr != null) {
8941 try {
8942 timeStamp = Long.parseLong(timeStampStr);
8943 } catch (NumberFormatException e) {
8944 }
8945 }
8946 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8947 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8948 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8949 if (resourcePathStr == null) {
8950 resourcePathStr = codePathStr;
8951 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008952 if (realName != null) {
8953 realName = realName.intern();
8954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955 if (name == null) {
8956 reportSettingsProblem(Log.WARN,
8957 "Error in package manager settings: <package> has no name at "
8958 + parser.getPositionDescription());
8959 } else if (codePathStr == null) {
8960 reportSettingsProblem(Log.WARN,
8961 "Error in package manager settings: <package> has no codePath at "
8962 + parser.getPositionDescription());
8963 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008964 packageSetting = addPackageLP(name.intern(), realName,
8965 new File(codePathStr), new File(resourcePathStr),
8966 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008967 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8968 + ": userId=" + userId + " pkg=" + packageSetting);
8969 if (packageSetting == null) {
8970 reportSettingsProblem(Log.ERROR,
8971 "Failure adding uid " + userId
8972 + " while parsing settings at "
8973 + parser.getPositionDescription());
8974 } else {
8975 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8976 }
8977 } else if (sharedIdStr != null) {
8978 userId = sharedIdStr != null
8979 ? Integer.parseInt(sharedIdStr) : 0;
8980 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008981 packageSetting = new PendingPackage(name.intern(), realName,
8982 new File(codePathStr), new File(resourcePathStr),
8983 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008984 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8985 mPendingPackages.add((PendingPackage) packageSetting);
8986 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8987 + ": sharedUserId=" + userId + " pkg="
8988 + packageSetting);
8989 } else {
8990 reportSettingsProblem(Log.WARN,
8991 "Error in package manager settings: package "
8992 + name + " has bad sharedId " + sharedIdStr
8993 + " at " + parser.getPositionDescription());
8994 }
8995 } else {
8996 reportSettingsProblem(Log.WARN,
8997 "Error in package manager settings: package "
8998 + name + " has bad userId " + idStr + " at "
8999 + parser.getPositionDescription());
9000 }
9001 } catch (NumberFormatException e) {
9002 reportSettingsProblem(Log.WARN,
9003 "Error in package manager settings: package "
9004 + name + " has bad userId " + idStr + " at "
9005 + parser.getPositionDescription());
9006 }
9007 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009008 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009009 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009010 final String enabledStr = parser.getAttributeValue(null, "enabled");
9011 if (enabledStr != null) {
9012 if (enabledStr.equalsIgnoreCase("true")) {
9013 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9014 } else if (enabledStr.equalsIgnoreCase("false")) {
9015 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9016 } else if (enabledStr.equalsIgnoreCase("default")) {
9017 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9018 } else {
9019 reportSettingsProblem(Log.WARN,
9020 "Error in package manager settings: package "
9021 + name + " has bad enabled value: " + idStr
9022 + " at " + parser.getPositionDescription());
9023 }
9024 } else {
9025 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9026 }
9027 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9028 if (installStatusStr != null) {
9029 if (installStatusStr.equalsIgnoreCase("false")) {
9030 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9031 } else {
9032 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9033 }
9034 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009036 int outerDepth = parser.getDepth();
9037 int type;
9038 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9039 && (type != XmlPullParser.END_TAG
9040 || parser.getDepth() > outerDepth)) {
9041 if (type == XmlPullParser.END_TAG
9042 || type == XmlPullParser.TEXT) {
9043 continue;
9044 }
9045
9046 String tagName = parser.getName();
9047 if (tagName.equals("disabled-components")) {
9048 readDisabledComponentsLP(packageSetting, parser);
9049 } else if (tagName.equals("enabled-components")) {
9050 readEnabledComponentsLP(packageSetting, parser);
9051 } else if (tagName.equals("sigs")) {
9052 packageSetting.signatures.readXml(parser, mPastSignatures);
9053 } else if (tagName.equals("perms")) {
9054 readGrantedPermissionsLP(parser,
9055 packageSetting.loadedPermissions);
9056 packageSetting.permissionsFixed = true;
9057 } else {
9058 reportSettingsProblem(Log.WARN,
9059 "Unknown element under <package>: "
9060 + parser.getName());
9061 XmlUtils.skipCurrentTag(parser);
9062 }
9063 }
9064 } else {
9065 XmlUtils.skipCurrentTag(parser);
9066 }
9067 }
9068
9069 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9070 XmlPullParser parser)
9071 throws IOException, XmlPullParserException {
9072 int outerDepth = parser.getDepth();
9073 int type;
9074 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9075 && (type != XmlPullParser.END_TAG
9076 || parser.getDepth() > outerDepth)) {
9077 if (type == XmlPullParser.END_TAG
9078 || type == XmlPullParser.TEXT) {
9079 continue;
9080 }
9081
9082 String tagName = parser.getName();
9083 if (tagName.equals("item")) {
9084 String name = parser.getAttributeValue(null, "name");
9085 if (name != null) {
9086 packageSetting.disabledComponents.add(name.intern());
9087 } else {
9088 reportSettingsProblem(Log.WARN,
9089 "Error in package manager settings: <disabled-components> has"
9090 + " no name at " + parser.getPositionDescription());
9091 }
9092 } else {
9093 reportSettingsProblem(Log.WARN,
9094 "Unknown element under <disabled-components>: "
9095 + parser.getName());
9096 }
9097 XmlUtils.skipCurrentTag(parser);
9098 }
9099 }
9100
9101 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9102 XmlPullParser parser)
9103 throws IOException, XmlPullParserException {
9104 int outerDepth = parser.getDepth();
9105 int type;
9106 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9107 && (type != XmlPullParser.END_TAG
9108 || parser.getDepth() > outerDepth)) {
9109 if (type == XmlPullParser.END_TAG
9110 || type == XmlPullParser.TEXT) {
9111 continue;
9112 }
9113
9114 String tagName = parser.getName();
9115 if (tagName.equals("item")) {
9116 String name = parser.getAttributeValue(null, "name");
9117 if (name != null) {
9118 packageSetting.enabledComponents.add(name.intern());
9119 } else {
9120 reportSettingsProblem(Log.WARN,
9121 "Error in package manager settings: <enabled-components> has"
9122 + " no name at " + parser.getPositionDescription());
9123 }
9124 } else {
9125 reportSettingsProblem(Log.WARN,
9126 "Unknown element under <enabled-components>: "
9127 + parser.getName());
9128 }
9129 XmlUtils.skipCurrentTag(parser);
9130 }
9131 }
9132
9133 private void readSharedUserLP(XmlPullParser parser)
9134 throws XmlPullParserException, IOException {
9135 String name = null;
9136 String idStr = null;
9137 int pkgFlags = 0;
9138 SharedUserSetting su = null;
9139 try {
9140 name = parser.getAttributeValue(null, "name");
9141 idStr = parser.getAttributeValue(null, "userId");
9142 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9143 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9144 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9145 }
9146 if (name == null) {
9147 reportSettingsProblem(Log.WARN,
9148 "Error in package manager settings: <shared-user> has no name at "
9149 + parser.getPositionDescription());
9150 } else if (userId == 0) {
9151 reportSettingsProblem(Log.WARN,
9152 "Error in package manager settings: shared-user "
9153 + name + " has bad userId " + idStr + " at "
9154 + parser.getPositionDescription());
9155 } else {
9156 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9157 reportSettingsProblem(Log.ERROR,
9158 "Occurred while parsing settings at "
9159 + parser.getPositionDescription());
9160 }
9161 }
9162 } catch (NumberFormatException e) {
9163 reportSettingsProblem(Log.WARN,
9164 "Error in package manager settings: package "
9165 + name + " has bad userId " + idStr + " at "
9166 + parser.getPositionDescription());
9167 };
9168
9169 if (su != null) {
9170 int outerDepth = parser.getDepth();
9171 int type;
9172 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9173 && (type != XmlPullParser.END_TAG
9174 || parser.getDepth() > outerDepth)) {
9175 if (type == XmlPullParser.END_TAG
9176 || type == XmlPullParser.TEXT) {
9177 continue;
9178 }
9179
9180 String tagName = parser.getName();
9181 if (tagName.equals("sigs")) {
9182 su.signatures.readXml(parser, mPastSignatures);
9183 } else if (tagName.equals("perms")) {
9184 readGrantedPermissionsLP(parser, su.loadedPermissions);
9185 } else {
9186 reportSettingsProblem(Log.WARN,
9187 "Unknown element under <shared-user>: "
9188 + parser.getName());
9189 XmlUtils.skipCurrentTag(parser);
9190 }
9191 }
9192
9193 } else {
9194 XmlUtils.skipCurrentTag(parser);
9195 }
9196 }
9197
9198 private void readGrantedPermissionsLP(XmlPullParser parser,
9199 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9200 int outerDepth = parser.getDepth();
9201 int type;
9202 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9203 && (type != XmlPullParser.END_TAG
9204 || parser.getDepth() > outerDepth)) {
9205 if (type == XmlPullParser.END_TAG
9206 || type == XmlPullParser.TEXT) {
9207 continue;
9208 }
9209
9210 String tagName = parser.getName();
9211 if (tagName.equals("item")) {
9212 String name = parser.getAttributeValue(null, "name");
9213 if (name != null) {
9214 outPerms.add(name.intern());
9215 } else {
9216 reportSettingsProblem(Log.WARN,
9217 "Error in package manager settings: <perms> has"
9218 + " no name at " + parser.getPositionDescription());
9219 }
9220 } else {
9221 reportSettingsProblem(Log.WARN,
9222 "Unknown element under <perms>: "
9223 + parser.getName());
9224 }
9225 XmlUtils.skipCurrentTag(parser);
9226 }
9227 }
9228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009229 private void readPreferredActivitiesLP(XmlPullParser parser)
9230 throws XmlPullParserException, IOException {
9231 int outerDepth = parser.getDepth();
9232 int type;
9233 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9234 && (type != XmlPullParser.END_TAG
9235 || parser.getDepth() > outerDepth)) {
9236 if (type == XmlPullParser.END_TAG
9237 || type == XmlPullParser.TEXT) {
9238 continue;
9239 }
9240
9241 String tagName = parser.getName();
9242 if (tagName.equals("item")) {
9243 PreferredActivity pa = new PreferredActivity(parser);
9244 if (pa.mParseError == null) {
9245 mPreferredActivities.addFilter(pa);
9246 } else {
9247 reportSettingsProblem(Log.WARN,
9248 "Error in package manager settings: <preferred-activity> "
9249 + pa.mParseError + " at "
9250 + parser.getPositionDescription());
9251 }
9252 } else {
9253 reportSettingsProblem(Log.WARN,
9254 "Unknown element under <preferred-activities>: "
9255 + parser.getName());
9256 XmlUtils.skipCurrentTag(parser);
9257 }
9258 }
9259 }
9260
9261 // Returns -1 if we could not find an available UserId to assign
9262 private int newUserIdLP(Object obj) {
9263 // Let's be stupidly inefficient for now...
9264 final int N = mUserIds.size();
9265 for (int i=0; i<N; i++) {
9266 if (mUserIds.get(i) == null) {
9267 mUserIds.set(i, obj);
9268 return FIRST_APPLICATION_UID + i;
9269 }
9270 }
9271
9272 // None left?
9273 if (N >= MAX_APPLICATION_UIDS) {
9274 return -1;
9275 }
9276
9277 mUserIds.add(obj);
9278 return FIRST_APPLICATION_UID + N;
9279 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009281 public PackageSetting getDisabledSystemPkg(String name) {
9282 synchronized(mPackages) {
9283 PackageSetting ps = mDisabledSysPackages.get(name);
9284 return ps;
9285 }
9286 }
9287
9288 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9289 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9290 if (Config.LOGV) {
9291 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9292 + " componentName = " + componentInfo.name);
9293 Log.v(TAG, "enabledComponents: "
9294 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9295 Log.v(TAG, "disabledComponents: "
9296 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9297 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009298 if (packageSettings == null) {
9299 if (false) {
9300 Log.w(TAG, "WAITING FOR DEBUGGER");
9301 Debug.waitForDebugger();
9302 Log.i(TAG, "We will crash!");
9303 }
9304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009305 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9306 || ((componentInfo.enabled
9307 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9308 || (componentInfo.applicationInfo.enabled
9309 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9310 && !packageSettings.disabledComponents.contains(componentInfo.name))
9311 || packageSettings.enabledComponents.contains(componentInfo.name));
9312 }
9313 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009314
9315 // ------- apps on sdcard specific code -------
9316 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009317 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009318 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009319 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009320 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009321
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009322 private String getEncryptKey() {
9323 try {
9324 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9325 if (sdEncKey == null) {
9326 sdEncKey = SystemKeyStore.getInstance().
9327 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9328 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009329 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009330 return null;
9331 }
9332 }
9333 return sdEncKey;
9334 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009335 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009336 return null;
9337 }
9338 }
9339
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009340 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009341 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009342 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009343 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009344 if (list != null) {
9345 int idx = 0;
9346 int idList[] = new int[MAX_CONTAINERS];
9347 boolean neverFound = true;
9348 for (String name : list) {
9349 // Ignore null entries
9350 if (name == null) {
9351 continue;
9352 }
9353 int sidx = name.indexOf(prefix);
9354 if (sidx == -1) {
9355 // Not a temp file. just ignore
9356 continue;
9357 }
9358 String subStr = name.substring(sidx + prefix.length());
9359 idList[idx] = -1;
9360 if (subStr != null) {
9361 try {
9362 int cid = Integer.parseInt(subStr);
9363 idList[idx++] = cid;
9364 neverFound = false;
9365 } catch (NumberFormatException e) {
9366 }
9367 }
9368 }
9369 if (!neverFound) {
9370 // Sort idList
9371 Arrays.sort(idList);
9372 for (int j = 1; j <= idList.length; j++) {
9373 if (idList[j-1] != j) {
9374 tmpIdx = j;
9375 break;
9376 }
9377 }
9378 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009379 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009380 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009381 }
9382
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009383 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009384 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009385 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009386 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9387 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9388 throw new SecurityException("Media status can only be updated by the system");
9389 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009390 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009391 Log.i(TAG, "Updating external media status from " +
9392 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9393 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009394 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9395 mediaStatus+", mMediaMounted=" + mMediaMounted);
9396 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009397 if (reportStatus) {
9398 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9399 }
9400 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009401 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009402 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009403 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009404 // Queue up an async operation since the package installation may take a little while.
9405 mHandler.post(new Runnable() {
9406 public void run() {
9407 mHandler.removeCallbacks(this);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009408 try {
9409 updateExternalMediaStatusInner(mediaStatus);
9410 } finally {
9411 if (reportStatus) {
9412 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9413 }
9414 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009415 }
9416 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009417 }
9418
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009419 private void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009420 // If we are up here that means there are packages to be
9421 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009422 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009423 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009424 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009425 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009426 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009427
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009428 int uidList[] = new int[list.length];
9429 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009430 HashSet<String> removeCids = new HashSet<String>();
9431 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009432 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009433 for (String cid : list) {
9434 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009435 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9436 boolean failed = true;
9437 try {
9438 String pkgName = args.getPackageName();
9439 if (pkgName == null) {
9440 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009441 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009442 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9443 PackageSetting ps = mSettings.mPackages.get(pkgName);
9444 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009445 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009446 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9447 " corresponds to pkg : " + pkgName +
9448 " at code path: " + ps.codePathString);
9449 // We do have a valid package installed on sdcard
9450 processCids.put(args, ps.codePathString);
9451 failed = false;
9452 int uid = ps.userId;
9453 if (uid != -1) {
9454 uidList[num++] = uid;
9455 }
9456 }
9457 } finally {
9458 if (failed) {
9459 // Stale container on sdcard. Just delete
9460 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9461 removeCids.add(cid);
9462 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009463 }
9464 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009465 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009466 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009467 int uidArr[] = null;
9468 if (num > 0) {
9469 // Sort uid list
9470 Arrays.sort(uidList, 0, num);
9471 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009472 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009473 uidArr[0] = uidList[0];
9474 int di = 0;
9475 for (int i = 1; i < num; i++) {
9476 if (uidList[i-1] != uidList[i]) {
9477 uidArr[di++] = uidList[i];
9478 }
9479 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009480 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009481 // Process packages with valid entries.
9482 if (mediaStatus) {
9483 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009484 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009485 startCleaningPackages();
9486 } else {
9487 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009488 unloadMediaPackages(processCids, uidArr);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009489 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009490 }
9491
9492 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9493 ArrayList<String> pkgList, int uidArr[]) {
9494 int size = pkgList.size();
9495 if (size > 0) {
9496 // Send broadcasts here
9497 Bundle extras = new Bundle();
9498 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9499 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009500 if (uidArr != null) {
9501 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9502 }
9503 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9504 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009505 sendPackageBroadcast(action, null, extras);
9506 }
9507 }
9508
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009509 /*
9510 * Look at potentially valid container ids from processCids
9511 * If package information doesn't match the one on record
9512 * or package scanning fails, the cid is added to list of
9513 * removeCids and cleaned up. Since cleaning up containers
9514 * involves destroying them, we do not want any parse
9515 * references to such stale containers. So force gc's
9516 * to avoid unnecessary crashes.
9517 */
9518 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009519 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009520 ArrayList<String> pkgList = new ArrayList<String>();
9521 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009522 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009523 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009524 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009525 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9526 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009527 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009528 try {
9529 // Make sure there are no container errors first.
9530 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9531 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009532 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009533 " when installing from sdcard");
9534 continue;
9535 }
9536 // Check code path here.
9537 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009538 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009539 " does not match one in settings " + codePath);
9540 continue;
9541 }
9542 // Parse package
9543 int parseFlags = PackageParser.PARSE_CHATTY |
9544 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9545 PackageParser pp = new PackageParser(codePath);
9546 pp.setSeparateProcesses(mSeparateProcesses);
9547 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9548 codePath, mMetrics, parseFlags);
9549 pp = null;
9550 doGc = true;
9551 // Check for parse errors
9552 if (pkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009553 Slog.e(TAG, "Parse error when installing install pkg : "
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009554 + args.cid + " from " + args.cachePath);
9555 continue;
9556 }
9557 setApplicationInfoPaths(pkg, codePath, codePath);
9558 synchronized (mInstallLock) {
9559 // Scan the package
9560 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9561 synchronized (mPackages) {
Suchi Amalapurapuebb83ad2010-03-19 11:55:29 -07009562 updatePermissionsLP(pkg.packageName, pkg,
9563 pkg.permissions.size() > 0, false);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009564 retCode = PackageManager.INSTALL_SUCCEEDED;
9565 pkgList.add(pkg.packageName);
9566 // Post process args
9567 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9568 }
9569 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009570 Slog.i(TAG, "Failed to install pkg: " +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009571 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009572 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009573 }
9574
9575 } finally {
9576 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9577 // Don't destroy container here. Wait till gc clears things up.
9578 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009579 }
9580 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009581 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009582 synchronized (mPackages) {
9583 // Persist settings
9584 mSettings.writeLP();
9585 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009586 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009587 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009588 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9589 }
9590 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009591 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009592 }
9593 // Delete any stale containers if needed.
9594 if (removeCids != null) {
9595 for (String cid : removeCids) {
9596 Log.i(TAG, "Destroying stale container : " + cid);
9597 PackageHelper.destroySdDir(cid);
9598 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009599 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009600 }
9601
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009602 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009603 int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009604 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009605 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009606 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009607 Set<SdInstallArgs> keys = processCids.keySet();
9608 for (SdInstallArgs args : keys) {
9609 String cid = args.cid;
9610 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009611 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009612 // Delete package internally
9613 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9614 synchronized (mInstallLock) {
9615 boolean res = deletePackageLI(pkgName, false,
9616 PackageManager.DONT_DELETE_DATA, outInfo);
9617 if (res) {
9618 pkgList.add(pkgName);
9619 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009620 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009621 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009622 }
9623 }
9624 }
9625 // Send broadcasts
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009626 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009627 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009628 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009629 // Force gc
9630 Runtime.getRuntime().gc();
9631 // Just unmount all valid containers.
9632 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009633 synchronized (mInstallLock) {
9634 args.doPostDeleteLI(false);
9635 }
9636 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009637 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009638
9639 public void movePackage(final String packageName,
9640 final IPackageMoveObserver observer, final int flags) {
9641 if (packageName == null) {
9642 return;
9643 }
9644 mContext.enforceCallingOrSelfPermission(
9645 android.Manifest.permission.MOVE_PACKAGE, null);
9646 int returnCode = PackageManager.MOVE_SUCCEEDED;
9647 int currFlags = 0;
9648 int newFlags = 0;
9649 synchronized (mPackages) {
9650 PackageParser.Package pkg = mPackages.get(packageName);
9651 if (pkg == null) {
9652 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9653 }
9654 // Disable moving fwd locked apps and system packages
9655 if (pkg.applicationInfo != null &&
9656 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009657 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009658 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9659 } else if (pkg.applicationInfo != null &&
9660 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009661 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009662 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9663 } else {
9664 // Find install location first
9665 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9666 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009667 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009668 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9669 } else {
9670 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9671 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009672 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009673 PackageManager.INSTALL_EXTERNAL : 0;
9674 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009675 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009676 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9677 }
9678 }
9679 }
9680 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9681 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9682 } else {
9683 Message msg = mHandler.obtainMessage(INIT_COPY);
9684 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9685 pkg.applicationInfo.publicSourceDir);
9686 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9687 packageName);
9688 msg.obj = mp;
9689 mHandler.sendMessage(msg);
9690 }
9691 }
9692 }
9693
9694 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9695 // Queue up an async operation since the package deletion may take a little while.
9696 mHandler.post(new Runnable() {
9697 public void run() {
9698 mHandler.removeCallbacks(this);
9699 int returnCode = currentStatus;
9700 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9701 if (moveSucceeded) {
9702 int uid = -1;
9703 synchronized (mPackages) {
9704 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9705 }
9706 ArrayList<String> pkgList = new ArrayList<String>();
9707 pkgList.add(mp.packageName);
9708 int uidArr[] = new int[] { uid };
9709 // Send resources unavailable broadcast
9710 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9711
9712 // Update package code and resource paths
9713 synchronized (mPackages) {
9714 PackageParser.Package pkg = mPackages.get(mp.packageName);
9715 if (pkg != null) {
9716 String oldCodePath = pkg.mPath;
9717 String newCodePath = mp.targetArgs.getCodePath();
9718 String newResPath = mp.targetArgs.getResourcePath();
9719 pkg.mPath = newCodePath;
9720 // Move dex files around
9721 if (moveDexFiles(pkg)
9722 != PackageManager.INSTALL_SUCCEEDED) {
9723 // Moving of dex files failed. Set
9724 // error code and abort move.
9725 pkg.mPath = pkg.mScanPath;
9726 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9727 moveSucceeded = false;
9728 } else {
9729 pkg.mScanPath = newCodePath;
9730 pkg.applicationInfo.sourceDir = newCodePath;
9731 pkg.applicationInfo.publicSourceDir = newResPath;
9732 PackageSetting ps = (PackageSetting) pkg.mExtras;
9733 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9734 ps.codePathString = ps.codePath.getPath();
9735 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9736 ps.resourcePathString = ps.resourcePath.getPath();
9737 // Set the application info flag correctly.
9738 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009739 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009740 } else {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009741 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009742 }
9743 ps.setFlags(pkg.applicationInfo.flags);
9744 mAppDirs.remove(oldCodePath);
9745 mAppDirs.put(newCodePath, pkg);
9746 // Persist settings
9747 mSettings.writeLP();
9748 }
9749 }
9750 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009751 // Send resources available broadcast
9752 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009753 }
9754 if (!moveSucceeded){
9755 // Clean up failed installation
9756 if (mp.targetArgs != null) {
9757 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009758 returnCode);
9759 }
9760 } else {
9761 // Force a gc to clear things up.
9762 Runtime.getRuntime().gc();
9763 // Delete older code
9764 synchronized (mInstallLock) {
9765 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009766 }
9767 }
9768 IPackageMoveObserver observer = mp.observer;
9769 if (observer != null) {
9770 try {
9771 observer.packageMoved(mp.packageName, returnCode);
9772 } catch (RemoteException e) {
9773 Log.i(TAG, "Observer no longer exists.");
9774 }
9775 }
9776 }
9777 });
9778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009779}