blob: 53415c76022a295370684db708b0381ea492ad88 [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 Amalapurapudaec1722010-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 Amalapurapudaec1722010-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 Hackbornc14b9cc2009-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 Hackbornc14b9cc2009-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 Hackbornc14b9cc2009-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 Hackbornc14b9cc2009-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 Hackbornf657b632010-03-22 18:08:07 -07003980 if (!allowedSig && !gp.grantedPermissions.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;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003992 Log.i(TAG, "Auto-granting " + perm + " 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);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004004 } else if (!ps.haveGids) {
4005 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 }
4007 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004008 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 + " to package " + pkg.packageName
4010 + " because it was previously installed without");
4011 }
4012 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004013 if (gp.grantedPermissions.remove(perm)) {
4014 changedPermission = true;
4015 gp.gids = removeInts(gp.gids, bp.gids);
4016 Slog.i(TAG, "Un-granting permission " + perm
4017 + " from package " + pkg.packageName
4018 + " (protectionLevel=" + bp.protectionLevel
4019 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4020 + ")");
4021 } else {
4022 Slog.w(TAG, "Not granting permission " + perm
4023 + " to package " + pkg.packageName
4024 + " (protectionLevel=" + bp.protectionLevel
4025 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4026 + ")");
4027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 }
4029 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004030 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 + " in package " + pkg.packageName);
4032 }
4033 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004034
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004035 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004036 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4037 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 // This is the first that we have heard about this package, so the
4039 // permissions we have now selected are fixed until explicitly
4040 // changed.
4041 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004042 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004043 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 private final class ActivityIntentResolver
4047 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004048 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004050 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 }
4052
Mihai Preda074edef2009-05-18 17:13:31 +02004053 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004055 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4057 }
4058
Mihai Predaeae850c2009-05-13 10:13:48 +02004059 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4060 ArrayList<PackageParser.Activity> packageActivities) {
4061 if (packageActivities == null) {
4062 return null;
4063 }
4064 mFlags = flags;
4065 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4066 int N = packageActivities.size();
4067 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4068 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004069
4070 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004071 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004072 intentFilters = packageActivities.get(i).intents;
4073 if (intentFilters != null && intentFilters.size() > 0) {
4074 listCut.add(intentFilters);
4075 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004076 }
4077 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4078 }
4079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004081 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 if (SHOW_INFO || Config.LOGV) Log.v(
4083 TAG, " " + type + " " +
4084 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4085 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4086 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004087 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4089 if (SHOW_INFO || Config.LOGV) {
4090 Log.v(TAG, " IntentFilter:");
4091 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4092 }
4093 if (!intent.debugCheck()) {
4094 Log.w(TAG, "==> For Activity " + a.info.name);
4095 }
4096 addFilter(intent);
4097 }
4098 }
4099
4100 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004101 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 if (SHOW_INFO || Config.LOGV) Log.v(
4103 TAG, " " + type + " " +
4104 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4105 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4106 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004107 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4109 if (SHOW_INFO || Config.LOGV) {
4110 Log.v(TAG, " IntentFilter:");
4111 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4112 }
4113 removeFilter(intent);
4114 }
4115 }
4116
4117 @Override
4118 protected boolean allowFilterResult(
4119 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4120 ActivityInfo filterAi = filter.activity.info;
4121 for (int i=dest.size()-1; i>=0; i--) {
4122 ActivityInfo destAi = dest.get(i).activityInfo;
4123 if (destAi.name == filterAi.name
4124 && destAi.packageName == filterAi.packageName) {
4125 return false;
4126 }
4127 }
4128 return true;
4129 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004132 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4133 return info.activity.owner.packageName;
4134 }
4135
4136 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004137 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4138 int match) {
4139 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4140 return null;
4141 }
4142 final PackageParser.Activity activity = info.activity;
4143 if (mSafeMode && (activity.info.applicationInfo.flags
4144 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4145 return null;
4146 }
4147 final ResolveInfo res = new ResolveInfo();
4148 res.activityInfo = PackageParser.generateActivityInfo(activity,
4149 mFlags);
4150 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4151 res.filter = info;
4152 }
4153 res.priority = info.getPriority();
4154 res.preferredOrder = activity.owner.mPreferredOrder;
4155 //System.out.println("Result: " + res.activityInfo.className +
4156 // " = " + res.priority);
4157 res.match = match;
4158 res.isDefault = info.hasDefault;
4159 res.labelRes = info.labelRes;
4160 res.nonLocalizedLabel = info.nonLocalizedLabel;
4161 res.icon = info.icon;
4162 return res;
4163 }
4164
4165 @Override
4166 protected void sortResults(List<ResolveInfo> results) {
4167 Collections.sort(results, mResolvePrioritySorter);
4168 }
4169
4170 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004171 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004173 out.print(prefix); out.print(
4174 Integer.toHexString(System.identityHashCode(filter.activity)));
4175 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004176 out.print(filter.activity.getComponentShortName());
4177 out.print(" filter ");
4178 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004179 }
4180
4181// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4182// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4183// final List<ResolveInfo> retList = Lists.newArrayList();
4184// while (i.hasNext()) {
4185// final ResolveInfo resolveInfo = i.next();
4186// if (isEnabledLP(resolveInfo.activityInfo)) {
4187// retList.add(resolveInfo);
4188// }
4189// }
4190// return retList;
4191// }
4192
4193 // Keys are String (activity class name), values are Activity.
4194 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4195 = new HashMap<ComponentName, PackageParser.Activity>();
4196 private int mFlags;
4197 }
4198
4199 private final class ServiceIntentResolver
4200 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004201 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004203 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 }
4205
Mihai Preda074edef2009-05-18 17:13:31 +02004206 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004208 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4210 }
4211
Dianne Hackbornc14b9cc2009-06-17 18:02:12 -07004212 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4213 ArrayList<PackageParser.Service> packageServices) {
4214 if (packageServices == null) {
4215 return null;
4216 }
4217 mFlags = flags;
4218 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4219 int N = packageServices.size();
4220 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4221 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4222
4223 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4224 for (int i = 0; i < N; ++i) {
4225 intentFilters = packageServices.get(i).intents;
4226 if (intentFilters != null && intentFilters.size() > 0) {
4227 listCut.add(intentFilters);
4228 }
4229 }
4230 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4231 }
4232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004234 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 if (SHOW_INFO || Config.LOGV) Log.v(
4236 TAG, " " + (s.info.nonLocalizedLabel != null
4237 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4238 if (SHOW_INFO || Config.LOGV) Log.v(
4239 TAG, " Class=" + s.info.name);
4240 int NI = s.intents.size();
4241 int j;
4242 for (j=0; j<NI; j++) {
4243 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4244 if (SHOW_INFO || Config.LOGV) {
4245 Log.v(TAG, " IntentFilter:");
4246 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4247 }
4248 if (!intent.debugCheck()) {
4249 Log.w(TAG, "==> For Service " + s.info.name);
4250 }
4251 addFilter(intent);
4252 }
4253 }
4254
4255 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004256 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004257 if (SHOW_INFO || Config.LOGV) Log.v(
4258 TAG, " " + (s.info.nonLocalizedLabel != null
4259 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4260 if (SHOW_INFO || Config.LOGV) Log.v(
4261 TAG, " Class=" + s.info.name);
4262 int NI = s.intents.size();
4263 int j;
4264 for (j=0; j<NI; j++) {
4265 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4266 if (SHOW_INFO || Config.LOGV) {
4267 Log.v(TAG, " IntentFilter:");
4268 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4269 }
4270 removeFilter(intent);
4271 }
4272 }
4273
4274 @Override
4275 protected boolean allowFilterResult(
4276 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4277 ServiceInfo filterSi = filter.service.info;
4278 for (int i=dest.size()-1; i>=0; i--) {
4279 ServiceInfo destAi = dest.get(i).serviceInfo;
4280 if (destAi.name == filterSi.name
4281 && destAi.packageName == filterSi.packageName) {
4282 return false;
4283 }
4284 }
4285 return true;
4286 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004289 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4290 return info.service.owner.packageName;
4291 }
4292
4293 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4295 int match) {
4296 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4297 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4298 return null;
4299 }
4300 final PackageParser.Service service = info.service;
4301 if (mSafeMode && (service.info.applicationInfo.flags
4302 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4303 return null;
4304 }
4305 final ResolveInfo res = new ResolveInfo();
4306 res.serviceInfo = PackageParser.generateServiceInfo(service,
4307 mFlags);
4308 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4309 res.filter = filter;
4310 }
4311 res.priority = info.getPriority();
4312 res.preferredOrder = service.owner.mPreferredOrder;
4313 //System.out.println("Result: " + res.activityInfo.className +
4314 // " = " + res.priority);
4315 res.match = match;
4316 res.isDefault = info.hasDefault;
4317 res.labelRes = info.labelRes;
4318 res.nonLocalizedLabel = info.nonLocalizedLabel;
4319 res.icon = info.icon;
4320 return res;
4321 }
4322
4323 @Override
4324 protected void sortResults(List<ResolveInfo> results) {
4325 Collections.sort(results, mResolvePrioritySorter);
4326 }
4327
4328 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004329 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004331 out.print(prefix); out.print(
4332 Integer.toHexString(System.identityHashCode(filter.service)));
4333 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004334 out.print(filter.service.getComponentShortName());
4335 out.print(" filter ");
4336 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337 }
4338
4339// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4340// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4341// final List<ResolveInfo> retList = Lists.newArrayList();
4342// while (i.hasNext()) {
4343// final ResolveInfo resolveInfo = (ResolveInfo) i;
4344// if (isEnabledLP(resolveInfo.serviceInfo)) {
4345// retList.add(resolveInfo);
4346// }
4347// }
4348// return retList;
4349// }
4350
4351 // Keys are String (activity class name), values are Activity.
4352 private final HashMap<ComponentName, PackageParser.Service> mServices
4353 = new HashMap<ComponentName, PackageParser.Service>();
4354 private int mFlags;
4355 };
4356
4357 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4358 new Comparator<ResolveInfo>() {
4359 public int compare(ResolveInfo r1, ResolveInfo r2) {
4360 int v1 = r1.priority;
4361 int v2 = r2.priority;
4362 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4363 if (v1 != v2) {
4364 return (v1 > v2) ? -1 : 1;
4365 }
4366 v1 = r1.preferredOrder;
4367 v2 = r2.preferredOrder;
4368 if (v1 != v2) {
4369 return (v1 > v2) ? -1 : 1;
4370 }
4371 if (r1.isDefault != r2.isDefault) {
4372 return r1.isDefault ? -1 : 1;
4373 }
4374 v1 = r1.match;
4375 v2 = r2.match;
4376 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4377 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4378 }
4379 };
4380
4381 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4382 new Comparator<ProviderInfo>() {
4383 public int compare(ProviderInfo p1, ProviderInfo p2) {
4384 final int v1 = p1.initOrder;
4385 final int v2 = p2.initOrder;
4386 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4387 }
4388 };
4389
4390 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4391 IActivityManager am = ActivityManagerNative.getDefault();
4392 if (am != null) {
4393 try {
4394 final Intent intent = new Intent(action,
4395 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4396 if (extras != null) {
4397 intent.putExtras(extras);
4398 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004399 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 am.broadcastIntent(
4401 null, intent,
4402 null, null, 0, null, null, null, false, false);
4403 } catch (RemoteException ex) {
4404 }
4405 }
4406 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004407
4408 public String nextPackageToClean(String lastPackage) {
4409 synchronized (mPackages) {
4410 if (!mMediaMounted) {
4411 // If the external storage is no longer mounted at this point,
4412 // the caller may not have been able to delete all of this
4413 // packages files and can not delete any more. Bail.
4414 return null;
4415 }
4416 if (lastPackage != null) {
4417 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4418 }
4419 return mSettings.mPackagesToBeCleaned.size() > 0
4420 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4421 }
4422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004423
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004424 void schedulePackageCleaning(String packageName) {
4425 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4426 }
4427
4428 void startCleaningPackages() {
4429 synchronized (mPackages) {
4430 if (!mMediaMounted) {
4431 return;
4432 }
4433 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4434 return;
4435 }
4436 }
4437 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4438 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4439 IActivityManager am = ActivityManagerNative.getDefault();
4440 if (am != null) {
4441 try {
4442 am.startService(null, intent, null);
4443 } catch (RemoteException e) {
4444 }
4445 }
4446 }
4447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004448 private final class AppDirObserver extends FileObserver {
4449 public AppDirObserver(String path, int mask, boolean isrom) {
4450 super(path, mask);
4451 mRootDir = path;
4452 mIsRom = isrom;
4453 }
4454
4455 public void onEvent(int event, String path) {
4456 String removedPackage = null;
4457 int removedUid = -1;
4458 String addedPackage = null;
4459 int addedUid = -1;
4460
4461 synchronized (mInstallLock) {
4462 String fullPathStr = null;
4463 File fullPath = null;
4464 if (path != null) {
4465 fullPath = new File(mRootDir, path);
4466 fullPathStr = fullPath.getPath();
4467 }
4468
4469 if (Config.LOGV) Log.v(
4470 TAG, "File " + fullPathStr + " changed: "
4471 + Integer.toHexString(event));
4472
4473 if (!isPackageFilename(path)) {
4474 if (Config.LOGV) Log.v(
4475 TAG, "Ignoring change of non-package file: " + fullPathStr);
4476 return;
4477 }
4478
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004479 // Ignore packages that are being installed or
4480 // have just been installed.
4481 if (ignoreCodePath(fullPathStr)) {
4482 return;
4483 }
4484 PackageParser.Package p = null;
4485 synchronized (mPackages) {
4486 p = mAppDirs.get(fullPathStr);
4487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004489 if (p != null) {
4490 removePackageLI(p, true);
4491 removedPackage = p.applicationInfo.packageName;
4492 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 }
4494 }
4495
4496 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004498 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004499 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4500 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 PackageParser.PARSE_CHATTY |
4502 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004503 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 if (p != null) {
4505 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004506 updatePermissionsLP(p.packageName, p,
4507 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004508 }
4509 addedPackage = p.applicationInfo.packageName;
4510 addedUid = p.applicationInfo.uid;
4511 }
4512 }
4513 }
4514
4515 synchronized (mPackages) {
4516 mSettings.writeLP();
4517 }
4518 }
4519
4520 if (removedPackage != null) {
4521 Bundle extras = new Bundle(1);
4522 extras.putInt(Intent.EXTRA_UID, removedUid);
4523 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4524 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4525 }
4526 if (addedPackage != null) {
4527 Bundle extras = new Bundle(1);
4528 extras.putInt(Intent.EXTRA_UID, addedUid);
4529 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4530 }
4531 }
4532
4533 private final String mRootDir;
4534 private final boolean mIsRom;
4535 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 /* Called when a downloaded package installation has been confirmed by the user */
4538 public void installPackage(
4539 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004540 installPackage(packageURI, observer, flags, null);
4541 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004542
Jacek Surazski65e13172009-04-28 15:26:38 +02004543 /* Called when a downloaded package installation has been confirmed by the user */
4544 public void installPackage(
4545 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4546 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004547 mContext.enforceCallingOrSelfPermission(
4548 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004549
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004550 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004551 msg.obj = new InstallParams(packageURI, observer, flags,
4552 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004553 mHandler.sendMessage(msg);
4554 }
4555
Christopher Tate1bb69062010-02-19 17:02:12 -08004556 public void finishPackageInstall(int token) {
4557 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4558 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4559 mHandler.sendMessage(msg);
4560 }
4561
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004562 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004563 // Queue up an async operation since the package installation may take a little while.
4564 mHandler.post(new Runnable() {
4565 public void run() {
4566 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004567 // Result object to be returned
4568 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004569 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004570 res.uid = -1;
4571 res.pkg = null;
4572 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004573 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004574 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004575 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004576 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004577 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004578 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004579 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004580
4581 // A restore should be performed at this point if (a) the install
4582 // succeeded, (b) the operation is not an update, and (c) the new
4583 // package has a backupAgent defined.
4584 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004585 boolean doRestore = (!update
4586 && res.pkg != null
4587 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004588
4589 // Set up the post-install work request bookkeeping. This will be used
4590 // and cleaned up by the post-install event handling regardless of whether
4591 // there's a restore pass performed. Token values are >= 1.
4592 int token;
4593 if (mNextInstallToken < 0) mNextInstallToken = 1;
4594 token = mNextInstallToken++;
4595
4596 PostInstallData data = new PostInstallData(args, res);
4597 mRunningInstalls.put(token, data);
4598 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4599
4600 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4601 // Pass responsibility to the Backup Manager. It will perform a
4602 // restore if appropriate, then pass responsibility back to the
4603 // Package Manager to run the post-install observer callbacks
4604 // and broadcasts.
4605 IBackupManager bm = IBackupManager.Stub.asInterface(
4606 ServiceManager.getService(Context.BACKUP_SERVICE));
4607 if (bm != null) {
4608 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4609 + " to BM for possible restore");
4610 try {
4611 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4612 } catch (RemoteException e) {
4613 // can't happen; the backup manager is local
4614 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004615 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004616 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004617 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004618 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004619 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004620 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004623
4624 if (!doRestore) {
4625 // No restore possible, or the Backup Manager was mysteriously not
4626 // available -- just fire the post-install work request directly.
4627 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4628 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4629 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004631 }
4632 });
4633 }
4634
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004635 abstract class HandlerParams {
4636 final static int MAX_RETRIES = 4;
4637 int retry = 0;
4638 final void startCopy() {
4639 try {
4640 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4641 retry++;
4642 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004643 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004644 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4645 handleServiceError();
4646 return;
4647 } else {
4648 handleStartCopy();
4649 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4650 mHandler.sendEmptyMessage(MCS_UNBIND);
4651 }
4652 } catch (RemoteException e) {
4653 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4654 mHandler.sendEmptyMessage(MCS_RECONNECT);
4655 }
4656 handleReturnCode();
4657 }
4658
4659 final void serviceError() {
4660 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4661 handleServiceError();
4662 handleReturnCode();
4663 }
4664 abstract void handleStartCopy() throws RemoteException;
4665 abstract void handleServiceError();
4666 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004667 }
4668
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004669 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004670 final IPackageInstallObserver observer;
4671 int flags;
4672 final Uri packageURI;
4673 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004674 private InstallArgs mArgs;
4675 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004676 InstallParams(Uri packageURI,
4677 IPackageInstallObserver observer, int flags,
4678 String installerPackageName) {
4679 this.packageURI = packageURI;
4680 this.flags = flags;
4681 this.observer = observer;
4682 this.installerPackageName = installerPackageName;
4683 }
4684
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004685 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4686 String packageName = pkgLite.packageName;
4687 int installLocation = pkgLite.installLocation;
4688 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4689 synchronized (mPackages) {
4690 PackageParser.Package pkg = mPackages.get(packageName);
4691 if (pkg != null) {
4692 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4693 // Check for updated system application.
4694 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4695 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004696 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004697 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4698 }
4699 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4700 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004701 if (onSd) {
4702 // Install flag overrides everything.
4703 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4704 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004705 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004706 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4707 // Application explicitly specified internal.
4708 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4709 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4710 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004711 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004712 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004713 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4714 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4715 }
4716 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004717 }
4718 }
4719 } else {
4720 // Invalid install. Return error code
4721 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4722 }
4723 }
4724 }
4725 // All the special cases have been taken care of.
4726 // Return result based on recommended install location.
4727 if (onSd) {
4728 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4729 }
4730 return pkgLite.recommendedInstallLocation;
4731 }
4732
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004733 /*
4734 * Invoke remote method to get package information and install
4735 * location values. Override install location based on default
4736 * policy if needed and then create install arguments based
4737 * on the install location.
4738 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004739 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004740 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004741 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4742 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004743 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4744 if (onInt && onSd) {
4745 // Check if both bits are set.
4746 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4747 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4748 } else if (fwdLocked && onSd) {
4749 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004750 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004751 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004752 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004753 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004754 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004755 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004756 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4757 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4758 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4759 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4760 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004761 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4762 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4763 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004764 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4765 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004766 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004767 // Override with defaults if needed.
4768 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004769 if (!onSd && !onInt) {
4770 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004771 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4772 // Set the flag to install on external media.
4773 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004774 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004775 } else {
4776 // Make sure the flag for installing on external
4777 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004778 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004779 flags &= ~PackageManager.INSTALL_EXTERNAL;
4780 }
4781 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004782 }
4783 }
4784 // Create the file args now.
4785 mArgs = createInstallArgs(this);
4786 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4787 // Create copy only if we are not in an erroneous state.
4788 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004789 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004790 }
4791 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004792 }
4793
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004794 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004795 void handleReturnCode() {
4796 processPendingInstall(mArgs, mRet);
4797 }
4798
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004799 @Override
4800 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004801 mArgs = createInstallArgs(this);
4802 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004803 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004804 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004805
4806 /*
4807 * Utility class used in movePackage api.
4808 * srcArgs and targetArgs are not set for invalid flags and make
4809 * sure to do null checks when invoking methods on them.
4810 * We probably want to return ErrorPrams for both failed installs
4811 * and moves.
4812 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004813 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004814 final IPackageMoveObserver observer;
4815 final int flags;
4816 final String packageName;
4817 final InstallArgs srcArgs;
4818 final InstallArgs targetArgs;
4819 int mRet;
4820 MoveParams(InstallArgs srcArgs,
4821 IPackageMoveObserver observer,
4822 int flags, String packageName) {
4823 this.srcArgs = srcArgs;
4824 this.observer = observer;
4825 this.flags = flags;
4826 this.packageName = packageName;
4827 if (srcArgs != null) {
4828 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4829 targetArgs = createInstallArgs(packageUri, flags, packageName);
4830 } else {
4831 targetArgs = null;
4832 }
4833 }
4834
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004835 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004836 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4837 // Check for storage space on target medium
4838 if (!targetArgs.checkFreeStorage(mContainerService)) {
4839 Log.w(TAG, "Insufficient storage to install");
4840 return;
4841 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004842 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004843 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004844 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004845 if (DEBUG_SD_INSTALL) {
4846 StringBuilder builder = new StringBuilder();
4847 if (srcArgs != null) {
4848 builder.append("src: ");
4849 builder.append(srcArgs.getCodePath());
4850 }
4851 if (targetArgs != null) {
4852 builder.append(" target : ");
4853 builder.append(targetArgs.getCodePath());
4854 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004855 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004856 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004857 }
4858
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004859 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004860 void handleReturnCode() {
4861 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004862 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4863 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4864 currentStatus = PackageManager.MOVE_SUCCEEDED;
4865 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4866 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4867 }
4868 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004869 }
4870
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004871 @Override
4872 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004873 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004874 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004875 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004876
4877 private InstallArgs createInstallArgs(InstallParams params) {
4878 if (installOnSd(params.flags)) {
4879 return new SdInstallArgs(params);
4880 } else {
4881 return new FileInstallArgs(params);
4882 }
4883 }
4884
4885 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4886 if (installOnSd(flags)) {
4887 return new SdInstallArgs(fullCodePath, fullResourcePath);
4888 } else {
4889 return new FileInstallArgs(fullCodePath, fullResourcePath);
4890 }
4891 }
4892
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004893 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4894 if (installOnSd(flags)) {
4895 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4896 return new SdInstallArgs(packageURI, cid);
4897 } else {
4898 return new FileInstallArgs(packageURI, pkgName);
4899 }
4900 }
4901
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004902 static abstract class InstallArgs {
4903 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004904 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004905 final int flags;
4906 final Uri packageURI;
4907 final String installerPackageName;
4908
4909 InstallArgs(Uri packageURI,
4910 IPackageInstallObserver observer, int flags,
4911 String installerPackageName) {
4912 this.packageURI = packageURI;
4913 this.flags = flags;
4914 this.observer = observer;
4915 this.installerPackageName = installerPackageName;
4916 }
4917
4918 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004919 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004920 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004921 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004922 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004923 abstract String getCodePath();
4924 abstract String getResourcePath();
4925 // Need installer lock especially for dex file removal.
4926 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004927 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004928 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004929 }
4930
4931 class FileInstallArgs extends InstallArgs {
4932 File installDir;
4933 String codeFileName;
4934 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004935 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004936
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004937 FileInstallArgs(InstallParams params) {
4938 super(params.packageURI, params.observer,
4939 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004940 }
4941
4942 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4943 super(null, null, 0, null);
4944 File codeFile = new File(fullCodePath);
4945 installDir = codeFile.getParentFile();
4946 codeFileName = fullCodePath;
4947 resourceFileName = fullResourcePath;
4948 }
4949
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004950 FileInstallArgs(Uri packageURI, String pkgName) {
4951 super(packageURI, null, 0, null);
4952 boolean fwdLocked = isFwdLocked(flags);
4953 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4954 String apkName = getNextCodePath(null, pkgName, ".apk");
4955 codeFileName = new File(installDir, apkName + ".apk").getPath();
4956 resourceFileName = getResourcePathFromCodePath();
4957 }
4958
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004959 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4960 return imcs.checkFreeStorage(false, packageURI);
4961 }
4962
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004963 String getCodePath() {
4964 return codeFileName;
4965 }
4966
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004967 void createCopyFile() {
4968 boolean fwdLocked = isFwdLocked(flags);
4969 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4970 codeFileName = createTempPackageFile(installDir).getPath();
4971 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004972 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004973 }
4974
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004975 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004976 if (temp) {
4977 // Generate temp file name
4978 createCopyFile();
4979 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004980 // Get a ParcelFileDescriptor to write to the output file
4981 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004982 if (!created) {
4983 try {
4984 codeFile.createNewFile();
4985 // Set permissions
4986 if (!setPermissions()) {
4987 // Failed setting permissions.
4988 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4989 }
4990 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004991 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004992 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4993 }
4994 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004995 ParcelFileDescriptor out = null;
4996 try {
4997 out = ParcelFileDescriptor.open(codeFile,
4998 ParcelFileDescriptor.MODE_READ_WRITE);
4999 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005000 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005001 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5002 }
5003 // Copy the resource now
5004 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5005 try {
5006 if (imcs.copyResource(packageURI, out)) {
5007 ret = PackageManager.INSTALL_SUCCEEDED;
5008 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005009 } finally {
5010 try { if (out != null) out.close(); } catch (IOException e) {}
5011 }
5012 return ret;
5013 }
5014
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005015 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005016 if (status != PackageManager.INSTALL_SUCCEEDED) {
5017 cleanUp();
5018 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005019 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005020 }
5021
5022 boolean doRename(int status, final String pkgName, String oldCodePath) {
5023 if (status != PackageManager.INSTALL_SUCCEEDED) {
5024 cleanUp();
5025 return false;
5026 } else {
5027 // Rename based on packageName
5028 File codeFile = new File(getCodePath());
5029 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5030 File desFile = new File(installDir, apkName + ".apk");
5031 if (!codeFile.renameTo(desFile)) {
5032 return false;
5033 }
5034 // Reset paths since the file has been renamed.
5035 codeFileName = desFile.getPath();
5036 resourceFileName = getResourcePathFromCodePath();
5037 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005038 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005039 // Failed setting permissions.
5040 return false;
5041 }
5042 return true;
5043 }
5044 }
5045
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005046 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005047 if (status != PackageManager.INSTALL_SUCCEEDED) {
5048 cleanUp();
5049 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005050 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005051 }
5052
5053 String getResourcePath() {
5054 return resourceFileName;
5055 }
5056
5057 String getResourcePathFromCodePath() {
5058 String codePath = getCodePath();
5059 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5060 String apkNameOnly = getApkName(codePath);
5061 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5062 } else {
5063 return codePath;
5064 }
5065 }
5066
5067 private boolean cleanUp() {
5068 boolean ret = true;
5069 String sourceDir = getCodePath();
5070 String publicSourceDir = getResourcePath();
5071 if (sourceDir != null) {
5072 File sourceFile = new File(sourceDir);
5073 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005074 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005075 ret = false;
5076 }
5077 // Delete application's code and resources
5078 sourceFile.delete();
5079 }
5080 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5081 final File publicSourceFile = new File(publicSourceDir);
5082 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005083 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005084 }
5085 if (publicSourceFile.exists()) {
5086 publicSourceFile.delete();
5087 }
5088 }
5089 return ret;
5090 }
5091
5092 void cleanUpResourcesLI() {
5093 String sourceDir = getCodePath();
5094 if (cleanUp() && mInstaller != null) {
5095 int retCode = mInstaller.rmdex(sourceDir);
5096 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005097 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005098 + " at location "
5099 + sourceDir + ", retcode=" + retCode);
5100 // we don't consider this to be a failure of the core package deletion
5101 }
5102 }
5103 }
5104
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005105 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005106 // TODO Do this in a more elegant way later on. for now just a hack
5107 if (!isFwdLocked(flags)) {
5108 final int filePermissions =
5109 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5110 |FileUtils.S_IROTH;
5111 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5112 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005113 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005114 getCodePath()
5115 + ". The return code was: " + retCode);
5116 // TODO Define new internal error
5117 return false;
5118 }
5119 return true;
5120 }
5121 return true;
5122 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005123
5124 boolean doPostDeleteLI(boolean delete) {
5125 cleanUpResourcesLI();
5126 return true;
5127 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005128 }
5129
5130 class SdInstallArgs extends InstallArgs {
5131 String cid;
5132 String cachePath;
5133 static final String RES_FILE_NAME = "pkg.apk";
5134
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005135 SdInstallArgs(InstallParams params) {
5136 super(params.packageURI, params.observer,
5137 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005138 }
5139
5140 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005141 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005142 // Extract cid from fullCodePath
5143 int eidx = fullCodePath.lastIndexOf("/");
5144 String subStr1 = fullCodePath.substring(0, eidx);
5145 int sidx = subStr1.lastIndexOf("/");
5146 cid = subStr1.substring(sidx+1, eidx);
5147 cachePath = subStr1;
5148 }
5149
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005150 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005151 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5152 this.cid = cid;
5153 }
5154
5155 SdInstallArgs(Uri packageURI, String cid) {
5156 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005157 this.cid = cid;
5158 }
5159
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005160 void createCopyFile() {
5161 cid = getTempContainerId();
5162 }
5163
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005164 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5165 return imcs.checkFreeStorage(true, packageURI);
5166 }
5167
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005168 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005169 if (temp) {
5170 createCopyFile();
5171 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005172 cachePath = imcs.copyResourceToContainer(
5173 packageURI, cid,
5174 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005175 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5176 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005177 }
5178
5179 @Override
5180 String getCodePath() {
5181 return cachePath + "/" + RES_FILE_NAME;
5182 }
5183
5184 @Override
5185 String getResourcePath() {
5186 return cachePath + "/" + RES_FILE_NAME;
5187 }
5188
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005189 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005190 if (status != PackageManager.INSTALL_SUCCEEDED) {
5191 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005192 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005193 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005194 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005195 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005196 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005197 if (cachePath == null) {
5198 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5199 }
5200 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005201 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005202 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005203 }
5204
5205 boolean doRename(int status, final String pkgName,
5206 String oldCodePath) {
5207 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005208 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005209 if (PackageHelper.isContainerMounted(cid)) {
5210 // Unmount the container
5211 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005212 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005213 return false;
5214 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005215 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005216 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005217 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005218 return false;
5219 }
5220 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005221 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005222 newCachePath = PackageHelper.mountSdDir(newCacheId,
5223 getEncryptKey(), Process.SYSTEM_UID);
5224 } else {
5225 newCachePath = PackageHelper.getSdDir(newCacheId);
5226 }
5227 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005228 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005229 return false;
5230 }
5231 Log.i(TAG, "Succesfully renamed " + cid +
5232 " at path: " + cachePath + " to " + newCacheId +
5233 " at new path: " + newCachePath);
5234 cid = newCacheId;
5235 cachePath = newCachePath;
5236 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005237 }
5238
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005239 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005240 if (status != PackageManager.INSTALL_SUCCEEDED) {
5241 cleanUp();
5242 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005243 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005244 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005245 PackageHelper.mountSdDir(cid,
5246 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005247 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005248 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005249 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005250 }
5251
5252 private void cleanUp() {
5253 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005254 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005255 }
5256
5257 void cleanUpResourcesLI() {
5258 String sourceFile = getCodePath();
5259 // Remove dex file
5260 if (mInstaller != null) {
5261 int retCode = mInstaller.rmdex(sourceFile.toString());
5262 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005263 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005264 + " at location "
5265 + sourceFile.toString() + ", retcode=" + retCode);
5266 // we don't consider this to be a failure of the core package deletion
5267 }
5268 }
5269 cleanUp();
5270 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005271
5272 boolean matchContainer(String app) {
5273 if (cid.startsWith(app)) {
5274 return true;
5275 }
5276 return false;
5277 }
5278
5279 String getPackageName() {
5280 int idx = cid.lastIndexOf("-");
5281 if (idx == -1) {
5282 return cid;
5283 }
5284 return cid.substring(0, idx);
5285 }
5286
5287 boolean doPostDeleteLI(boolean delete) {
5288 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005289 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005290 if (mounted) {
5291 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005292 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005293 }
5294 if (ret && delete) {
5295 cleanUpResourcesLI();
5296 }
5297 return ret;
5298 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005299 };
5300
5301 // Utility method used to create code paths based on package name and available index.
5302 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5303 String idxStr = "";
5304 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005305 // Fall back to default value of idx=1 if prefix is not
5306 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005307 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005308 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005309 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005310 if (subStr.endsWith(suffix)) {
5311 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005312 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005313 // If oldCodePath already contains prefix find out the
5314 // ending index to either increment or decrement.
5315 int sidx = subStr.lastIndexOf(prefix);
5316 if (sidx != -1) {
5317 subStr = subStr.substring(sidx + prefix.length());
5318 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005319 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5320 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005321 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005322 try {
5323 idx = Integer.parseInt(subStr);
5324 if (idx <= 1) {
5325 idx++;
5326 } else {
5327 idx--;
5328 }
5329 } catch(NumberFormatException e) {
5330 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005331 }
5332 }
5333 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005334 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005335 return prefix + idxStr;
5336 }
5337
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005338 // Utility method used to ignore ADD/REMOVE events
5339 // by directory observer.
5340 private static boolean ignoreCodePath(String fullPathStr) {
5341 String apkName = getApkName(fullPathStr);
5342 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5343 if (idx != -1 && ((idx+1) < apkName.length())) {
5344 // Make sure the package ends with a numeral
5345 String version = apkName.substring(idx+1);
5346 try {
5347 Integer.parseInt(version);
5348 return true;
5349 } catch (NumberFormatException e) {}
5350 }
5351 return false;
5352 }
5353
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005354 // Utility method that returns the relative package path with respect
5355 // to the installation directory. Like say for /data/data/com.test-1.apk
5356 // string com.test-1 is returned.
5357 static String getApkName(String codePath) {
5358 if (codePath == null) {
5359 return null;
5360 }
5361 int sidx = codePath.lastIndexOf("/");
5362 int eidx = codePath.lastIndexOf(".");
5363 if (eidx == -1) {
5364 eidx = codePath.length();
5365 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005366 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005367 return null;
5368 }
5369 return codePath.substring(sidx+1, eidx);
5370 }
5371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 class PackageInstalledInfo {
5373 String name;
5374 int uid;
5375 PackageParser.Package pkg;
5376 int returnCode;
5377 PackageRemovedInfo removedInfo;
5378 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380 /*
5381 * Install a non-existing package.
5382 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005383 private void installNewPackageLI(PackageParser.Package pkg,
5384 int parseFlags,
5385 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005386 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005388 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005389
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005390 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005391 res.name = pkgName;
5392 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005393 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005394 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005395 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005396 + " without first uninstalling.");
5397 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5398 return;
5399 }
5400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005401 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005402 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005403 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005404 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005405 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5406 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5407 }
5408 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005409 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005410 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005411 res);
5412 // delete the partially installed application. the data directory will have to be
5413 // restored if it was already existing
5414 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5415 // remove package from internal structures. Note that we want deletePackageX to
5416 // delete the package data and cache directories that it created in
5417 // scanPackageLocked, unless those directories existed before we even tried to
5418 // install.
5419 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005420 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005421 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5422 res.removedInfo);
5423 }
5424 }
5425 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005426
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005427 private void replacePackageLI(PackageParser.Package pkg,
5428 int parseFlags,
5429 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005430 String installerPackageName, PackageInstalledInfo res) {
5431
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005432 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005433 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005434 // First find the old package info and check signatures
5435 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005436 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005437 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005438 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5440 return;
5441 }
5442 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005443 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005444 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005445 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005447 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 }
5449 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005452 PackageParser.Package pkg,
5453 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005454 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 PackageParser.Package newPackage = null;
5456 String pkgName = deletedPackage.packageName;
5457 boolean deletedPkg = true;
5458 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005459
Jacek Surazski65e13172009-04-28 15:26:38 +02005460 String oldInstallerPackageName = null;
5461 synchronized (mPackages) {
5462 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5463 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005464
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005465 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005467 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 res.removedInfo)) {
5469 // If the existing package was'nt successfully deleted
5470 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5471 deletedPkg = false;
5472 } else {
5473 // Successfully deleted the old package. Now proceed with re-installation
5474 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005475 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005477 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5479 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005480 }
5481 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005482 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005483 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 res);
5485 updatedSettings = true;
5486 }
5487 }
5488
5489 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5490 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005491 // were keeping around in case we needed them (see below) can now be deleted.
5492 // This info will be set on the res.removedInfo to clean up later on as post
5493 // install action.
5494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 //update signature on the new package setting
5496 //this should always succeed, since we checked the
5497 //signature earlier.
5498 synchronized(mPackages) {
5499 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5500 parseFlags, true);
5501 }
5502 } else {
5503 // remove package from internal structures. Note that we want deletePackageX to
5504 // delete the package data and cache directories that it created in
5505 // scanPackageLocked, unless those directories existed before we even tried to
5506 // install.
5507 if(updatedSettings) {
5508 deletePackageLI(
5509 pkgName, true,
5510 PackageManager.DONT_DELETE_DATA,
5511 res.removedInfo);
5512 }
5513 // Since we failed to install the new package we need to restore the old
5514 // package that we deleted.
5515 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005516 File restoreFile = new File(deletedPackage.mPath);
5517 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005518 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005519 return;
5520 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005521 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5522 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005523 // Parse old package
5524 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5525 scanPackageLI(restoreFile, parseFlags, scanMode);
5526 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005527 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5528 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005529 mSettings.writeLP();
5530 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005531 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005532 Slog.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005534 }
5535 }
5536 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005538 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005539 PackageParser.Package pkg,
5540 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005541 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 PackageParser.Package newPackage = null;
5543 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005544 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 PackageParser.PARSE_IS_SYSTEM;
5546 String packageName = deletedPackage.packageName;
5547 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5548 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005549 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550 return;
5551 }
5552 PackageParser.Package oldPkg;
5553 PackageSetting oldPkgSetting;
5554 synchronized (mPackages) {
5555 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005556 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5558 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005559 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005560 return;
5561 }
5562 }
5563 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5564 res.removedInfo.removedPackage = packageName;
5565 // Remove existing system package
5566 removePackageLI(oldPkg, true);
5567 synchronized (mPackages) {
5568 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5569 }
5570
5571 // Successfully disabled the old package. Now proceed with re-installation
5572 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5573 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005574 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005576 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5578 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5579 }
5580 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005581 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 updatedSettings = true;
5583 }
5584
5585 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5586 //update signature on the new package setting
5587 //this should always succeed, since we checked the
5588 //signature earlier.
5589 synchronized(mPackages) {
5590 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5591 parseFlags, true);
5592 }
5593 } else {
5594 // Re installation failed. Restore old information
5595 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005596 if (newPackage != null) {
5597 removePackageLI(newPackage, true);
5598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005600 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005602 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 // Restore the old system information in Settings
5604 synchronized(mPackages) {
5605 if(updatedSettings) {
5606 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005607 mSettings.setInstallerPackageName(packageName,
5608 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 }
5610 mSettings.writeLP();
5611 }
5612 }
5613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005614
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005615 // Utility method used to move dex files during install.
5616 private int moveDexFiles(PackageParser.Package newPackage) {
5617 int retCode;
5618 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5619 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5620 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005621 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005622 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5623 }
5624 }
5625 return PackageManager.INSTALL_SUCCEEDED;
5626 }
5627
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005628 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005629 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005630 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005631 synchronized (mPackages) {
5632 //write settings. the installStatus will be incomplete at this stage.
5633 //note that the new package setting would have already been
5634 //added to mPackages. It hasn't been persisted yet.
5635 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5636 mSettings.writeLP();
5637 }
5638
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005639 if ((res.returnCode = moveDexFiles(newPackage))
5640 != PackageManager.INSTALL_SUCCEEDED) {
5641 // Discontinue if moving dex files failed.
5642 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005644 if((res.returnCode = setPermissionsLI(newPackage))
5645 != PackageManager.INSTALL_SUCCEEDED) {
5646 if (mInstaller != null) {
5647 mInstaller.rmdex(newPackage.mScanPath);
5648 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005649 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005651 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005654 updatePermissionsLP(newPackage.packageName, newPackage,
5655 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 res.name = pkgName;
5657 res.uid = newPackage.applicationInfo.uid;
5658 res.pkg = newPackage;
5659 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005660 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5662 //to update install status
5663 mSettings.writeLP();
5664 }
5665 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005666
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005667 private void installPackageLI(InstallArgs args,
5668 boolean newInstall, PackageInstalledInfo res) {
5669 int pFlags = args.flags;
5670 String installerPackageName = args.installerPackageName;
5671 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005672 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005673 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005674 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005675 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5676 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005677 // Result object to be returned
5678 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5679
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005680 // Retrieve PackageSettings and parse package
5681 int parseFlags = PackageParser.PARSE_CHATTY |
5682 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5683 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5684 parseFlags |= mDefParseFlags;
5685 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5686 pp.setSeparateProcesses(mSeparateProcesses);
5687 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5688 null, mMetrics, parseFlags);
5689 if (pkg == null) {
5690 res.returnCode = pp.getParseError();
5691 return;
5692 }
5693 String pkgName = res.name = pkg.packageName;
5694 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5695 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5696 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5697 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005698 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005699 }
5700 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5701 res.returnCode = pp.getParseError();
5702 return;
5703 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005704 // Get rid of all references to package scan path via parser.
5705 pp = null;
5706 String oldCodePath = null;
5707 boolean systemApp = false;
5708 synchronized (mPackages) {
5709 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005710 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5711 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005712 if (pkg.mOriginalPackages != null
5713 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005714 && mPackages.containsKey(oldName)) {
5715 // This package is derived from an original package,
5716 // and this device has been updating from that original
5717 // name. We must continue using the original name, so
5718 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005719 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005720 pkgName = pkg.packageName;
5721 replace = true;
5722 } else if (mPackages.containsKey(pkgName)) {
5723 // This package, under its official name, already exists
5724 // on the device; we should replace it.
5725 replace = true;
5726 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005727 }
5728 PackageSetting ps = mSettings.mPackages.get(pkgName);
5729 if (ps != null) {
5730 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5731 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5732 systemApp = (ps.pkg.applicationInfo.flags &
5733 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005734 }
5735 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005736 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005737
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005738 if (systemApp && onSd) {
5739 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005740 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005741 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5742 return;
5743 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005744
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005745 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5746 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5747 return;
5748 }
5749 // Set application objects path explicitly after the rename
5750 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005751 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005752 replacePackageLI(pkg, parseFlags, scanMode,
5753 installerPackageName, res);
5754 } else {
5755 installNewPackageLI(pkg, parseFlags, scanMode,
5756 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005757 }
5758 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005759
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005760 private int setPermissionsLI(PackageParser.Package newPackage) {
5761 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005762 int retCode = 0;
5763 // TODO Gross hack but fix later. Ideally move this to be a post installation
5764 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005765 if ((newPackage.applicationInfo.flags
5766 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5767 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 try {
5769 extractPublicFiles(newPackage, destResourceFile);
5770 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005771 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 -08005772 " forward-locked app.");
5773 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5774 } finally {
5775 //TODO clean up the extracted public files
5776 }
5777 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005778 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 newPackage.applicationInfo.uid);
5780 } else {
5781 final int filePermissions =
5782 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005783 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 newPackage.applicationInfo.uid);
5785 }
5786 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005787 // The permissions on the resource file was set when it was copied for
5788 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005791 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005792 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005793 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005795 // TODO Define new internal error
5796 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 }
5798 return PackageManager.INSTALL_SUCCEEDED;
5799 }
5800
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005801 private boolean isForwardLocked(PackageParser.Package pkg) {
5802 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 }
5804
5805 private void extractPublicFiles(PackageParser.Package newPackage,
5806 File publicZipFile) throws IOException {
5807 final ZipOutputStream publicZipOutStream =
5808 new ZipOutputStream(new FileOutputStream(publicZipFile));
5809 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5810
5811 // Copy manifest, resources.arsc and res directory to public zip
5812
5813 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5814 while (privateZipEntries.hasMoreElements()) {
5815 final ZipEntry zipEntry = privateZipEntries.nextElement();
5816 final String zipEntryName = zipEntry.getName();
5817 if ("AndroidManifest.xml".equals(zipEntryName)
5818 || "resources.arsc".equals(zipEntryName)
5819 || zipEntryName.startsWith("res/")) {
5820 try {
5821 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5822 } catch (IOException e) {
5823 try {
5824 publicZipOutStream.close();
5825 throw e;
5826 } finally {
5827 publicZipFile.delete();
5828 }
5829 }
5830 }
5831 }
5832
5833 publicZipOutStream.close();
5834 FileUtils.setPermissions(
5835 publicZipFile.getAbsolutePath(),
5836 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5837 -1, -1);
5838 }
5839
5840 private static void copyZipEntry(ZipEntry zipEntry,
5841 ZipFile inZipFile,
5842 ZipOutputStream outZipStream) throws IOException {
5843 byte[] buffer = new byte[4096];
5844 int num;
5845
5846 ZipEntry newEntry;
5847 if (zipEntry.getMethod() == ZipEntry.STORED) {
5848 // Preserve the STORED method of the input entry.
5849 newEntry = new ZipEntry(zipEntry);
5850 } else {
5851 // Create a new entry so that the compressed len is recomputed.
5852 newEntry = new ZipEntry(zipEntry.getName());
5853 }
5854 outZipStream.putNextEntry(newEntry);
5855
5856 InputStream data = inZipFile.getInputStream(zipEntry);
5857 while ((num = data.read(buffer)) > 0) {
5858 outZipStream.write(buffer, 0, num);
5859 }
5860 outZipStream.flush();
5861 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 private void deleteTempPackageFiles() {
5864 FilenameFilter filter = new FilenameFilter() {
5865 public boolean accept(File dir, String name) {
5866 return name.startsWith("vmdl") && name.endsWith(".tmp");
5867 }
5868 };
5869 String tmpFilesList[] = mAppInstallDir.list(filter);
5870 if(tmpFilesList == null) {
5871 return;
5872 }
5873 for(int i = 0; i < tmpFilesList.length; i++) {
5874 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5875 tmpFile.delete();
5876 }
5877 }
5878
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005879 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 File tmpPackageFile;
5881 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005882 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005884 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 return null;
5886 }
5887 try {
5888 FileUtils.setPermissions(
5889 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5890 -1, -1);
5891 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005892 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 return null;
5894 }
5895 return tmpPackageFile;
5896 }
5897
5898 public void deletePackage(final String packageName,
5899 final IPackageDeleteObserver observer,
5900 final int flags) {
5901 mContext.enforceCallingOrSelfPermission(
5902 android.Manifest.permission.DELETE_PACKAGES, null);
5903 // Queue up an async operation since the package deletion may take a little while.
5904 mHandler.post(new Runnable() {
5905 public void run() {
5906 mHandler.removeCallbacks(this);
5907 final boolean succeded = deletePackageX(packageName, true, true, flags);
5908 if (observer != null) {
5909 try {
5910 observer.packageDeleted(succeded);
5911 } catch (RemoteException e) {
5912 Log.i(TAG, "Observer no longer exists.");
5913 } //end catch
5914 } //end if
5915 } //end run
5916 });
5917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005919 /**
5920 * This method is an internal method that could be get invoked either
5921 * to delete an installed package or to clean up a failed installation.
5922 * After deleting an installed package, a broadcast is sent to notify any
5923 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005924 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 * installation wouldn't have sent the initial broadcast either
5926 * The key steps in deleting a package are
5927 * deleting the package information in internal structures like mPackages,
5928 * deleting the packages base directories through installd
5929 * updating mSettings to reflect current status
5930 * persisting settings for later use
5931 * sending a broadcast if necessary
5932 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005933 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5934 boolean deleteCodeAndResources, int flags) {
5935 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005936 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005937
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005938 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5939 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5940 try {
5941 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005942 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005943 return false;
5944 }
5945 } catch (RemoteException e) {
5946 }
5947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005948 synchronized (mInstallLock) {
5949 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5950 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005952 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005953 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5954 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5955
5956 // If the removed package was a system update, the old system packaged
5957 // was re-enabled; we need to broadcast this information
5958 if (systemUpdate) {
5959 Bundle extras = new Bundle(1);
5960 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5961 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5962
5963 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5964 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005967 // Force a gc here.
5968 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005969 // Delete the resources here after sending the broadcast to let
5970 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005971 if (info.args != null) {
5972 synchronized (mInstallLock) {
5973 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005974 }
5975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 return res;
5977 }
5978
5979 static class PackageRemovedInfo {
5980 String removedPackage;
5981 int uid = -1;
5982 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005983 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005984 // Clean up resources deleted packages.
5985 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 void sendBroadcast(boolean fullRemove, boolean replacing) {
5988 Bundle extras = new Bundle(1);
5989 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5990 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5991 if (replacing) {
5992 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5993 }
5994 if (removedPackage != null) {
5995 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5996 }
5997 if (removedUid >= 0) {
5998 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5999 }
6000 }
6001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006003 /*
6004 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6005 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006006 * 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 -08006007 * delete a partially installed application.
6008 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006009 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 int flags) {
6011 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006012 if (outInfo != null) {
6013 outInfo.removedPackage = packageName;
6014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 removePackageLI(p, true);
6016 // Retrieve object to delete permissions for shared user later on
6017 PackageSetting deletedPs;
6018 synchronized (mPackages) {
6019 deletedPs = mSettings.mPackages.get(packageName);
6020 }
6021 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006022 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006023 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006024 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006026 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 + packageName + ", retcode=" + retCode);
6028 // we don't consider this to be a failure of the core package deletion
6029 }
6030 } else {
6031 //for emulator
6032 PackageParser.Package pkg = mPackages.get(packageName);
6033 File dataDir = new File(pkg.applicationInfo.dataDir);
6034 dataDir.delete();
6035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 }
6037 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006038 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006039 schedulePackageCleaning(packageName);
6040
6041 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6042 if (outInfo != null) {
6043 outInfo.removedUid = mSettings.removePackageLP(packageName);
6044 }
6045 if (deletedPs != null) {
6046 updatePermissionsLP(deletedPs.name, null, false, false);
6047 if (deletedPs.sharedUser != null) {
6048 // remove permissions associated with package
6049 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6050 }
6051 }
6052 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006053 // remove from preferred activities.
6054 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6055 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6056 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6057 removed.add(pa);
6058 }
6059 }
6060 for (PreferredActivity pa : removed) {
6061 mSettings.mPreferredActivities.removeFilter(pa);
6062 }
6063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006065 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 }
6067 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006069 /*
6070 * Tries to delete system package.
6071 */
6072 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006073 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006074 ApplicationInfo applicationInfo = p.applicationInfo;
6075 //applicable for non-partially installed applications only
6076 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006077 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 return false;
6079 }
6080 PackageSetting ps = null;
6081 // Confirm if the system package has been updated
6082 // An updated system app can be deleted. This will also have to restore
6083 // the system pkg from system partition
6084 synchronized (mPackages) {
6085 ps = mSettings.getDisabledSystemPkg(p.packageName);
6086 }
6087 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006088 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 return false;
6090 } else {
6091 Log.i(TAG, "Deleting system pkg from data partition");
6092 }
6093 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006094 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006095 boolean deleteCodeAndResources = false;
6096 if (ps.versionCode < p.mVersionCode) {
6097 // Delete code and resources for downgrades
6098 deleteCodeAndResources = true;
6099 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6100 flags &= ~PackageManager.DONT_DELETE_DATA;
6101 }
6102 } else {
6103 // Preserve data by setting flag
6104 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6105 flags |= PackageManager.DONT_DELETE_DATA;
6106 }
6107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006108 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6109 if (!ret) {
6110 return false;
6111 }
6112 synchronized (mPackages) {
6113 // Reinstate the old system package
6114 mSettings.enableSystemPackageLP(p.packageName);
6115 }
6116 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006117 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006118 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006119 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006122 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 return false;
6124 }
6125 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006126 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 mSettings.writeLP();
6128 }
6129 return true;
6130 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6133 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6134 ApplicationInfo applicationInfo = p.applicationInfo;
6135 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006136 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 return false;
6138 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006139 if (outInfo != null) {
6140 outInfo.uid = applicationInfo.uid;
6141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142
6143 // Delete package data from internal structures and also remove data if flag is set
6144 removePackageDataLI(p, outInfo, flags);
6145
6146 // Delete application code and resources
6147 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006148 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006149 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006150 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006151 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6152 PackageManager.INSTALL_FORWARD_LOCK : 0;
6153 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006154 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 }
6156 return true;
6157 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006159 /*
6160 * This method handles package deletion in general
6161 */
6162 private boolean deletePackageLI(String packageName,
6163 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6164 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006165 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 return false;
6167 }
6168 PackageParser.Package p;
6169 boolean dataOnly = false;
6170 synchronized (mPackages) {
6171 p = mPackages.get(packageName);
6172 if (p == null) {
6173 //this retrieves partially installed apps
6174 dataOnly = true;
6175 PackageSetting ps = mSettings.mPackages.get(packageName);
6176 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006177 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 return false;
6179 }
6180 p = ps.pkg;
6181 }
6182 }
6183 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006184 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 return false;
6186 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 if (dataOnly) {
6189 // Delete application data first
6190 removePackageDataLI(p, outInfo, flags);
6191 return true;
6192 }
6193 // At this point the package should have ApplicationInfo associated with it
6194 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006195 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 return false;
6197 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006198 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6200 Log.i(TAG, "Removing system package:"+p.packageName);
6201 // When an updated system application is deleted we delete the existing resources as well and
6202 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006203 ret = deleteSystemPackageLI(p, flags, outInfo);
6204 } else {
6205 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006206 // Kill application pre-emptively especially for apps on sd.
6207 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006208 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006210 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 public void clearApplicationUserData(final String packageName,
6214 final IPackageDataObserver observer) {
6215 mContext.enforceCallingOrSelfPermission(
6216 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6217 // Queue up an async operation since the package deletion may take a little while.
6218 mHandler.post(new Runnable() {
6219 public void run() {
6220 mHandler.removeCallbacks(this);
6221 final boolean succeeded;
6222 synchronized (mInstallLock) {
6223 succeeded = clearApplicationUserDataLI(packageName);
6224 }
6225 if (succeeded) {
6226 // invoke DeviceStorageMonitor's update method to clear any notifications
6227 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6228 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6229 if (dsm != null) {
6230 dsm.updateMemory();
6231 }
6232 }
6233 if(observer != null) {
6234 try {
6235 observer.onRemoveCompleted(packageName, succeeded);
6236 } catch (RemoteException e) {
6237 Log.i(TAG, "Observer no longer exists.");
6238 }
6239 } //end if observer
6240 } //end run
6241 });
6242 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 private boolean clearApplicationUserDataLI(String packageName) {
6245 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006246 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 return false;
6248 }
6249 PackageParser.Package p;
6250 boolean dataOnly = false;
6251 synchronized (mPackages) {
6252 p = mPackages.get(packageName);
6253 if(p == null) {
6254 dataOnly = true;
6255 PackageSetting ps = mSettings.mPackages.get(packageName);
6256 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006257 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 return false;
6259 }
6260 p = ps.pkg;
6261 }
6262 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006263 boolean useEncryptedFSDir = false;
6264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 if(!dataOnly) {
6266 //need to check this only for fully installed applications
6267 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006268 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 return false;
6270 }
6271 final ApplicationInfo applicationInfo = p.applicationInfo;
6272 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006273 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 return false;
6275 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006276 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 }
6278 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006279 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006281 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 + packageName);
6283 return false;
6284 }
6285 }
6286 return true;
6287 }
6288
6289 public void deleteApplicationCacheFiles(final String packageName,
6290 final IPackageDataObserver observer) {
6291 mContext.enforceCallingOrSelfPermission(
6292 android.Manifest.permission.DELETE_CACHE_FILES, null);
6293 // Queue up an async operation since the package deletion may take a little while.
6294 mHandler.post(new Runnable() {
6295 public void run() {
6296 mHandler.removeCallbacks(this);
6297 final boolean succeded;
6298 synchronized (mInstallLock) {
6299 succeded = deleteApplicationCacheFilesLI(packageName);
6300 }
6301 if(observer != null) {
6302 try {
6303 observer.onRemoveCompleted(packageName, succeded);
6304 } catch (RemoteException e) {
6305 Log.i(TAG, "Observer no longer exists.");
6306 }
6307 } //end if observer
6308 } //end run
6309 });
6310 }
6311
6312 private boolean deleteApplicationCacheFilesLI(String packageName) {
6313 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006314 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006315 return false;
6316 }
6317 PackageParser.Package p;
6318 synchronized (mPackages) {
6319 p = mPackages.get(packageName);
6320 }
6321 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006322 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 return false;
6324 }
6325 final ApplicationInfo applicationInfo = p.applicationInfo;
6326 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006327 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 return false;
6329 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006330 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006332 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006334 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 + packageName);
6336 return false;
6337 }
6338 }
6339 return true;
6340 }
6341
6342 public void getPackageSizeInfo(final String packageName,
6343 final IPackageStatsObserver observer) {
6344 mContext.enforceCallingOrSelfPermission(
6345 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6346 // Queue up an async operation since the package deletion may take a little while.
6347 mHandler.post(new Runnable() {
6348 public void run() {
6349 mHandler.removeCallbacks(this);
6350 PackageStats lStats = new PackageStats(packageName);
6351 final boolean succeded;
6352 synchronized (mInstallLock) {
6353 succeded = getPackageSizeInfoLI(packageName, lStats);
6354 }
6355 if(observer != null) {
6356 try {
6357 observer.onGetStatsCompleted(lStats, succeded);
6358 } catch (RemoteException e) {
6359 Log.i(TAG, "Observer no longer exists.");
6360 }
6361 } //end if observer
6362 } //end run
6363 });
6364 }
6365
6366 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6367 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006368 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 return false;
6370 }
6371 PackageParser.Package p;
6372 boolean dataOnly = false;
6373 synchronized (mPackages) {
6374 p = mPackages.get(packageName);
6375 if(p == null) {
6376 dataOnly = true;
6377 PackageSetting ps = mSettings.mPackages.get(packageName);
6378 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006379 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 return false;
6381 }
6382 p = ps.pkg;
6383 }
6384 }
6385 String publicSrcDir = null;
6386 if(!dataOnly) {
6387 final ApplicationInfo applicationInfo = p.applicationInfo;
6388 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006389 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 return false;
6391 }
6392 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6393 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006394 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 if (mInstaller != null) {
6396 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006397 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 if (res < 0) {
6399 return false;
6400 } else {
6401 return true;
6402 }
6403 }
6404 return true;
6405 }
6406
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 public void addPackageToPreferred(String packageName) {
6409 mContext.enforceCallingOrSelfPermission(
6410 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006411 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 }
6413
6414 public void removePackageFromPreferred(String packageName) {
6415 mContext.enforceCallingOrSelfPermission(
6416 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006417 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 }
6419
6420 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006421 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 }
6423
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006424 int getUidTargetSdkVersionLockedLP(int uid) {
6425 Object obj = mSettings.getUserIdLP(uid);
6426 if (obj instanceof SharedUserSetting) {
6427 SharedUserSetting sus = (SharedUserSetting)obj;
6428 final int N = sus.packages.size();
6429 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6430 Iterator<PackageSetting> it = sus.packages.iterator();
6431 int i=0;
6432 while (it.hasNext()) {
6433 PackageSetting ps = it.next();
6434 if (ps.pkg != null) {
6435 int v = ps.pkg.applicationInfo.targetSdkVersion;
6436 if (v < vers) vers = v;
6437 }
6438 }
6439 return vers;
6440 } else if (obj instanceof PackageSetting) {
6441 PackageSetting ps = (PackageSetting)obj;
6442 if (ps.pkg != null) {
6443 return ps.pkg.applicationInfo.targetSdkVersion;
6444 }
6445 }
6446 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6447 }
6448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 public void addPreferredActivity(IntentFilter filter, int match,
6450 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006452 if (mContext.checkCallingOrSelfPermission(
6453 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6454 != PackageManager.PERMISSION_GRANTED) {
6455 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6456 < Build.VERSION_CODES.FROYO) {
6457 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6458 + Binder.getCallingUid());
6459 return;
6460 }
6461 mContext.enforceCallingOrSelfPermission(
6462 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6463 }
6464
6465 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006466 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6467 mSettings.mPreferredActivities.addFilter(
6468 new PreferredActivity(filter, match, set, activity));
6469 mSettings.writeLP();
6470 }
6471 }
6472
Satish Sampath8dbe6122009-06-02 23:35:54 +01006473 public void replacePreferredActivity(IntentFilter filter, int match,
6474 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006475 if (filter.countActions() != 1) {
6476 throw new IllegalArgumentException(
6477 "replacePreferredActivity expects filter to have only 1 action.");
6478 }
6479 if (filter.countCategories() != 1) {
6480 throw new IllegalArgumentException(
6481 "replacePreferredActivity expects filter to have only 1 category.");
6482 }
6483 if (filter.countDataAuthorities() != 0
6484 || filter.countDataPaths() != 0
6485 || filter.countDataSchemes() != 0
6486 || filter.countDataTypes() != 0) {
6487 throw new IllegalArgumentException(
6488 "replacePreferredActivity expects filter to have no data authorities, " +
6489 "paths, schemes or types.");
6490 }
6491 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006492 if (mContext.checkCallingOrSelfPermission(
6493 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6494 != PackageManager.PERMISSION_GRANTED) {
6495 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6496 < Build.VERSION_CODES.FROYO) {
6497 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6498 + Binder.getCallingUid());
6499 return;
6500 }
6501 mContext.enforceCallingOrSelfPermission(
6502 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6503 }
6504
Satish Sampath8dbe6122009-06-02 23:35:54 +01006505 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6506 String action = filter.getAction(0);
6507 String category = filter.getCategory(0);
6508 while (it.hasNext()) {
6509 PreferredActivity pa = it.next();
6510 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6511 it.remove();
6512 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6513 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6514 }
6515 }
6516 addPreferredActivity(filter, match, set, activity);
6517 }
6518 }
6519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006522 int uid = Binder.getCallingUid();
6523 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006524 if (pkg == null || pkg.applicationInfo.uid != uid) {
6525 if (mContext.checkCallingOrSelfPermission(
6526 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6527 != PackageManager.PERMISSION_GRANTED) {
6528 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6529 < Build.VERSION_CODES.FROYO) {
6530 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6531 + Binder.getCallingUid());
6532 return;
6533 }
6534 mContext.enforceCallingOrSelfPermission(
6535 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6536 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006537 }
6538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 if (clearPackagePreferredActivitiesLP(packageName)) {
6540 mSettings.writeLP();
6541 }
6542 }
6543 }
6544
6545 boolean clearPackagePreferredActivitiesLP(String packageName) {
6546 boolean changed = false;
6547 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6548 while (it.hasNext()) {
6549 PreferredActivity pa = it.next();
6550 if (pa.mActivity.getPackageName().equals(packageName)) {
6551 it.remove();
6552 changed = true;
6553 }
6554 }
6555 return changed;
6556 }
6557
6558 public int getPreferredActivities(List<IntentFilter> outFilters,
6559 List<ComponentName> outActivities, String packageName) {
6560
6561 int num = 0;
6562 synchronized (mPackages) {
6563 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6564 while (it.hasNext()) {
6565 PreferredActivity pa = it.next();
6566 if (packageName == null
6567 || pa.mActivity.getPackageName().equals(packageName)) {
6568 if (outFilters != null) {
6569 outFilters.add(new IntentFilter(pa));
6570 }
6571 if (outActivities != null) {
6572 outActivities.add(pa.mActivity);
6573 }
6574 }
6575 }
6576 }
6577
6578 return num;
6579 }
6580
6581 public void setApplicationEnabledSetting(String appPackageName,
6582 int newState, int flags) {
6583 setEnabledSetting(appPackageName, null, newState, flags);
6584 }
6585
6586 public void setComponentEnabledSetting(ComponentName componentName,
6587 int newState, int flags) {
6588 setEnabledSetting(componentName.getPackageName(),
6589 componentName.getClassName(), newState, flags);
6590 }
6591
6592 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006593 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6595 || newState == COMPONENT_ENABLED_STATE_ENABLED
6596 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6597 throw new IllegalArgumentException("Invalid new component state: "
6598 + newState);
6599 }
6600 PackageSetting pkgSetting;
6601 final int uid = Binder.getCallingUid();
6602 final int permission = mContext.checkCallingPermission(
6603 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6604 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006605 boolean sendNow = false;
6606 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006607 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006609 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006611 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006613 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006615 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 }
6617 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006618 "Unknown component: " + packageName
6619 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 }
6621 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6622 throw new SecurityException(
6623 "Permission Denial: attempt to change component state from pid="
6624 + Binder.getCallingPid()
6625 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6626 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006627 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 // We're dealing with an application/package level state change
6629 pkgSetting.enabled = newState;
6630 } else {
6631 // We're dealing with a component level state change
6632 switch (newState) {
6633 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006634 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 break;
6636 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006637 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006638 break;
6639 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006640 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 break;
6642 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006643 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006644 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 }
6646 }
6647 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006648 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006649 components = mPendingBroadcasts.get(packageName);
6650 boolean newPackage = components == null;
6651 if (newPackage) {
6652 components = new ArrayList<String>();
6653 }
6654 if (!components.contains(componentName)) {
6655 components.add(componentName);
6656 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006657 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6658 sendNow = true;
6659 // Purge entry from pending broadcast list if another one exists already
6660 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006661 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006662 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006663 if (newPackage) {
6664 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006665 }
6666 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6667 // Schedule a message
6668 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6669 }
6670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006673 long callingId = Binder.clearCallingIdentity();
6674 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006675 if (sendNow) {
6676 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006677 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 } finally {
6680 Binder.restoreCallingIdentity(callingId);
6681 }
6682 }
6683
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006684 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006685 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6686 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6687 + " components=" + componentNames);
6688 Bundle extras = new Bundle(4);
6689 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6690 String nameList[] = new String[componentNames.size()];
6691 componentNames.toArray(nameList);
6692 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006693 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6694 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006695 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006696 }
6697
Jacek Surazski65e13172009-04-28 15:26:38 +02006698 public String getInstallerPackageName(String packageName) {
6699 synchronized (mPackages) {
6700 PackageSetting pkg = mSettings.mPackages.get(packageName);
6701 if (pkg == null) {
6702 throw new IllegalArgumentException("Unknown package: " + packageName);
6703 }
6704 return pkg.installerPackageName;
6705 }
6706 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 public int getApplicationEnabledSetting(String appPackageName) {
6709 synchronized (mPackages) {
6710 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6711 if (pkg == null) {
6712 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6713 }
6714 return pkg.enabled;
6715 }
6716 }
6717
6718 public int getComponentEnabledSetting(ComponentName componentName) {
6719 synchronized (mPackages) {
6720 final String packageNameStr = componentName.getPackageName();
6721 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6722 if (pkg == null) {
6723 throw new IllegalArgumentException("Unknown component: " + componentName);
6724 }
6725 final String classNameStr = componentName.getClassName();
6726 return pkg.currentEnabledStateLP(classNameStr);
6727 }
6728 }
6729
6730 public void enterSafeMode() {
6731 if (!mSystemReady) {
6732 mSafeMode = true;
6733 }
6734 }
6735
6736 public void systemReady() {
6737 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006738
6739 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006740 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006741 mContext.getContentResolver(),
6742 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006743 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006744 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006745 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 }
6748
6749 public boolean isSafeMode() {
6750 return mSafeMode;
6751 }
6752
6753 public boolean hasSystemUidErrors() {
6754 return mHasSystemUidErrors;
6755 }
6756
6757 static String arrayToString(int[] array) {
6758 StringBuffer buf = new StringBuffer(128);
6759 buf.append('[');
6760 if (array != null) {
6761 for (int i=0; i<array.length; i++) {
6762 if (i > 0) buf.append(", ");
6763 buf.append(array[i]);
6764 }
6765 }
6766 buf.append(']');
6767 return buf.toString();
6768 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006770 @Override
6771 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6772 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6773 != PackageManager.PERMISSION_GRANTED) {
6774 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6775 + Binder.getCallingPid()
6776 + ", uid=" + Binder.getCallingUid()
6777 + " without permission "
6778 + android.Manifest.permission.DUMP);
6779 return;
6780 }
6781
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006782 String packageName = null;
6783
6784 int opti = 0;
6785 while (opti < args.length) {
6786 String opt = args[opti];
6787 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6788 break;
6789 }
6790 opti++;
6791 if ("-a".equals(opt)) {
6792 // Right now we only know how to print all.
6793 } else if ("-h".equals(opt)) {
6794 pw.println("Package manager dump options:");
6795 pw.println(" [-h] [cmd] ...");
6796 pw.println(" cmd may be one of:");
6797 pw.println(" [package.name]: info about given package");
6798 return;
6799 } else {
6800 pw.println("Unknown argument: " + opt + "; use -h for help");
6801 }
6802 }
6803
6804 // Is the caller requesting to dump a particular piece of data?
6805 if (opti < args.length) {
6806 String cmd = args[opti];
6807 opti++;
6808 // Is this a package name?
6809 if ("android".equals(cmd) || cmd.contains(".")) {
6810 packageName = cmd;
6811 }
6812 }
6813
6814 boolean printedTitle = false;
6815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006816 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006817 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6818 printedTitle = true;
6819 }
6820 if (mReceivers.dump(pw, printedTitle
6821 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6822 " ", packageName)) {
6823 printedTitle = true;
6824 }
6825 if (mServices.dump(pw, printedTitle
6826 ? "\nService Resolver Table:" : "Service Resolver Table:",
6827 " ", packageName)) {
6828 printedTitle = true;
6829 }
6830 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6831 ? "\nPreferred Activities:" : "Preferred Activities:",
6832 " ", packageName)) {
6833 printedTitle = true;
6834 }
6835 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 {
6837 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006838 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6839 continue;
6840 }
6841 if (!printedSomething) {
6842 if (printedTitle) pw.println(" ");
6843 pw.println("Permissions:");
6844 printedSomething = true;
6845 printedTitle = true;
6846 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006847 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6848 pw.print(Integer.toHexString(System.identityHashCode(p)));
6849 pw.println("):");
6850 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6851 pw.print(" uid="); pw.print(p.uid);
6852 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006853 pw.print(" type="); pw.print(p.type);
6854 pw.print(" prot="); pw.println(p.protectionLevel);
6855 if (p.packageSetting != null) {
6856 pw.print(" packageSetting="); pw.println(p.packageSetting);
6857 }
6858 if (p.perm != null) {
6859 pw.print(" perm="); pw.println(p.perm);
6860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 }
6862 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006863 printedSomething = false;
6864 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865 {
6866 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006867 if (packageName != null && !packageName.equals(ps.realName)
6868 && !packageName.equals(ps.name)) {
6869 continue;
6870 }
6871 if (!printedSomething) {
6872 if (printedTitle) pw.println(" ");
6873 pw.println("Packages:");
6874 printedSomething = true;
6875 printedTitle = true;
6876 }
6877 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006878 pw.print(" Package [");
6879 pw.print(ps.realName != null ? ps.realName : ps.name);
6880 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006881 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6882 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006883 if (ps.realName != null) {
6884 pw.print(" compat name="); pw.println(ps.name);
6885 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006886 pw.print(" userId="); pw.print(ps.userId);
6887 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6888 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6889 pw.print(" pkg="); pw.println(ps.pkg);
6890 pw.print(" codePath="); pw.println(ps.codePathString);
6891 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006892 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006893 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006894 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006895 pw.print(" supportsScreens=[");
6896 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006897 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006898 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006899 if (!first) pw.print(", ");
6900 first = false;
6901 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006902 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006903 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006904 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006905 if (!first) pw.print(", ");
6906 first = false;
6907 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006909 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006910 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006911 if (!first) pw.print(", ");
6912 first = false;
6913 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006914 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006915 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006916 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006917 if (!first) pw.print(", ");
6918 first = false;
6919 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006920 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006921 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006922 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6923 if (!first) pw.print(", ");
6924 first = false;
6925 pw.print("anyDensity");
6926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006927 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006928 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006929 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6930 pw.print(" signatures="); pw.println(ps.signatures);
6931 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07006932 pw.print(" haveGids="); pw.println(ps.haveGids);
6933 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006934 pw.print(" installStatus="); pw.print(ps.installStatus);
6935 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006936 if (ps.disabledComponents.size() > 0) {
6937 pw.println(" disabledComponents:");
6938 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006939 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006940 }
6941 }
6942 if (ps.enabledComponents.size() > 0) {
6943 pw.println(" enabledComponents:");
6944 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006945 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 }
6947 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006948 if (ps.grantedPermissions.size() > 0) {
6949 pw.println(" grantedPermissions:");
6950 for (String s : ps.grantedPermissions) {
6951 pw.print(" "); pw.println(s);
6952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006954 }
6955 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006956 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006957 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006958 for (HashMap.Entry<String, String> e
6959 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006960 if (packageName != null && !packageName.equals(e.getKey())
6961 && !packageName.equals(e.getValue())) {
6962 continue;
6963 }
6964 if (!printedSomething) {
6965 if (printedTitle) pw.println(" ");
6966 pw.println("Renamed packages:");
6967 printedSomething = true;
6968 printedTitle = true;
6969 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006970 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6971 pw.println(e.getValue());
6972 }
6973 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006974 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006975 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006976 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006977 if (packageName != null && !packageName.equals(ps.realName)
6978 && !packageName.equals(ps.name)) {
6979 continue;
6980 }
6981 if (!printedSomething) {
6982 if (printedTitle) pw.println(" ");
6983 pw.println("Hidden system packages:");
6984 printedSomething = true;
6985 printedTitle = true;
6986 }
6987 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006988 pw.print(ps.realName != null ? ps.realName : ps.name);
6989 pw.print("] (");
6990 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6991 pw.println("):");
6992 if (ps.realName != null) {
6993 pw.print(" compat name="); pw.println(ps.name);
6994 }
6995 pw.print(" userId="); pw.println(ps.userId);
6996 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6997 pw.print(" codePath="); pw.println(ps.codePathString);
6998 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6999 }
7000 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007001 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007002 {
7003 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007004 if (packageName != null && su != packageSharedUser) {
7005 continue;
7006 }
7007 if (!printedSomething) {
7008 if (printedTitle) pw.println(" ");
7009 pw.println("Shared users:");
7010 printedSomething = true;
7011 printedTitle = true;
7012 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007013 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7014 pw.print(Integer.toHexString(System.identityHashCode(su)));
7015 pw.println("):");
7016 pw.print(" userId="); pw.print(su.userId);
7017 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007018 pw.println(" grantedPermissions:");
7019 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007020 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 }
7023 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007024
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007025 if (packageName == null) {
7026 if (printedTitle) pw.println(" ");
7027 printedTitle = true;
7028 pw.println("Settings parse messages:");
7029 pw.println(mSettings.mReadMessages.toString());
7030
7031 pw.println(" ");
7032 pw.println("Package warning messages:");
7033 File fname = getSettingsProblemFile();
7034 FileInputStream in;
7035 try {
7036 in = new FileInputStream(fname);
7037 int avail = in.available();
7038 byte[] data = new byte[avail];
7039 in.read(data);
7040 pw.println(new String(data));
7041 } catch (FileNotFoundException e) {
7042 } catch (IOException e) {
7043 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007045 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007046
7047 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007048 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007049 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007050 if (packageName != null && !packageName.equals(p.info.packageName)) {
7051 continue;
7052 }
7053 if (!printedSomething) {
7054 if (printedTitle) pw.println(" ");
7055 pw.println("Registered ContentProviders:");
7056 printedSomething = true;
7057 printedTitle = true;
7058 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007059 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007060 pw.println(p.toString());
7061 }
7062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007063 }
7064
7065 static final class BasePermission {
7066 final static int TYPE_NORMAL = 0;
7067 final static int TYPE_BUILTIN = 1;
7068 final static int TYPE_DYNAMIC = 2;
7069
7070 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007071 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007072 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007073 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007074 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007075 PackageParser.Permission perm;
7076 PermissionInfo pendingInfo;
7077 int uid;
7078 int[] gids;
7079
7080 BasePermission(String _name, String _sourcePackage, int _type) {
7081 name = _name;
7082 sourcePackage = _sourcePackage;
7083 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007084 // Default to most conservative protection level.
7085 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7086 }
7087
7088 public String toString() {
7089 return "BasePermission{"
7090 + Integer.toHexString(System.identityHashCode(this))
7091 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 }
7093 }
7094
7095 static class PackageSignatures {
7096 private Signature[] mSignatures;
7097
7098 PackageSignatures(Signature[] sigs) {
7099 assignSignatures(sigs);
7100 }
7101
7102 PackageSignatures() {
7103 }
7104
7105 void writeXml(XmlSerializer serializer, String tagName,
7106 ArrayList<Signature> pastSignatures) throws IOException {
7107 if (mSignatures == null) {
7108 return;
7109 }
7110 serializer.startTag(null, tagName);
7111 serializer.attribute(null, "count",
7112 Integer.toString(mSignatures.length));
7113 for (int i=0; i<mSignatures.length; i++) {
7114 serializer.startTag(null, "cert");
7115 final Signature sig = mSignatures[i];
7116 final int sigHash = sig.hashCode();
7117 final int numPast = pastSignatures.size();
7118 int j;
7119 for (j=0; j<numPast; j++) {
7120 Signature pastSig = pastSignatures.get(j);
7121 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7122 serializer.attribute(null, "index", Integer.toString(j));
7123 break;
7124 }
7125 }
7126 if (j >= numPast) {
7127 pastSignatures.add(sig);
7128 serializer.attribute(null, "index", Integer.toString(numPast));
7129 serializer.attribute(null, "key", sig.toCharsString());
7130 }
7131 serializer.endTag(null, "cert");
7132 }
7133 serializer.endTag(null, tagName);
7134 }
7135
7136 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7137 throws IOException, XmlPullParserException {
7138 String countStr = parser.getAttributeValue(null, "count");
7139 if (countStr == null) {
7140 reportSettingsProblem(Log.WARN,
7141 "Error in package manager settings: <signatures> has"
7142 + " no count at " + parser.getPositionDescription());
7143 XmlUtils.skipCurrentTag(parser);
7144 }
7145 final int count = Integer.parseInt(countStr);
7146 mSignatures = new Signature[count];
7147 int pos = 0;
7148
7149 int outerDepth = parser.getDepth();
7150 int type;
7151 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7152 && (type != XmlPullParser.END_TAG
7153 || parser.getDepth() > outerDepth)) {
7154 if (type == XmlPullParser.END_TAG
7155 || type == XmlPullParser.TEXT) {
7156 continue;
7157 }
7158
7159 String tagName = parser.getName();
7160 if (tagName.equals("cert")) {
7161 if (pos < count) {
7162 String index = parser.getAttributeValue(null, "index");
7163 if (index != null) {
7164 try {
7165 int idx = Integer.parseInt(index);
7166 String key = parser.getAttributeValue(null, "key");
7167 if (key == null) {
7168 if (idx >= 0 && idx < pastSignatures.size()) {
7169 Signature sig = pastSignatures.get(idx);
7170 if (sig != null) {
7171 mSignatures[pos] = pastSignatures.get(idx);
7172 pos++;
7173 } else {
7174 reportSettingsProblem(Log.WARN,
7175 "Error in package manager settings: <cert> "
7176 + "index " + index + " is not defined at "
7177 + parser.getPositionDescription());
7178 }
7179 } else {
7180 reportSettingsProblem(Log.WARN,
7181 "Error in package manager settings: <cert> "
7182 + "index " + index + " is out of bounds at "
7183 + parser.getPositionDescription());
7184 }
7185 } else {
7186 while (pastSignatures.size() <= idx) {
7187 pastSignatures.add(null);
7188 }
7189 Signature sig = new Signature(key);
7190 pastSignatures.set(idx, sig);
7191 mSignatures[pos] = sig;
7192 pos++;
7193 }
7194 } catch (NumberFormatException e) {
7195 reportSettingsProblem(Log.WARN,
7196 "Error in package manager settings: <cert> "
7197 + "index " + index + " is not a number at "
7198 + parser.getPositionDescription());
7199 }
7200 } else {
7201 reportSettingsProblem(Log.WARN,
7202 "Error in package manager settings: <cert> has"
7203 + " no index at " + parser.getPositionDescription());
7204 }
7205 } else {
7206 reportSettingsProblem(Log.WARN,
7207 "Error in package manager settings: too "
7208 + "many <cert> tags, expected " + count
7209 + " at " + parser.getPositionDescription());
7210 }
7211 } else {
7212 reportSettingsProblem(Log.WARN,
7213 "Unknown element under <cert>: "
7214 + parser.getName());
7215 }
7216 XmlUtils.skipCurrentTag(parser);
7217 }
7218
7219 if (pos < count) {
7220 // Should never happen -- there is an error in the written
7221 // settings -- but if it does we don't want to generate
7222 // a bad array.
7223 Signature[] newSigs = new Signature[pos];
7224 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7225 mSignatures = newSigs;
7226 }
7227 }
7228
7229 /**
7230 * If any of the given 'sigs' is contained in the existing signatures,
7231 * then completely replace the current signatures with the ones in
7232 * 'sigs'. This is used for updating an existing package to a newly
7233 * installed version.
7234 */
7235 boolean updateSignatures(Signature[] sigs, boolean update) {
7236 if (mSignatures == null) {
7237 if (update) {
7238 assignSignatures(sigs);
7239 }
7240 return true;
7241 }
7242 if (sigs == null) {
7243 return false;
7244 }
7245
7246 for (int i=0; i<sigs.length; i++) {
7247 Signature sig = sigs[i];
7248 for (int j=0; j<mSignatures.length; j++) {
7249 if (mSignatures[j].equals(sig)) {
7250 if (update) {
7251 assignSignatures(sigs);
7252 }
7253 return true;
7254 }
7255 }
7256 }
7257 return false;
7258 }
7259
7260 /**
7261 * If any of the given 'sigs' is contained in the existing signatures,
7262 * then add in any new signatures found in 'sigs'. This is used for
7263 * including a new package into an existing shared user id.
7264 */
7265 boolean mergeSignatures(Signature[] sigs, boolean update) {
7266 if (mSignatures == null) {
7267 if (update) {
7268 assignSignatures(sigs);
7269 }
7270 return true;
7271 }
7272 if (sigs == null) {
7273 return false;
7274 }
7275
7276 Signature[] added = null;
7277 int addedCount = 0;
7278 boolean haveMatch = false;
7279 for (int i=0; i<sigs.length; i++) {
7280 Signature sig = sigs[i];
7281 boolean found = false;
7282 for (int j=0; j<mSignatures.length; j++) {
7283 if (mSignatures[j].equals(sig)) {
7284 found = true;
7285 haveMatch = true;
7286 break;
7287 }
7288 }
7289
7290 if (!found) {
7291 if (added == null) {
7292 added = new Signature[sigs.length];
7293 }
7294 added[i] = sig;
7295 addedCount++;
7296 }
7297 }
7298
7299 if (!haveMatch) {
7300 // Nothing matched -- reject the new signatures.
7301 return false;
7302 }
7303 if (added == null) {
7304 // Completely matched -- nothing else to do.
7305 return true;
7306 }
7307
7308 // Add additional signatures in.
7309 if (update) {
7310 Signature[] total = new Signature[addedCount+mSignatures.length];
7311 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
7312 int j = mSignatures.length;
7313 for (int i=0; i<added.length; i++) {
7314 if (added[i] != null) {
7315 total[j] = added[i];
7316 j++;
7317 }
7318 }
7319 mSignatures = total;
7320 }
7321 return true;
7322 }
7323
7324 private void assignSignatures(Signature[] sigs) {
7325 if (sigs == null) {
7326 mSignatures = null;
7327 return;
7328 }
7329 mSignatures = new Signature[sigs.length];
7330 for (int i=0; i<sigs.length; i++) {
7331 mSignatures[i] = sigs[i];
7332 }
7333 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007335 @Override
7336 public String toString() {
7337 StringBuffer buf = new StringBuffer(128);
7338 buf.append("PackageSignatures{");
7339 buf.append(Integer.toHexString(System.identityHashCode(this)));
7340 buf.append(" [");
7341 if (mSignatures != null) {
7342 for (int i=0; i<mSignatures.length; i++) {
7343 if (i > 0) buf.append(", ");
7344 buf.append(Integer.toHexString(
7345 System.identityHashCode(mSignatures[i])));
7346 }
7347 }
7348 buf.append("]}");
7349 return buf.toString();
7350 }
7351 }
7352
7353 static class PreferredActivity extends IntentFilter {
7354 final int mMatch;
7355 final String[] mSetPackages;
7356 final String[] mSetClasses;
7357 final String[] mSetComponents;
7358 final ComponentName mActivity;
7359 final String mShortActivity;
7360 String mParseError;
7361
7362 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7363 ComponentName activity) {
7364 super(filter);
7365 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7366 mActivity = activity;
7367 mShortActivity = activity.flattenToShortString();
7368 mParseError = null;
7369 if (set != null) {
7370 final int N = set.length;
7371 String[] myPackages = new String[N];
7372 String[] myClasses = new String[N];
7373 String[] myComponents = new String[N];
7374 for (int i=0; i<N; i++) {
7375 ComponentName cn = set[i];
7376 if (cn == null) {
7377 mSetPackages = null;
7378 mSetClasses = null;
7379 mSetComponents = null;
7380 return;
7381 }
7382 myPackages[i] = cn.getPackageName().intern();
7383 myClasses[i] = cn.getClassName().intern();
7384 myComponents[i] = cn.flattenToShortString().intern();
7385 }
7386 mSetPackages = myPackages;
7387 mSetClasses = myClasses;
7388 mSetComponents = myComponents;
7389 } else {
7390 mSetPackages = null;
7391 mSetClasses = null;
7392 mSetComponents = null;
7393 }
7394 }
7395
7396 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7397 IOException {
7398 mShortActivity = parser.getAttributeValue(null, "name");
7399 mActivity = ComponentName.unflattenFromString(mShortActivity);
7400 if (mActivity == null) {
7401 mParseError = "Bad activity name " + mShortActivity;
7402 }
7403 String matchStr = parser.getAttributeValue(null, "match");
7404 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7405 String setCountStr = parser.getAttributeValue(null, "set");
7406 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7407
7408 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7409 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7410 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7411
7412 int setPos = 0;
7413
7414 int outerDepth = parser.getDepth();
7415 int type;
7416 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7417 && (type != XmlPullParser.END_TAG
7418 || parser.getDepth() > outerDepth)) {
7419 if (type == XmlPullParser.END_TAG
7420 || type == XmlPullParser.TEXT) {
7421 continue;
7422 }
7423
7424 String tagName = parser.getName();
7425 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7426 // + parser.getDepth() + " tag=" + tagName);
7427 if (tagName.equals("set")) {
7428 String name = parser.getAttributeValue(null, "name");
7429 if (name == null) {
7430 if (mParseError == null) {
7431 mParseError = "No name in set tag in preferred activity "
7432 + mShortActivity;
7433 }
7434 } else if (setPos >= setCount) {
7435 if (mParseError == null) {
7436 mParseError = "Too many set tags in preferred activity "
7437 + mShortActivity;
7438 }
7439 } else {
7440 ComponentName cn = ComponentName.unflattenFromString(name);
7441 if (cn == null) {
7442 if (mParseError == null) {
7443 mParseError = "Bad set name " + name + " in preferred activity "
7444 + mShortActivity;
7445 }
7446 } else {
7447 myPackages[setPos] = cn.getPackageName();
7448 myClasses[setPos] = cn.getClassName();
7449 myComponents[setPos] = name;
7450 setPos++;
7451 }
7452 }
7453 XmlUtils.skipCurrentTag(parser);
7454 } else if (tagName.equals("filter")) {
7455 //Log.i(TAG, "Starting to parse filter...");
7456 readFromXml(parser);
7457 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7458 // + parser.getDepth() + " tag=" + parser.getName());
7459 } else {
7460 reportSettingsProblem(Log.WARN,
7461 "Unknown element under <preferred-activities>: "
7462 + parser.getName());
7463 XmlUtils.skipCurrentTag(parser);
7464 }
7465 }
7466
7467 if (setPos != setCount) {
7468 if (mParseError == null) {
7469 mParseError = "Not enough set tags (expected " + setCount
7470 + " but found " + setPos + ") in " + mShortActivity;
7471 }
7472 }
7473
7474 mSetPackages = myPackages;
7475 mSetClasses = myClasses;
7476 mSetComponents = myComponents;
7477 }
7478
7479 public void writeToXml(XmlSerializer serializer) throws IOException {
7480 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7481 serializer.attribute(null, "name", mShortActivity);
7482 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7483 serializer.attribute(null, "set", Integer.toString(NS));
7484 for (int s=0; s<NS; s++) {
7485 serializer.startTag(null, "set");
7486 serializer.attribute(null, "name", mSetComponents[s]);
7487 serializer.endTag(null, "set");
7488 }
7489 serializer.startTag(null, "filter");
7490 super.writeToXml(serializer);
7491 serializer.endTag(null, "filter");
7492 }
7493
7494 boolean sameSet(List<ResolveInfo> query, int priority) {
7495 if (mSetPackages == null) return false;
7496 final int NQ = query.size();
7497 final int NS = mSetPackages.length;
7498 int numMatch = 0;
7499 for (int i=0; i<NQ; i++) {
7500 ResolveInfo ri = query.get(i);
7501 if (ri.priority != priority) continue;
7502 ActivityInfo ai = ri.activityInfo;
7503 boolean good = false;
7504 for (int j=0; j<NS; j++) {
7505 if (mSetPackages[j].equals(ai.packageName)
7506 && mSetClasses[j].equals(ai.name)) {
7507 numMatch++;
7508 good = true;
7509 break;
7510 }
7511 }
7512 if (!good) return false;
7513 }
7514 return numMatch == NS;
7515 }
7516 }
7517
7518 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007519 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007521 HashSet<String> grantedPermissions = new HashSet<String>();
7522 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007524 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007525 setFlags(pkgFlags);
7526 }
7527
7528 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007529 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007530 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08007531 (pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) |
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08007532 (pkgFlags & ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 }
7534 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536 /**
7537 * Settings base class for pending and resolved classes.
7538 */
7539 static class PackageSettingBase extends GrantedPermissions {
7540 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007541 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007542 File codePath;
7543 String codePathString;
7544 File resourcePath;
7545 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007546 private long timeStamp;
7547 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007548 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007549
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007550 boolean uidError;
7551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 PackageSignatures signatures = new PackageSignatures();
7553
7554 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007555 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007557 /* Explicitly disabled components */
7558 HashSet<String> disabledComponents = new HashSet<String>(0);
7559 /* Explicitly enabled components */
7560 HashSet<String> enabledComponents = new HashSet<String>(0);
7561 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7562 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007563
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007564 PackageSettingBase origPackage;
7565
Jacek Surazski65e13172009-04-28 15:26:38 +02007566 /* package name of the app that installed this package */
7567 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007568
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007569 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007570 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007571 super(pkgFlags);
7572 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007573 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007574 init(codePath, resourcePath, pVersionCode);
7575 }
7576
7577 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007578 this.codePath = codePath;
7579 this.codePathString = codePath.toString();
7580 this.resourcePath = resourcePath;
7581 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007582 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007584
Jacek Surazski65e13172009-04-28 15:26:38 +02007585 public void setInstallerPackageName(String packageName) {
7586 installerPackageName = packageName;
7587 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007588
Jacek Surazski65e13172009-04-28 15:26:38 +02007589 String getInstallerPackageName() {
7590 return installerPackageName;
7591 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007593 public void setInstallStatus(int newStatus) {
7594 installStatus = newStatus;
7595 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007597 public int getInstallStatus() {
7598 return installStatus;
7599 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007601 public void setTimeStamp(long newStamp) {
7602 if (newStamp != timeStamp) {
7603 timeStamp = newStamp;
7604 timeStampString = Long.toString(newStamp);
7605 }
7606 }
7607
7608 public void setTimeStamp(long newStamp, String newStampStr) {
7609 timeStamp = newStamp;
7610 timeStampString = newStampStr;
7611 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613 public long getTimeStamp() {
7614 return timeStamp;
7615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007617 public String getTimeStampStr() {
7618 return timeStampString;
7619 }
7620
7621 public void copyFrom(PackageSettingBase base) {
7622 grantedPermissions = base.grantedPermissions;
7623 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007625 timeStamp = base.timeStamp;
7626 timeStampString = base.timeStampString;
7627 signatures = base.signatures;
7628 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007629 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007630 disabledComponents = base.disabledComponents;
7631 enabledComponents = base.enabledComponents;
7632 enabled = base.enabled;
7633 installStatus = base.installStatus;
7634 }
7635
7636 void enableComponentLP(String componentClassName) {
7637 disabledComponents.remove(componentClassName);
7638 enabledComponents.add(componentClassName);
7639 }
7640
7641 void disableComponentLP(String componentClassName) {
7642 enabledComponents.remove(componentClassName);
7643 disabledComponents.add(componentClassName);
7644 }
7645
7646 void restoreComponentLP(String componentClassName) {
7647 enabledComponents.remove(componentClassName);
7648 disabledComponents.remove(componentClassName);
7649 }
7650
7651 int currentEnabledStateLP(String componentName) {
7652 if (enabledComponents.contains(componentName)) {
7653 return COMPONENT_ENABLED_STATE_ENABLED;
7654 } else if (disabledComponents.contains(componentName)) {
7655 return COMPONENT_ENABLED_STATE_DISABLED;
7656 } else {
7657 return COMPONENT_ENABLED_STATE_DEFAULT;
7658 }
7659 }
7660 }
7661
7662 /**
7663 * Settings data for a particular package we know about.
7664 */
7665 static final class PackageSetting extends PackageSettingBase {
7666 int userId;
7667 PackageParser.Package pkg;
7668 SharedUserSetting sharedUser;
7669
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007670 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007671 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007672 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 @Override
7676 public String toString() {
7677 return "PackageSetting{"
7678 + Integer.toHexString(System.identityHashCode(this))
7679 + " " + name + "/" + userId + "}";
7680 }
7681 }
7682
7683 /**
7684 * Settings data for a particular shared user ID we know about.
7685 */
7686 static final class SharedUserSetting extends GrantedPermissions {
7687 final String name;
7688 int userId;
7689 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7690 final PackageSignatures signatures = new PackageSignatures();
7691
7692 SharedUserSetting(String _name, int _pkgFlags) {
7693 super(_pkgFlags);
7694 name = _name;
7695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007697 @Override
7698 public String toString() {
7699 return "SharedUserSetting{"
7700 + Integer.toHexString(System.identityHashCode(this))
7701 + " " + name + "/" + userId + "}";
7702 }
7703 }
7704
7705 /**
7706 * Holds information about dynamic settings.
7707 */
7708 private static final class Settings {
7709 private final File mSettingsFilename;
7710 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007711 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 private final HashMap<String, PackageSetting> mPackages =
7713 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 // List of replaced system applications
7715 final HashMap<String, PackageSetting> mDisabledSysPackages =
7716 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 // The user's preferred activities associated with particular intent
7719 // filters.
7720 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7721 new IntentResolver<PreferredActivity, PreferredActivity>() {
7722 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007723 protected String packageForFilter(PreferredActivity filter) {
7724 return filter.mActivity.getPackageName();
7725 }
7726 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007727 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007728 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007729 out.print(prefix); out.print(
7730 Integer.toHexString(System.identityHashCode(filter)));
7731 out.print(' ');
7732 out.print(filter.mActivity.flattenToShortString());
7733 out.print(" match=0x");
7734 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007736 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007738 out.print(prefix); out.print(" ");
7739 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 }
7741 }
7742 }
7743 };
7744 private final HashMap<String, SharedUserSetting> mSharedUsers =
7745 new HashMap<String, SharedUserSetting>();
7746 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7747 private final SparseArray<Object> mOtherUserIds =
7748 new SparseArray<Object>();
7749
7750 // For reading/writing settings file.
7751 private final ArrayList<Signature> mPastSignatures =
7752 new ArrayList<Signature>();
7753
7754 // Mapping from permission names to info about them.
7755 final HashMap<String, BasePermission> mPermissions =
7756 new HashMap<String, BasePermission>();
7757
7758 // Mapping from permission tree names to info about them.
7759 final HashMap<String, BasePermission> mPermissionTrees =
7760 new HashMap<String, BasePermission>();
7761
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007762 // Packages that have been uninstalled and still need their external
7763 // storage data deleted.
7764 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7765
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007766 // Packages that have been renamed since they were first installed.
7767 // Keys are the new names of the packages, values are the original
7768 // names. The packages appear everwhere else under their original
7769 // names.
7770 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007772 private final StringBuilder mReadMessages = new StringBuilder();
7773
7774 private static final class PendingPackage extends PackageSettingBase {
7775 final int sharedId;
7776
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007777 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007778 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007779 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 this.sharedId = sharedId;
7781 }
7782 }
7783 private final ArrayList<PendingPackage> mPendingPackages
7784 = new ArrayList<PendingPackage>();
7785
7786 Settings() {
7787 File dataDir = Environment.getDataDirectory();
7788 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007789 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7790 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007792 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 FileUtils.setPermissions(systemDir.toString(),
7794 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7795 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7796 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007797 FileUtils.setPermissions(systemSecureDir.toString(),
7798 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7799 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7800 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 mSettingsFilename = new File(systemDir, "packages.xml");
7802 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007803 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007804 }
7805
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007806 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007807 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007808 int pkgFlags, boolean create, boolean add) {
7809 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007810 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007811 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007812 return p;
7813 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007814
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007815 PackageSetting peekPackageLP(String name) {
7816 return mPackages.get(name);
7817 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 PackageSetting p = mPackages.get(name);
7819 if (p != null && p.codePath.getPath().equals(codePath)) {
7820 return p;
7821 }
7822 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007823 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 void setInstallStatus(String pkgName, int status) {
7827 PackageSetting p = mPackages.get(pkgName);
7828 if(p != null) {
7829 if(p.getInstallStatus() != status) {
7830 p.setInstallStatus(status);
7831 }
7832 }
7833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007834
Jacek Surazski65e13172009-04-28 15:26:38 +02007835 void setInstallerPackageName(String pkgName,
7836 String installerPkgName) {
7837 PackageSetting p = mPackages.get(pkgName);
7838 if(p != null) {
7839 p.setInstallerPackageName(installerPkgName);
7840 }
7841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007842
Jacek Surazski65e13172009-04-28 15:26:38 +02007843 String getInstallerPackageName(String pkgName) {
7844 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007845 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007846 }
7847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 int getInstallStatus(String pkgName) {
7849 PackageSetting p = mPackages.get(pkgName);
7850 if(p != null) {
7851 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007853 return -1;
7854 }
7855
7856 SharedUserSetting getSharedUserLP(String name,
7857 int pkgFlags, boolean create) {
7858 SharedUserSetting s = mSharedUsers.get(name);
7859 if (s == null) {
7860 if (!create) {
7861 return null;
7862 }
7863 s = new SharedUserSetting(name, pkgFlags);
7864 if (MULTIPLE_APPLICATION_UIDS) {
7865 s.userId = newUserIdLP(s);
7866 } else {
7867 s.userId = FIRST_APPLICATION_UID;
7868 }
7869 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7870 // < 0 means we couldn't assign a userid; fall out and return
7871 // s, which is currently null
7872 if (s.userId >= 0) {
7873 mSharedUsers.put(name, s);
7874 }
7875 }
7876
7877 return s;
7878 }
7879
7880 int disableSystemPackageLP(String name) {
7881 PackageSetting p = mPackages.get(name);
7882 if(p == null) {
7883 Log.w(TAG, "Package:"+name+" is not an installed package");
7884 return -1;
7885 }
7886 PackageSetting dp = mDisabledSysPackages.get(name);
7887 // always make sure the system package code and resource paths dont change
7888 if(dp == null) {
7889 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7890 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7891 }
7892 mDisabledSysPackages.put(name, p);
7893 }
7894 return removePackageLP(name);
7895 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007897 PackageSetting enableSystemPackageLP(String name) {
7898 PackageSetting p = mDisabledSysPackages.get(name);
7899 if(p == null) {
7900 Log.w(TAG, "Package:"+name+" is not disabled");
7901 return null;
7902 }
7903 // Reset flag in ApplicationInfo object
7904 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7905 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7906 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007907 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007908 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 mDisabledSysPackages.remove(name);
7910 return ret;
7911 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007912
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007913 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007914 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007915 PackageSetting p = mPackages.get(name);
7916 if (p != null) {
7917 if (p.userId == uid) {
7918 return p;
7919 }
7920 reportSettingsProblem(Log.ERROR,
7921 "Adding duplicate package, keeping first: " + name);
7922 return null;
7923 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007924 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007925 p.userId = uid;
7926 if (addUserIdLP(uid, p, name)) {
7927 mPackages.put(name, p);
7928 return p;
7929 }
7930 return null;
7931 }
7932
7933 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7934 SharedUserSetting s = mSharedUsers.get(name);
7935 if (s != null) {
7936 if (s.userId == uid) {
7937 return s;
7938 }
7939 reportSettingsProblem(Log.ERROR,
7940 "Adding duplicate shared user, keeping first: " + name);
7941 return null;
7942 }
7943 s = new SharedUserSetting(name, pkgFlags);
7944 s.userId = uid;
7945 if (addUserIdLP(uid, s, name)) {
7946 mSharedUsers.put(name, s);
7947 return s;
7948 }
7949 return null;
7950 }
7951
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007952 // Transfer ownership of permissions from one package to another.
7953 private void transferPermissions(String origPkg, String newPkg) {
7954 // Transfer ownership of permissions to the new package.
7955 for (int i=0; i<2; i++) {
7956 HashMap<String, BasePermission> permissions =
7957 i == 0 ? mPermissionTrees : mPermissions;
7958 for (BasePermission bp : permissions.values()) {
7959 if (origPkg.equals(bp.sourcePackage)) {
7960 if (DEBUG_UPGRADE) Log.v(TAG,
7961 "Moving permission " + bp.name
7962 + " from pkg " + bp.sourcePackage
7963 + " to " + newPkg);
7964 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007965 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007966 bp.perm = null;
7967 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007968 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007969 }
7970 bp.uid = 0;
7971 bp.gids = null;
7972 }
7973 }
7974 }
7975 }
7976
7977 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007978 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007979 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 PackageSetting p = mPackages.get(name);
7981 if (p != null) {
7982 if (!p.codePath.equals(codePath)) {
7983 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007984 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007985 // This is an updated system app with versions in both system
7986 // and data partition. Just let the most recent version
7987 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007988 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007989 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007990 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007991 // Just a change in the code path is not an issue, but
7992 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007993 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007994 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007995 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007996 }
7997 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 reportSettingsProblem(Log.WARN,
7999 "Package " + name + " shared user changed from "
8000 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8001 + " to "
8002 + (sharedUser != null ? sharedUser.name : "<nothing>")
8003 + "; replacing with new");
8004 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008005 } else {
8006 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8007 // If what we are scanning is a system package, then
8008 // make it so, regardless of whether it was previously
8009 // installed only in the data partition.
8010 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008012 }
8013 }
8014 if (p == null) {
8015 // Create a new PackageSettings entry. this can end up here because
8016 // of code path mismatch or user id mismatch of an updated system partition
8017 if (!create) {
8018 return null;
8019 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008020 if (origPackage != null) {
8021 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008022 p = new PackageSetting(origPackage.name, name, codePath,
8023 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008024 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8025 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008026 // Note that we will retain the new package's signature so
8027 // that we can keep its data.
8028 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008029 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008030 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008031 p.sharedUser = origPackage.sharedUser;
8032 p.userId = origPackage.userId;
8033 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008034 mRenamedPackages.put(name, origPackage.name);
8035 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008036 // Update new package state.
8037 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008038 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008039 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008040 p.setTimeStamp(codePath.lastModified());
8041 p.sharedUser = sharedUser;
8042 if (sharedUser != null) {
8043 p.userId = sharedUser.userId;
8044 } else if (MULTIPLE_APPLICATION_UIDS) {
8045 // Clone the setting here for disabled system packages
8046 PackageSetting dis = mDisabledSysPackages.get(name);
8047 if (dis != null) {
8048 // For disabled packages a new setting is created
8049 // from the existing user id. This still has to be
8050 // added to list of user id's
8051 // Copy signatures from previous setting
8052 if (dis.signatures.mSignatures != null) {
8053 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8054 }
8055 p.userId = dis.userId;
8056 // Clone permissions
8057 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008058 // Clone component info
8059 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8060 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8061 // Add new setting to list of user ids
8062 addUserIdLP(p.userId, p, name);
8063 } else {
8064 // Assign new user id
8065 p.userId = newUserIdLP(p);
8066 }
8067 } else {
8068 p.userId = FIRST_APPLICATION_UID;
8069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 }
8071 if (p.userId < 0) {
8072 reportSettingsProblem(Log.WARN,
8073 "Package " + name + " could not be assigned a valid uid");
8074 return null;
8075 }
8076 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008077 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008078 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008079 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008080 }
8081 }
8082 return p;
8083 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008084
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008085 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008086 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008087 String codePath = pkg.applicationInfo.sourceDir;
8088 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008089 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008090 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008091 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008092 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008093 p.codePath = new File(codePath);
8094 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008095 }
8096 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008097 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008098 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008099 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008100 p.resourcePath = new File(resourcePath);
8101 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008102 }
8103 // Update version code if needed
8104 if (pkg.mVersionCode != p.versionCode) {
8105 p.versionCode = pkg.mVersionCode;
8106 }
8107 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8108 }
8109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 // Utility method that adds a PackageSetting to mPackages and
8111 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008112 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008113 SharedUserSetting sharedUser) {
8114 mPackages.put(name, p);
8115 if (sharedUser != null) {
8116 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8117 reportSettingsProblem(Log.ERROR,
8118 "Package " + p.name + " was user "
8119 + p.sharedUser + " but is now " + sharedUser
8120 + "; I am not changing its files so it will probably fail!");
8121 p.sharedUser.packages.remove(p);
8122 } else if (p.userId != sharedUser.userId) {
8123 reportSettingsProblem(Log.ERROR,
8124 "Package " + p.name + " was user id " + p.userId
8125 + " but is now user " + sharedUser
8126 + " with id " + sharedUser.userId
8127 + "; I am not changing its files so it will probably fail!");
8128 }
8129
8130 sharedUser.packages.add(p);
8131 p.sharedUser = sharedUser;
8132 p.userId = sharedUser.userId;
8133 }
8134 }
8135
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008136 /*
8137 * Update the shared user setting when a package using
8138 * specifying the shared user id is removed. The gids
8139 * associated with each permission of the deleted package
8140 * are removed from the shared user's gid list only if its
8141 * not in use by other permissions of packages in the
8142 * shared user setting.
8143 */
8144 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008145 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008146 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008147 return;
8148 }
8149 // No sharedUserId
8150 if (deletedPs.sharedUser == null) {
8151 return;
8152 }
8153 SharedUserSetting sus = deletedPs.sharedUser;
8154 // Update permissions
8155 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8156 boolean used = false;
8157 if (!sus.grantedPermissions.contains (eachPerm)) {
8158 continue;
8159 }
8160 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008161 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008162 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008163 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008164 used = true;
8165 break;
8166 }
8167 }
8168 if (!used) {
8169 // can safely delete this permission from list
8170 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008171 }
8172 }
8173 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008174 int newGids[] = globalGids;
8175 for (String eachPerm : sus.grantedPermissions) {
8176 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008177 if (bp != null) {
8178 newGids = appendInts(newGids, bp.gids);
8179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008180 }
8181 sus.gids = newGids;
8182 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008184 private int removePackageLP(String name) {
8185 PackageSetting p = mPackages.get(name);
8186 if (p != null) {
8187 mPackages.remove(name);
8188 if (p.sharedUser != null) {
8189 p.sharedUser.packages.remove(p);
8190 if (p.sharedUser.packages.size() == 0) {
8191 mSharedUsers.remove(p.sharedUser.name);
8192 removeUserIdLP(p.sharedUser.userId);
8193 return p.sharedUser.userId;
8194 }
8195 } else {
8196 removeUserIdLP(p.userId);
8197 return p.userId;
8198 }
8199 }
8200 return -1;
8201 }
8202
8203 private boolean addUserIdLP(int uid, Object obj, Object name) {
8204 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8205 return false;
8206 }
8207
8208 if (uid >= FIRST_APPLICATION_UID) {
8209 int N = mUserIds.size();
8210 final int index = uid - FIRST_APPLICATION_UID;
8211 while (index >= N) {
8212 mUserIds.add(null);
8213 N++;
8214 }
8215 if (mUserIds.get(index) != null) {
8216 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008217 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008218 + " name=" + name);
8219 return false;
8220 }
8221 mUserIds.set(index, obj);
8222 } else {
8223 if (mOtherUserIds.get(uid) != null) {
8224 reportSettingsProblem(Log.ERROR,
8225 "Adding duplicate shared id: " + uid
8226 + " name=" + name);
8227 return false;
8228 }
8229 mOtherUserIds.put(uid, obj);
8230 }
8231 return true;
8232 }
8233
8234 public Object getUserIdLP(int uid) {
8235 if (uid >= FIRST_APPLICATION_UID) {
8236 int N = mUserIds.size();
8237 final int index = uid - FIRST_APPLICATION_UID;
8238 return index < N ? mUserIds.get(index) : null;
8239 } else {
8240 return mOtherUserIds.get(uid);
8241 }
8242 }
8243
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008244 private Set<String> findPackagesWithFlag(int flag) {
8245 Set<String> ret = new HashSet<String>();
8246 for (PackageSetting ps : mPackages.values()) {
8247 // Has to match atleast all the flag bits set on flag
8248 if ((ps.pkgFlags & flag) == flag) {
8249 ret.add(ps.name);
8250 }
8251 }
8252 return ret;
8253 }
8254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008255 private void removeUserIdLP(int uid) {
8256 if (uid >= FIRST_APPLICATION_UID) {
8257 int N = mUserIds.size();
8258 final int index = uid - FIRST_APPLICATION_UID;
8259 if (index < N) mUserIds.set(index, null);
8260 } else {
8261 mOtherUserIds.remove(uid);
8262 }
8263 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008265 void writeLP() {
8266 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8267
8268 // Keep the old settings around until we know the new ones have
8269 // been successfully written.
8270 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008271 // Presence of backup settings file indicates that we failed
8272 // to persist settings earlier. So preserve the older
8273 // backup for future reference since the current settings
8274 // might have been corrupted.
8275 if (!mBackupSettingsFilename.exists()) {
8276 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008277 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008278 return;
8279 }
8280 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008281 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008282 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 }
8285
8286 mPastSignatures.clear();
8287
8288 try {
8289 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8290
8291 //XmlSerializer serializer = XmlUtils.serializerInstance();
8292 XmlSerializer serializer = new FastXmlSerializer();
8293 serializer.setOutput(str, "utf-8");
8294 serializer.startDocument(null, true);
8295 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8296
8297 serializer.startTag(null, "packages");
8298
8299 serializer.startTag(null, "permission-trees");
8300 for (BasePermission bp : mPermissionTrees.values()) {
8301 writePermission(serializer, bp);
8302 }
8303 serializer.endTag(null, "permission-trees");
8304
8305 serializer.startTag(null, "permissions");
8306 for (BasePermission bp : mPermissions.values()) {
8307 writePermission(serializer, bp);
8308 }
8309 serializer.endTag(null, "permissions");
8310
8311 for (PackageSetting pkg : mPackages.values()) {
8312 writePackage(serializer, pkg);
8313 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008315 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8316 writeDisabledSysPackage(serializer, pkg);
8317 }
8318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008319 serializer.startTag(null, "preferred-activities");
8320 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8321 serializer.startTag(null, "item");
8322 pa.writeToXml(serializer);
8323 serializer.endTag(null, "item");
8324 }
8325 serializer.endTag(null, "preferred-activities");
8326
8327 for (SharedUserSetting usr : mSharedUsers.values()) {
8328 serializer.startTag(null, "shared-user");
8329 serializer.attribute(null, "name", usr.name);
8330 serializer.attribute(null, "userId",
8331 Integer.toString(usr.userId));
8332 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8333 serializer.startTag(null, "perms");
8334 for (String name : usr.grantedPermissions) {
8335 serializer.startTag(null, "item");
8336 serializer.attribute(null, "name", name);
8337 serializer.endTag(null, "item");
8338 }
8339 serializer.endTag(null, "perms");
8340 serializer.endTag(null, "shared-user");
8341 }
8342
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008343 if (mPackagesToBeCleaned.size() > 0) {
8344 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8345 serializer.startTag(null, "cleaning-package");
8346 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8347 serializer.endTag(null, "cleaning-package");
8348 }
8349 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008350
8351 if (mRenamedPackages.size() > 0) {
8352 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8353 serializer.startTag(null, "renamed-package");
8354 serializer.attribute(null, "new", e.getKey());
8355 serializer.attribute(null, "old", e.getValue());
8356 serializer.endTag(null, "renamed-package");
8357 }
8358 }
8359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008360 serializer.endTag(null, "packages");
8361
8362 serializer.endDocument();
8363
8364 str.flush();
8365 str.close();
8366
8367 // New settings successfully written, old ones are no longer
8368 // needed.
8369 mBackupSettingsFilename.delete();
8370 FileUtils.setPermissions(mSettingsFilename.toString(),
8371 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8372 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8373 |FileUtils.S_IROTH,
8374 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008375
8376 // Write package list file now, use a JournaledFile.
8377 //
8378 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8379 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8380
8381 str = new FileOutputStream(journal.chooseForWrite());
8382 try {
8383 StringBuilder sb = new StringBuilder();
8384 for (PackageSetting pkg : mPackages.values()) {
8385 ApplicationInfo ai = pkg.pkg.applicationInfo;
8386 String dataPath = ai.dataDir;
8387 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8388
8389 // Avoid any application that has a space in its path
8390 // or that is handled by the system.
8391 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8392 continue;
8393
8394 // we store on each line the following information for now:
8395 //
8396 // pkgName - package name
8397 // userId - application-specific user id
8398 // debugFlag - 0 or 1 if the package is debuggable.
8399 // dataPath - path to package's data path
8400 //
8401 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8402 //
8403 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8404 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8405 // system/core/run-as/run-as.c
8406 //
8407 sb.setLength(0);
8408 sb.append(ai.packageName);
8409 sb.append(" ");
8410 sb.append((int)ai.uid);
8411 sb.append(isDebug ? " 1 " : " 0 ");
8412 sb.append(dataPath);
8413 sb.append("\n");
8414 str.write(sb.toString().getBytes());
8415 }
8416 str.flush();
8417 str.close();
8418 journal.commit();
8419 }
8420 catch (Exception e) {
8421 journal.rollback();
8422 }
8423
8424 FileUtils.setPermissions(mPackageListFilename.toString(),
8425 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8426 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8427 |FileUtils.S_IROTH,
8428 -1, -1);
8429
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008430 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008431
8432 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008433 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 -08008434 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008435 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 -08008436 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008437 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008438 if (mSettingsFilename.exists()) {
8439 if (!mSettingsFilename.delete()) {
8440 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8441 }
8442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008443 //Debug.stopMethodTracing();
8444 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008445
8446 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008447 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008448 serializer.startTag(null, "updated-package");
8449 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008450 if (pkg.realName != null) {
8451 serializer.attribute(null, "realName", pkg.realName);
8452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008453 serializer.attribute(null, "codePath", pkg.codePathString);
8454 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008455 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008456 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8457 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8458 }
8459 if (pkg.sharedUser == null) {
8460 serializer.attribute(null, "userId",
8461 Integer.toString(pkg.userId));
8462 } else {
8463 serializer.attribute(null, "sharedUserId",
8464 Integer.toString(pkg.userId));
8465 }
8466 serializer.startTag(null, "perms");
8467 if (pkg.sharedUser == null) {
8468 // If this is a shared user, the permissions will
8469 // be written there. We still need to write an
8470 // empty permissions list so permissionsFixed will
8471 // be set.
8472 for (final String name : pkg.grantedPermissions) {
8473 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008474 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 // We only need to write signature or system permissions but this wont
8476 // match the semantics of grantedPermissions. So write all permissions.
8477 serializer.startTag(null, "item");
8478 serializer.attribute(null, "name", name);
8479 serializer.endTag(null, "item");
8480 }
8481 }
8482 }
8483 serializer.endTag(null, "perms");
8484 serializer.endTag(null, "updated-package");
8485 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008486
8487 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008488 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008489 serializer.startTag(null, "package");
8490 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008491 if (pkg.realName != null) {
8492 serializer.attribute(null, "realName", pkg.realName);
8493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494 serializer.attribute(null, "codePath", pkg.codePathString);
8495 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8496 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8497 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008498 serializer.attribute(null, "flags",
8499 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008500 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008501 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502 if (pkg.sharedUser == null) {
8503 serializer.attribute(null, "userId",
8504 Integer.toString(pkg.userId));
8505 } else {
8506 serializer.attribute(null, "sharedUserId",
8507 Integer.toString(pkg.userId));
8508 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008509 if (pkg.uidError) {
8510 serializer.attribute(null, "uidError", "true");
8511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008512 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8513 serializer.attribute(null, "enabled",
8514 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8515 ? "true" : "false");
8516 }
8517 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8518 serializer.attribute(null, "installStatus", "false");
8519 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008520 if (pkg.installerPackageName != null) {
8521 serializer.attribute(null, "installer", pkg.installerPackageName);
8522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008523 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8524 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8525 serializer.startTag(null, "perms");
8526 if (pkg.sharedUser == null) {
8527 // If this is a shared user, the permissions will
8528 // be written there. We still need to write an
8529 // empty permissions list so permissionsFixed will
8530 // be set.
8531 for (final String name : pkg.grantedPermissions) {
8532 serializer.startTag(null, "item");
8533 serializer.attribute(null, "name", name);
8534 serializer.endTag(null, "item");
8535 }
8536 }
8537 serializer.endTag(null, "perms");
8538 }
8539 if (pkg.disabledComponents.size() > 0) {
8540 serializer.startTag(null, "disabled-components");
8541 for (final String name : pkg.disabledComponents) {
8542 serializer.startTag(null, "item");
8543 serializer.attribute(null, "name", name);
8544 serializer.endTag(null, "item");
8545 }
8546 serializer.endTag(null, "disabled-components");
8547 }
8548 if (pkg.enabledComponents.size() > 0) {
8549 serializer.startTag(null, "enabled-components");
8550 for (final String name : pkg.enabledComponents) {
8551 serializer.startTag(null, "item");
8552 serializer.attribute(null, "name", name);
8553 serializer.endTag(null, "item");
8554 }
8555 serializer.endTag(null, "enabled-components");
8556 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008558 serializer.endTag(null, "package");
8559 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008561 void writePermission(XmlSerializer serializer, BasePermission bp)
8562 throws XmlPullParserException, java.io.IOException {
8563 if (bp.type != BasePermission.TYPE_BUILTIN
8564 && bp.sourcePackage != null) {
8565 serializer.startTag(null, "item");
8566 serializer.attribute(null, "name", bp.name);
8567 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008568 if (bp.protectionLevel !=
8569 PermissionInfo.PROTECTION_NORMAL) {
8570 serializer.attribute(null, "protection",
8571 Integer.toString(bp.protectionLevel));
8572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008573 if (DEBUG_SETTINGS) Log.v(TAG,
8574 "Writing perm: name=" + bp.name + " type=" + bp.type);
8575 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8576 PermissionInfo pi = bp.perm != null ? bp.perm.info
8577 : bp.pendingInfo;
8578 if (pi != null) {
8579 serializer.attribute(null, "type", "dynamic");
8580 if (pi.icon != 0) {
8581 serializer.attribute(null, "icon",
8582 Integer.toString(pi.icon));
8583 }
8584 if (pi.nonLocalizedLabel != null) {
8585 serializer.attribute(null, "label",
8586 pi.nonLocalizedLabel.toString());
8587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008588 }
8589 }
8590 serializer.endTag(null, "item");
8591 }
8592 }
8593
8594 String getReadMessagesLP() {
8595 return mReadMessages.toString();
8596 }
8597
Oscar Montemayora8529f62009-11-18 10:14:20 -08008598 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008599 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8600 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008601 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008602 while(its.hasNext()) {
8603 String key = its.next();
8604 PackageSetting ps = mPackages.get(key);
8605 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008606 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008607 }
8608 }
8609 return ret;
8610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612 boolean readLP() {
8613 FileInputStream str = null;
8614 if (mBackupSettingsFilename.exists()) {
8615 try {
8616 str = new FileInputStream(mBackupSettingsFilename);
8617 mReadMessages.append("Reading from backup settings file\n");
8618 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008619 if (mSettingsFilename.exists()) {
8620 // If both the backup and settings file exist, we
8621 // ignore the settings since it might have been
8622 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008623 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008624 mSettingsFilename.delete();
8625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008626 } catch (java.io.IOException e) {
8627 // We'll try for the normal settings file.
8628 }
8629 }
8630
8631 mPastSignatures.clear();
8632
8633 try {
8634 if (str == null) {
8635 if (!mSettingsFilename.exists()) {
8636 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008637 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008638 return false;
8639 }
8640 str = new FileInputStream(mSettingsFilename);
8641 }
8642 XmlPullParser parser = Xml.newPullParser();
8643 parser.setInput(str, null);
8644
8645 int type;
8646 while ((type=parser.next()) != XmlPullParser.START_TAG
8647 && type != XmlPullParser.END_DOCUMENT) {
8648 ;
8649 }
8650
8651 if (type != XmlPullParser.START_TAG) {
8652 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008653 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008654 return false;
8655 }
8656
8657 int outerDepth = parser.getDepth();
8658 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8659 && (type != XmlPullParser.END_TAG
8660 || parser.getDepth() > outerDepth)) {
8661 if (type == XmlPullParser.END_TAG
8662 || type == XmlPullParser.TEXT) {
8663 continue;
8664 }
8665
8666 String tagName = parser.getName();
8667 if (tagName.equals("package")) {
8668 readPackageLP(parser);
8669 } else if (tagName.equals("permissions")) {
8670 readPermissionsLP(mPermissions, parser);
8671 } else if (tagName.equals("permission-trees")) {
8672 readPermissionsLP(mPermissionTrees, parser);
8673 } else if (tagName.equals("shared-user")) {
8674 readSharedUserLP(parser);
8675 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008676 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008677 } else if (tagName.equals("preferred-activities")) {
8678 readPreferredActivitiesLP(parser);
8679 } else if(tagName.equals("updated-package")) {
8680 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008681 } else if (tagName.equals("cleaning-package")) {
8682 String name = parser.getAttributeValue(null, "name");
8683 if (name != null) {
8684 mPackagesToBeCleaned.add(name);
8685 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008686 } else if (tagName.equals("renamed-package")) {
8687 String nname = parser.getAttributeValue(null, "new");
8688 String oname = parser.getAttributeValue(null, "old");
8689 if (nname != null && oname != null) {
8690 mRenamedPackages.put(nname, oname);
8691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008692 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008693 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008694 + parser.getName());
8695 XmlUtils.skipCurrentTag(parser);
8696 }
8697 }
8698
8699 str.close();
8700
8701 } catch(XmlPullParserException e) {
8702 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008703 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008704
8705 } catch(java.io.IOException e) {
8706 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008707 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008708
8709 }
8710
8711 int N = mPendingPackages.size();
8712 for (int i=0; i<N; i++) {
8713 final PendingPackage pp = mPendingPackages.get(i);
8714 Object idObj = getUserIdLP(pp.sharedId);
8715 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008716 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008717 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008718 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008719 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008720 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008721 + pp.name);
8722 continue;
8723 }
8724 p.copyFrom(pp);
8725 } else if (idObj != null) {
8726 String msg = "Bad package setting: package " + pp.name
8727 + " has shared uid " + pp.sharedId
8728 + " that is not a shared uid\n";
8729 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008730 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008731 } else {
8732 String msg = "Bad package setting: package " + pp.name
8733 + " has shared uid " + pp.sharedId
8734 + " that is not defined\n";
8735 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008736 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008737 }
8738 }
8739 mPendingPackages.clear();
8740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008741 mReadMessages.append("Read completed successfully: "
8742 + mPackages.size() + " packages, "
8743 + mSharedUsers.size() + " shared uids\n");
8744
8745 return true;
8746 }
8747
8748 private int readInt(XmlPullParser parser, String ns, String name,
8749 int defValue) {
8750 String v = parser.getAttributeValue(ns, name);
8751 try {
8752 if (v == null) {
8753 return defValue;
8754 }
8755 return Integer.parseInt(v);
8756 } catch (NumberFormatException e) {
8757 reportSettingsProblem(Log.WARN,
8758 "Error in package manager settings: attribute " +
8759 name + " has bad integer value " + v + " at "
8760 + parser.getPositionDescription());
8761 }
8762 return defValue;
8763 }
8764
8765 private void readPermissionsLP(HashMap<String, BasePermission> out,
8766 XmlPullParser parser)
8767 throws IOException, XmlPullParserException {
8768 int outerDepth = parser.getDepth();
8769 int type;
8770 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8771 && (type != XmlPullParser.END_TAG
8772 || parser.getDepth() > outerDepth)) {
8773 if (type == XmlPullParser.END_TAG
8774 || type == XmlPullParser.TEXT) {
8775 continue;
8776 }
8777
8778 String tagName = parser.getName();
8779 if (tagName.equals("item")) {
8780 String name = parser.getAttributeValue(null, "name");
8781 String sourcePackage = parser.getAttributeValue(null, "package");
8782 String ptype = parser.getAttributeValue(null, "type");
8783 if (name != null && sourcePackage != null) {
8784 boolean dynamic = "dynamic".equals(ptype);
8785 BasePermission bp = new BasePermission(name, sourcePackage,
8786 dynamic
8787 ? BasePermission.TYPE_DYNAMIC
8788 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008789 bp.protectionLevel = readInt(parser, null, "protection",
8790 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008791 if (dynamic) {
8792 PermissionInfo pi = new PermissionInfo();
8793 pi.packageName = sourcePackage.intern();
8794 pi.name = name.intern();
8795 pi.icon = readInt(parser, null, "icon", 0);
8796 pi.nonLocalizedLabel = parser.getAttributeValue(
8797 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008798 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008799 bp.pendingInfo = pi;
8800 }
8801 out.put(bp.name, bp);
8802 } else {
8803 reportSettingsProblem(Log.WARN,
8804 "Error in package manager settings: permissions has"
8805 + " no name at " + parser.getPositionDescription());
8806 }
8807 } else {
8808 reportSettingsProblem(Log.WARN,
8809 "Unknown element reading permissions: "
8810 + parser.getName() + " at "
8811 + parser.getPositionDescription());
8812 }
8813 XmlUtils.skipCurrentTag(parser);
8814 }
8815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008817 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008818 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008819 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008820 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008821 String codePathStr = parser.getAttributeValue(null, "codePath");
8822 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008823 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008824 resourcePathStr = codePathStr;
8825 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008826 String version = parser.getAttributeValue(null, "version");
8827 int versionCode = 0;
8828 if (version != null) {
8829 try {
8830 versionCode = Integer.parseInt(version);
8831 } catch (NumberFormatException e) {
8832 }
8833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008835 int pkgFlags = 0;
8836 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008837 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008838 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008839 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008840 String timeStampStr = parser.getAttributeValue(null, "ts");
8841 if (timeStampStr != null) {
8842 try {
8843 long timeStamp = Long.parseLong(timeStampStr);
8844 ps.setTimeStamp(timeStamp, timeStampStr);
8845 } catch (NumberFormatException e) {
8846 }
8847 }
8848 String idStr = parser.getAttributeValue(null, "userId");
8849 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8850 if(ps.userId <= 0) {
8851 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8852 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8853 }
8854 int outerDepth = parser.getDepth();
8855 int type;
8856 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8857 && (type != XmlPullParser.END_TAG
8858 || parser.getDepth() > outerDepth)) {
8859 if (type == XmlPullParser.END_TAG
8860 || type == XmlPullParser.TEXT) {
8861 continue;
8862 }
8863
8864 String tagName = parser.getName();
8865 if (tagName.equals("perms")) {
8866 readGrantedPermissionsLP(parser,
8867 ps.grantedPermissions);
8868 } else {
8869 reportSettingsProblem(Log.WARN,
8870 "Unknown element under <updated-package>: "
8871 + parser.getName());
8872 XmlUtils.skipCurrentTag(parser);
8873 }
8874 }
8875 mDisabledSysPackages.put(name, ps);
8876 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008878 private void readPackageLP(XmlPullParser parser)
8879 throws XmlPullParserException, IOException {
8880 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008881 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008882 String idStr = null;
8883 String sharedIdStr = null;
8884 String codePathStr = null;
8885 String resourcePathStr = null;
8886 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008887 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008888 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008889 int pkgFlags = 0;
8890 String timeStampStr;
8891 long timeStamp = 0;
8892 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008893 String version = null;
8894 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008895 try {
8896 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008897 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008898 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008899 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008900 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8901 codePathStr = parser.getAttributeValue(null, "codePath");
8902 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008903 version = parser.getAttributeValue(null, "version");
8904 if (version != null) {
8905 try {
8906 versionCode = Integer.parseInt(version);
8907 } catch (NumberFormatException e) {
8908 }
8909 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008910 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008911
8912 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008913 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008914 try {
8915 pkgFlags = Integer.parseInt(systemStr);
8916 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008917 }
8918 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008919 // For backward compatibility
8920 systemStr = parser.getAttributeValue(null, "system");
8921 if (systemStr != null) {
8922 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8923 } else {
8924 // Old settings that don't specify system... just treat
8925 // them as system, good enough.
8926 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 }
8929 timeStampStr = parser.getAttributeValue(null, "ts");
8930 if (timeStampStr != null) {
8931 try {
8932 timeStamp = Long.parseLong(timeStampStr);
8933 } catch (NumberFormatException e) {
8934 }
8935 }
8936 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8937 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8938 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8939 if (resourcePathStr == null) {
8940 resourcePathStr = codePathStr;
8941 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008942 if (realName != null) {
8943 realName = realName.intern();
8944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 if (name == null) {
8946 reportSettingsProblem(Log.WARN,
8947 "Error in package manager settings: <package> has no name at "
8948 + parser.getPositionDescription());
8949 } else if (codePathStr == null) {
8950 reportSettingsProblem(Log.WARN,
8951 "Error in package manager settings: <package> has no codePath at "
8952 + parser.getPositionDescription());
8953 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008954 packageSetting = addPackageLP(name.intern(), realName,
8955 new File(codePathStr), new File(resourcePathStr),
8956 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8958 + ": userId=" + userId + " pkg=" + packageSetting);
8959 if (packageSetting == null) {
8960 reportSettingsProblem(Log.ERROR,
8961 "Failure adding uid " + userId
8962 + " while parsing settings at "
8963 + parser.getPositionDescription());
8964 } else {
8965 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8966 }
8967 } else if (sharedIdStr != null) {
8968 userId = sharedIdStr != null
8969 ? Integer.parseInt(sharedIdStr) : 0;
8970 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008971 packageSetting = new PendingPackage(name.intern(), realName,
8972 new File(codePathStr), new File(resourcePathStr),
8973 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008974 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8975 mPendingPackages.add((PendingPackage) packageSetting);
8976 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8977 + ": sharedUserId=" + userId + " pkg="
8978 + packageSetting);
8979 } else {
8980 reportSettingsProblem(Log.WARN,
8981 "Error in package manager settings: package "
8982 + name + " has bad sharedId " + sharedIdStr
8983 + " at " + parser.getPositionDescription());
8984 }
8985 } else {
8986 reportSettingsProblem(Log.WARN,
8987 "Error in package manager settings: package "
8988 + name + " has bad userId " + idStr + " at "
8989 + parser.getPositionDescription());
8990 }
8991 } catch (NumberFormatException e) {
8992 reportSettingsProblem(Log.WARN,
8993 "Error in package manager settings: package "
8994 + name + " has bad userId " + idStr + " at "
8995 + parser.getPositionDescription());
8996 }
8997 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008998 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008999 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009000 final String enabledStr = parser.getAttributeValue(null, "enabled");
9001 if (enabledStr != null) {
9002 if (enabledStr.equalsIgnoreCase("true")) {
9003 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9004 } else if (enabledStr.equalsIgnoreCase("false")) {
9005 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9006 } else if (enabledStr.equalsIgnoreCase("default")) {
9007 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9008 } else {
9009 reportSettingsProblem(Log.WARN,
9010 "Error in package manager settings: package "
9011 + name + " has bad enabled value: " + idStr
9012 + " at " + parser.getPositionDescription());
9013 }
9014 } else {
9015 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9016 }
9017 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9018 if (installStatusStr != null) {
9019 if (installStatusStr.equalsIgnoreCase("false")) {
9020 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9021 } else {
9022 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9023 }
9024 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009026 int outerDepth = parser.getDepth();
9027 int type;
9028 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9029 && (type != XmlPullParser.END_TAG
9030 || parser.getDepth() > outerDepth)) {
9031 if (type == XmlPullParser.END_TAG
9032 || type == XmlPullParser.TEXT) {
9033 continue;
9034 }
9035
9036 String tagName = parser.getName();
9037 if (tagName.equals("disabled-components")) {
9038 readDisabledComponentsLP(packageSetting, parser);
9039 } else if (tagName.equals("enabled-components")) {
9040 readEnabledComponentsLP(packageSetting, parser);
9041 } else if (tagName.equals("sigs")) {
9042 packageSetting.signatures.readXml(parser, mPastSignatures);
9043 } else if (tagName.equals("perms")) {
9044 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009045 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009046 packageSetting.permissionsFixed = true;
9047 } else {
9048 reportSettingsProblem(Log.WARN,
9049 "Unknown element under <package>: "
9050 + parser.getName());
9051 XmlUtils.skipCurrentTag(parser);
9052 }
9053 }
9054 } else {
9055 XmlUtils.skipCurrentTag(parser);
9056 }
9057 }
9058
9059 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9060 XmlPullParser parser)
9061 throws IOException, XmlPullParserException {
9062 int outerDepth = parser.getDepth();
9063 int type;
9064 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9065 && (type != XmlPullParser.END_TAG
9066 || parser.getDepth() > outerDepth)) {
9067 if (type == XmlPullParser.END_TAG
9068 || type == XmlPullParser.TEXT) {
9069 continue;
9070 }
9071
9072 String tagName = parser.getName();
9073 if (tagName.equals("item")) {
9074 String name = parser.getAttributeValue(null, "name");
9075 if (name != null) {
9076 packageSetting.disabledComponents.add(name.intern());
9077 } else {
9078 reportSettingsProblem(Log.WARN,
9079 "Error in package manager settings: <disabled-components> has"
9080 + " no name at " + parser.getPositionDescription());
9081 }
9082 } else {
9083 reportSettingsProblem(Log.WARN,
9084 "Unknown element under <disabled-components>: "
9085 + parser.getName());
9086 }
9087 XmlUtils.skipCurrentTag(parser);
9088 }
9089 }
9090
9091 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9092 XmlPullParser parser)
9093 throws IOException, XmlPullParserException {
9094 int outerDepth = parser.getDepth();
9095 int type;
9096 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9097 && (type != XmlPullParser.END_TAG
9098 || parser.getDepth() > outerDepth)) {
9099 if (type == XmlPullParser.END_TAG
9100 || type == XmlPullParser.TEXT) {
9101 continue;
9102 }
9103
9104 String tagName = parser.getName();
9105 if (tagName.equals("item")) {
9106 String name = parser.getAttributeValue(null, "name");
9107 if (name != null) {
9108 packageSetting.enabledComponents.add(name.intern());
9109 } else {
9110 reportSettingsProblem(Log.WARN,
9111 "Error in package manager settings: <enabled-components> has"
9112 + " no name at " + parser.getPositionDescription());
9113 }
9114 } else {
9115 reportSettingsProblem(Log.WARN,
9116 "Unknown element under <enabled-components>: "
9117 + parser.getName());
9118 }
9119 XmlUtils.skipCurrentTag(parser);
9120 }
9121 }
9122
9123 private void readSharedUserLP(XmlPullParser parser)
9124 throws XmlPullParserException, IOException {
9125 String name = null;
9126 String idStr = null;
9127 int pkgFlags = 0;
9128 SharedUserSetting su = null;
9129 try {
9130 name = parser.getAttributeValue(null, "name");
9131 idStr = parser.getAttributeValue(null, "userId");
9132 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9133 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9134 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9135 }
9136 if (name == null) {
9137 reportSettingsProblem(Log.WARN,
9138 "Error in package manager settings: <shared-user> has no name at "
9139 + parser.getPositionDescription());
9140 } else if (userId == 0) {
9141 reportSettingsProblem(Log.WARN,
9142 "Error in package manager settings: shared-user "
9143 + name + " has bad userId " + idStr + " at "
9144 + parser.getPositionDescription());
9145 } else {
9146 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9147 reportSettingsProblem(Log.ERROR,
9148 "Occurred while parsing settings at "
9149 + parser.getPositionDescription());
9150 }
9151 }
9152 } catch (NumberFormatException e) {
9153 reportSettingsProblem(Log.WARN,
9154 "Error in package manager settings: package "
9155 + name + " has bad userId " + idStr + " at "
9156 + parser.getPositionDescription());
9157 };
9158
9159 if (su != null) {
9160 int outerDepth = parser.getDepth();
9161 int type;
9162 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9163 && (type != XmlPullParser.END_TAG
9164 || parser.getDepth() > outerDepth)) {
9165 if (type == XmlPullParser.END_TAG
9166 || type == XmlPullParser.TEXT) {
9167 continue;
9168 }
9169
9170 String tagName = parser.getName();
9171 if (tagName.equals("sigs")) {
9172 su.signatures.readXml(parser, mPastSignatures);
9173 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009174 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009175 } else {
9176 reportSettingsProblem(Log.WARN,
9177 "Unknown element under <shared-user>: "
9178 + parser.getName());
9179 XmlUtils.skipCurrentTag(parser);
9180 }
9181 }
9182
9183 } else {
9184 XmlUtils.skipCurrentTag(parser);
9185 }
9186 }
9187
9188 private void readGrantedPermissionsLP(XmlPullParser parser,
9189 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9190 int outerDepth = parser.getDepth();
9191 int type;
9192 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9193 && (type != XmlPullParser.END_TAG
9194 || parser.getDepth() > outerDepth)) {
9195 if (type == XmlPullParser.END_TAG
9196 || type == XmlPullParser.TEXT) {
9197 continue;
9198 }
9199
9200 String tagName = parser.getName();
9201 if (tagName.equals("item")) {
9202 String name = parser.getAttributeValue(null, "name");
9203 if (name != null) {
9204 outPerms.add(name.intern());
9205 } else {
9206 reportSettingsProblem(Log.WARN,
9207 "Error in package manager settings: <perms> has"
9208 + " no name at " + parser.getPositionDescription());
9209 }
9210 } else {
9211 reportSettingsProblem(Log.WARN,
9212 "Unknown element under <perms>: "
9213 + parser.getName());
9214 }
9215 XmlUtils.skipCurrentTag(parser);
9216 }
9217 }
9218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009219 private void readPreferredActivitiesLP(XmlPullParser parser)
9220 throws XmlPullParserException, IOException {
9221 int outerDepth = parser.getDepth();
9222 int type;
9223 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9224 && (type != XmlPullParser.END_TAG
9225 || parser.getDepth() > outerDepth)) {
9226 if (type == XmlPullParser.END_TAG
9227 || type == XmlPullParser.TEXT) {
9228 continue;
9229 }
9230
9231 String tagName = parser.getName();
9232 if (tagName.equals("item")) {
9233 PreferredActivity pa = new PreferredActivity(parser);
9234 if (pa.mParseError == null) {
9235 mPreferredActivities.addFilter(pa);
9236 } else {
9237 reportSettingsProblem(Log.WARN,
9238 "Error in package manager settings: <preferred-activity> "
9239 + pa.mParseError + " at "
9240 + parser.getPositionDescription());
9241 }
9242 } else {
9243 reportSettingsProblem(Log.WARN,
9244 "Unknown element under <preferred-activities>: "
9245 + parser.getName());
9246 XmlUtils.skipCurrentTag(parser);
9247 }
9248 }
9249 }
9250
9251 // Returns -1 if we could not find an available UserId to assign
9252 private int newUserIdLP(Object obj) {
9253 // Let's be stupidly inefficient for now...
9254 final int N = mUserIds.size();
9255 for (int i=0; i<N; i++) {
9256 if (mUserIds.get(i) == null) {
9257 mUserIds.set(i, obj);
9258 return FIRST_APPLICATION_UID + i;
9259 }
9260 }
9261
9262 // None left?
9263 if (N >= MAX_APPLICATION_UIDS) {
9264 return -1;
9265 }
9266
9267 mUserIds.add(obj);
9268 return FIRST_APPLICATION_UID + N;
9269 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009271 public PackageSetting getDisabledSystemPkg(String name) {
9272 synchronized(mPackages) {
9273 PackageSetting ps = mDisabledSysPackages.get(name);
9274 return ps;
9275 }
9276 }
9277
9278 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9279 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9280 if (Config.LOGV) {
9281 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9282 + " componentName = " + componentInfo.name);
9283 Log.v(TAG, "enabledComponents: "
9284 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9285 Log.v(TAG, "disabledComponents: "
9286 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9287 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009288 if (packageSettings == null) {
9289 if (false) {
9290 Log.w(TAG, "WAITING FOR DEBUGGER");
9291 Debug.waitForDebugger();
9292 Log.i(TAG, "We will crash!");
9293 }
9294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009295 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9296 || ((componentInfo.enabled
9297 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9298 || (componentInfo.applicationInfo.enabled
9299 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9300 && !packageSettings.disabledComponents.contains(componentInfo.name))
9301 || packageSettings.enabledComponents.contains(componentInfo.name));
9302 }
9303 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009304
9305 // ------- apps on sdcard specific code -------
9306 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009307 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009308 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009309 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009310 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009311
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009312 private String getEncryptKey() {
9313 try {
9314 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9315 if (sdEncKey == null) {
9316 sdEncKey = SystemKeyStore.getInstance().
9317 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9318 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009319 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009320 return null;
9321 }
9322 }
9323 return sdEncKey;
9324 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009325 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009326 return null;
9327 }
9328 }
9329
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009330 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009331 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009332 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009333 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009334 if (list != null) {
9335 int idx = 0;
9336 int idList[] = new int[MAX_CONTAINERS];
9337 boolean neverFound = true;
9338 for (String name : list) {
9339 // Ignore null entries
9340 if (name == null) {
9341 continue;
9342 }
9343 int sidx = name.indexOf(prefix);
9344 if (sidx == -1) {
9345 // Not a temp file. just ignore
9346 continue;
9347 }
9348 String subStr = name.substring(sidx + prefix.length());
9349 idList[idx] = -1;
9350 if (subStr != null) {
9351 try {
9352 int cid = Integer.parseInt(subStr);
9353 idList[idx++] = cid;
9354 neverFound = false;
9355 } catch (NumberFormatException e) {
9356 }
9357 }
9358 }
9359 if (!neverFound) {
9360 // Sort idList
9361 Arrays.sort(idList);
9362 for (int j = 1; j <= idList.length; j++) {
9363 if (idList[j-1] != j) {
9364 tmpIdx = j;
9365 break;
9366 }
9367 }
9368 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009369 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009370 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009371 }
9372
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009373 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009374 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009375 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009376 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9377 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9378 throw new SecurityException("Media status can only be updated by the system");
9379 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009380 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009381 Log.i(TAG, "Updating external media status from " +
9382 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9383 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009384 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9385 mediaStatus+", mMediaMounted=" + mMediaMounted);
9386 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009387 if (reportStatus) {
9388 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9389 }
9390 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009391 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009392 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009393 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009394 // Queue up an async operation since the package installation may take a little while.
9395 mHandler.post(new Runnable() {
9396 public void run() {
9397 mHandler.removeCallbacks(this);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009398 try {
9399 updateExternalMediaStatusInner(mediaStatus);
9400 } finally {
9401 if (reportStatus) {
9402 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9403 }
9404 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009405 }
9406 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009407 }
9408
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009409 private void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009410 // If we are up here that means there are packages to be
9411 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009412 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009413 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009414 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009415 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009416 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009417
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009418 int uidList[] = new int[list.length];
9419 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009420 HashSet<String> removeCids = new HashSet<String>();
9421 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009422 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009423 for (String cid : list) {
9424 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009425 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9426 boolean failed = true;
9427 try {
9428 String pkgName = args.getPackageName();
9429 if (pkgName == null) {
9430 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009431 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009432 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9433 PackageSetting ps = mSettings.mPackages.get(pkgName);
9434 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009435 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009436 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9437 " corresponds to pkg : " + pkgName +
9438 " at code path: " + ps.codePathString);
9439 // We do have a valid package installed on sdcard
9440 processCids.put(args, ps.codePathString);
9441 failed = false;
9442 int uid = ps.userId;
9443 if (uid != -1) {
9444 uidList[num++] = uid;
9445 }
9446 }
9447 } finally {
9448 if (failed) {
9449 // Stale container on sdcard. Just delete
9450 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9451 removeCids.add(cid);
9452 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009453 }
9454 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009455 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009456 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009457 int uidArr[] = null;
9458 if (num > 0) {
9459 // Sort uid list
9460 Arrays.sort(uidList, 0, num);
9461 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009462 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009463 uidArr[0] = uidList[0];
9464 int di = 0;
9465 for (int i = 1; i < num; i++) {
9466 if (uidList[i-1] != uidList[i]) {
9467 uidArr[di++] = uidList[i];
9468 }
9469 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009470 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009471 // Process packages with valid entries.
9472 if (mediaStatus) {
9473 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009474 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009475 startCleaningPackages();
9476 } else {
9477 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009478 unloadMediaPackages(processCids, uidArr);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009479 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009480 }
9481
9482 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9483 ArrayList<String> pkgList, int uidArr[]) {
9484 int size = pkgList.size();
9485 if (size > 0) {
9486 // Send broadcasts here
9487 Bundle extras = new Bundle();
9488 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9489 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009490 if (uidArr != null) {
9491 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9492 }
9493 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9494 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009495 sendPackageBroadcast(action, null, extras);
9496 }
9497 }
9498
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009499 /*
9500 * Look at potentially valid container ids from processCids
9501 * If package information doesn't match the one on record
9502 * or package scanning fails, the cid is added to list of
9503 * removeCids and cleaned up. Since cleaning up containers
9504 * involves destroying them, we do not want any parse
9505 * references to such stale containers. So force gc's
9506 * to avoid unnecessary crashes.
9507 */
9508 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009509 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009510 ArrayList<String> pkgList = new ArrayList<String>();
9511 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009512 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009513 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009514 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009515 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9516 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009517 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009518 try {
9519 // Make sure there are no container errors first.
9520 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9521 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009522 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009523 " when installing from sdcard");
9524 continue;
9525 }
9526 // Check code path here.
9527 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009528 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009529 " does not match one in settings " + codePath);
9530 continue;
9531 }
9532 // Parse package
9533 int parseFlags = PackageParser.PARSE_CHATTY |
9534 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9535 PackageParser pp = new PackageParser(codePath);
9536 pp.setSeparateProcesses(mSeparateProcesses);
9537 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9538 codePath, mMetrics, parseFlags);
9539 pp = null;
9540 doGc = true;
9541 // Check for parse errors
9542 if (pkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009543 Slog.e(TAG, "Parse error when installing install pkg : "
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009544 + args.cid + " from " + args.cachePath);
9545 continue;
9546 }
9547 setApplicationInfoPaths(pkg, codePath, codePath);
9548 synchronized (mInstallLock) {
9549 // Scan the package
9550 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9551 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009552 retCode = PackageManager.INSTALL_SUCCEEDED;
9553 pkgList.add(pkg.packageName);
9554 // Post process args
9555 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9556 }
9557 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009558 Slog.i(TAG, "Failed to install pkg: " +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009559 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009560 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009561 }
9562
9563 } finally {
9564 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9565 // Don't destroy container here. Wait till gc clears things up.
9566 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009567 }
9568 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009569 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009570 synchronized (mPackages) {
9571 // Persist settings
9572 mSettings.writeLP();
9573 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009574 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009575 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009576 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9577 }
9578 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009579 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009580 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009581 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009582 if (removeCids != null) {
9583 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009584 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009585 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009586 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009587 }
9588
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009589 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009590 int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009591 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009592 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009593 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009594 Set<SdInstallArgs> keys = processCids.keySet();
9595 for (SdInstallArgs args : keys) {
9596 String cid = args.cid;
9597 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009598 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009599 // Delete package internally
9600 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9601 synchronized (mInstallLock) {
9602 boolean res = deletePackageLI(pkgName, false,
9603 PackageManager.DONT_DELETE_DATA, outInfo);
9604 if (res) {
9605 pkgList.add(pkgName);
9606 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009607 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009608 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009609 }
9610 }
9611 }
9612 // Send broadcasts
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009613 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009614 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009615 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009616 // Force gc
9617 Runtime.getRuntime().gc();
9618 // Just unmount all valid containers.
9619 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009620 synchronized (mInstallLock) {
9621 args.doPostDeleteLI(false);
9622 }
9623 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009624 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009625
9626 public void movePackage(final String packageName,
9627 final IPackageMoveObserver observer, final int flags) {
9628 if (packageName == null) {
9629 return;
9630 }
9631 mContext.enforceCallingOrSelfPermission(
9632 android.Manifest.permission.MOVE_PACKAGE, null);
9633 int returnCode = PackageManager.MOVE_SUCCEEDED;
9634 int currFlags = 0;
9635 int newFlags = 0;
9636 synchronized (mPackages) {
9637 PackageParser.Package pkg = mPackages.get(packageName);
9638 if (pkg == null) {
9639 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9640 }
9641 // Disable moving fwd locked apps and system packages
9642 if (pkg.applicationInfo != null &&
9643 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009644 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009645 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9646 } else if (pkg.applicationInfo != null &&
9647 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009648 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009649 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9650 } else {
9651 // Find install location first
9652 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9653 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009654 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009655 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9656 } else {
9657 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9658 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009659 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009660 PackageManager.INSTALL_EXTERNAL : 0;
9661 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009662 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009663 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9664 }
9665 }
9666 }
9667 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9668 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9669 } else {
9670 Message msg = mHandler.obtainMessage(INIT_COPY);
9671 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9672 pkg.applicationInfo.publicSourceDir);
9673 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9674 packageName);
9675 msg.obj = mp;
9676 mHandler.sendMessage(msg);
9677 }
9678 }
9679 }
9680
9681 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9682 // Queue up an async operation since the package deletion may take a little while.
9683 mHandler.post(new Runnable() {
9684 public void run() {
9685 mHandler.removeCallbacks(this);
9686 int returnCode = currentStatus;
9687 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9688 if (moveSucceeded) {
9689 int uid = -1;
9690 synchronized (mPackages) {
9691 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9692 }
9693 ArrayList<String> pkgList = new ArrayList<String>();
9694 pkgList.add(mp.packageName);
9695 int uidArr[] = new int[] { uid };
9696 // Send resources unavailable broadcast
9697 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9698
9699 // Update package code and resource paths
9700 synchronized (mPackages) {
9701 PackageParser.Package pkg = mPackages.get(mp.packageName);
9702 if (pkg != null) {
9703 String oldCodePath = pkg.mPath;
9704 String newCodePath = mp.targetArgs.getCodePath();
9705 String newResPath = mp.targetArgs.getResourcePath();
9706 pkg.mPath = newCodePath;
9707 // Move dex files around
9708 if (moveDexFiles(pkg)
9709 != PackageManager.INSTALL_SUCCEEDED) {
9710 // Moving of dex files failed. Set
9711 // error code and abort move.
9712 pkg.mPath = pkg.mScanPath;
9713 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9714 moveSucceeded = false;
9715 } else {
9716 pkg.mScanPath = newCodePath;
9717 pkg.applicationInfo.sourceDir = newCodePath;
9718 pkg.applicationInfo.publicSourceDir = newResPath;
9719 PackageSetting ps = (PackageSetting) pkg.mExtras;
9720 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9721 ps.codePathString = ps.codePath.getPath();
9722 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9723 ps.resourcePathString = ps.resourcePath.getPath();
9724 // Set the application info flag correctly.
9725 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009726 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009727 } else {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009728 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009729 }
9730 ps.setFlags(pkg.applicationInfo.flags);
9731 mAppDirs.remove(oldCodePath);
9732 mAppDirs.put(newCodePath, pkg);
9733 // Persist settings
9734 mSettings.writeLP();
9735 }
9736 }
9737 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009738 // Send resources available broadcast
9739 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009740 }
9741 if (!moveSucceeded){
9742 // Clean up failed installation
9743 if (mp.targetArgs != null) {
9744 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009745 returnCode);
9746 }
9747 } else {
9748 // Force a gc to clear things up.
9749 Runtime.getRuntime().gc();
9750 // Delete older code
9751 synchronized (mInstallLock) {
9752 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009753 }
9754 }
9755 IPackageMoveObserver observer = mp.observer;
9756 if (observer != null) {
9757 try {
9758 observer.packageMoved(mp.packageName, returnCode);
9759 } catch (RemoteException e) {
9760 Log.i(TAG, "Observer no longer exists.");
9761 }
9762 }
9763 }
9764 });
9765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009766}