blob: f9e19630abb6c569abd7f0d99386755852d180b7 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080021import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080022import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070023import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080024import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080032import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080033import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070038import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080039import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.pm.ActivityInfo;
42import android.content.pm.ApplicationInfo;
43import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070044import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.IPackageDataObserver;
46import android.content.pm.IPackageDeleteObserver;
47import android.content.pm.IPackageInstallObserver;
48import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080049import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.content.pm.IPackageStatsObserver;
51import android.content.pm.InstrumentationInfo;
52import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080053import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.content.pm.PackageManager;
55import android.content.pm.PackageStats;
56import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.pm.PackageParser;
60import android.content.pm.PermissionInfo;
61import android.content.pm.PermissionGroupInfo;
62import android.content.pm.ProviderInfo;
63import android.content.pm.ResolveInfo;
64import android.content.pm.ServiceInfo;
65import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.Uri;
67import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070068import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080070import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080072import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070073import android.os.Looper;
74import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Parcel;
76import android.os.RemoteException;
77import android.os.Environment;
78import android.os.FileObserver;
79import android.os.FileUtils;
80import android.os.Handler;
81import android.os.ParcelFileDescriptor;
82import android.os.Process;
83import android.os.ServiceManager;
84import android.os.SystemClock;
85import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080086import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.util.*;
88import android.view.Display;
89import android.view.WindowManager;
90
91import java.io.File;
92import java.io.FileDescriptor;
93import java.io.FileInputStream;
94import java.io.FileNotFoundException;
95import java.io.FileOutputStream;
96import java.io.FileReader;
97import java.io.FilenameFilter;
98import java.io.IOException;
99import java.io.InputStream;
100import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800101import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800102import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.util.ArrayList;
104import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700105import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.Collections;
107import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800108import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.Enumeration;
110import java.util.HashMap;
111import java.util.HashSet;
112import java.util.Iterator;
113import java.util.List;
114import java.util.Map;
115import java.util.Set;
116import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800117import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.zip.ZipFile;
119import java.util.zip.ZipOutputStream;
120
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700121/**
122 * Keep track of all those .apks everywhere.
123 *
124 * This is very central to the platform's security; please run the unit
125 * tests whenever making modifications here:
126 *
127mmm frameworks/base/tests/AndroidTests
128adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
129adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
130 *
131 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132class PackageManagerService extends IPackageManager.Stub {
133 private static final String TAG = "PackageManager";
134 private static final boolean DEBUG_SETTINGS = false;
135 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800136 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800137 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
139 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
140 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400141 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 private static final int FIRST_APPLICATION_UID =
143 Process.FIRST_APPLICATION_UID;
144 private static final int MAX_APPLICATION_UIDS = 1000;
145
146 private static final boolean SHOW_INFO = false;
147
148 private static final boolean GET_CERTIFICATES = true;
149
Oscar Montemayora8529f62009-11-18 10:14:20 -0800150 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 private static final int REMOVE_EVENTS =
153 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
154 private static final int ADD_EVENTS =
155 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
156
157 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800158 // Suffix used during package installation when copying/moving
159 // package apks to install directory.
160 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800162 /**
163 * Indicates the state of installation. Used by PackageManager to
164 * figure out incomplete installations. Say a package is being installed
165 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
166 * the package installation is successful or unsuccesful lin which case
167 * the PackageManager will no longer maintain state information associated
168 * with the package. If some exception(like device freeze or battery being
169 * pulled out) occurs during installation of a package, the PackageManager
170 * needs this information to clean up the previously failed installation.
171 */
172 private static final int PKG_INSTALL_INCOMPLETE = 0;
173 private static final int PKG_INSTALL_COMPLETE = 1;
174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final int SCAN_MONITOR = 1<<0;
176 static final int SCAN_NO_DEX = 1<<1;
177 static final int SCAN_FORCE_DEX = 1<<2;
178 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800179 static final int SCAN_NEW_INSTALL = 1<<4;
180 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800182 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
183 "com.android.defcontainer",
184 "com.android.defcontainer.DefaultContainerService");
185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
187 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700188 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
Dianne Hackborn851a5412009-05-08 12:06:44 -0700190 final int mSdkVersion = Build.VERSION.SDK_INT;
191 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
192 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 final Context mContext;
195 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700196 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 final DisplayMetrics mMetrics;
198 final int mDefParseFlags;
199 final String[] mSeparateProcesses;
200
201 // This is where all application persistent data goes.
202 final File mAppDataDir;
203
Oscar Montemayora8529f62009-11-18 10:14:20 -0800204 // If Encrypted File System feature is enabled, all application persistent data
205 // should go here instead.
206 final File mSecureAppDataDir;
207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 // This is the object monitoring the framework dir.
209 final FileObserver mFrameworkInstallObserver;
210
211 // This is the object monitoring the system app dir.
212 final FileObserver mSystemInstallObserver;
213
214 // This is the object monitoring mAppInstallDir.
215 final FileObserver mAppInstallObserver;
216
217 // This is the object monitoring mDrmAppPrivateInstallDir.
218 final FileObserver mDrmAppInstallObserver;
219
220 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
221 // LOCK HELD. Can be called with mInstallLock held.
222 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 final File mFrameworkDir;
225 final File mSystemAppDir;
226 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700227 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228
229 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
230 // apps.
231 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 // Lock for state used when installing and doing other long running
236 // operations. Methods that must be called with this lock held have
237 // the prefix "LI".
238 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // These are the directories in the 3rd party applications installed dir
241 // that we have currently loaded packages from. Keys are the application's
242 // installed zip file (absolute codePath), and values are Package.
243 final HashMap<String, PackageParser.Package> mAppDirs =
244 new HashMap<String, PackageParser.Package>();
245
246 // Information for the parser to write more useful error messages.
247 File mScanningPath;
248 int mLastScanError;
249
250 final int[] mOutPermissions = new int[3];
251
252 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 // Keys are String (package name), values are Package. This also serves
255 // as the lock for the global state. Methods that must be called with
256 // this lock held have the prefix "LP".
257 final HashMap<String, PackageParser.Package> mPackages =
258 new HashMap<String, PackageParser.Package>();
259
260 final Settings mSettings;
261 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262
263 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
264 int[] mGlobalGids;
265
266 // These are the built-in uid -> permission mappings that were read from the
267 // etc/permissions.xml file.
268 final SparseArray<HashSet<String>> mSystemPermissions =
269 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 // These are the built-in shared libraries that were read from the
272 // etc/permissions.xml file.
273 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800274
Dianne Hackborn49237342009-08-27 20:08:01 -0700275 // Temporary for building the final shared libraries for an .apk.
276 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800277
Dianne Hackborn49237342009-08-27 20:08:01 -0700278 // These are the features this devices supports that were read from the
279 // etc/permissions.xml file.
280 final HashMap<String, FeatureInfo> mAvailableFeatures =
281 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 // All available activities, for your resolving pleasure.
284 final ActivityIntentResolver mActivities =
285 new ActivityIntentResolver();
286
287 // All available receivers, for your resolving pleasure.
288 final ActivityIntentResolver mReceivers =
289 new ActivityIntentResolver();
290
291 // All available services, for your resolving pleasure.
292 final ServiceIntentResolver mServices = new ServiceIntentResolver();
293
294 // Keys are String (provider class name), values are Provider.
295 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
296 new HashMap<ComponentName, PackageParser.Provider>();
297
298 // Mapping from provider base names (first directory in content URI codePath)
299 // to the provider information.
300 final HashMap<String, PackageParser.Provider> mProviders =
301 new HashMap<String, PackageParser.Provider>();
302
303 // Mapping from instrumentation class names to info about them.
304 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
305 new HashMap<ComponentName, PackageParser.Instrumentation>();
306
307 // Mapping from permission names to info about them.
308 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
309 new HashMap<String, PackageParser.PermissionGroup>();
310
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800311 // Packages whose data we have transfered into another package, thus
312 // should no longer exist.
313 final HashSet<String> mTransferedPackages = new HashSet<String>();
314
Dianne Hackborn854060af2009-07-09 18:14:31 -0700315 // Broadcast actions that are only available to the system.
316 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 boolean mSystemReady;
319 boolean mSafeMode;
320 boolean mHasSystemUidErrors;
321
322 ApplicationInfo mAndroidApplication;
323 final ActivityInfo mResolveActivity = new ActivityInfo();
324 final ResolveInfo mResolveInfo = new ResolveInfo();
325 ComponentName mResolveComponentName;
326 PackageParser.Package mPlatformPackage;
327
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700328 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800329 final HashMap<String, ArrayList<String>> mPendingBroadcasts
330 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800331 // Service Connection to remote media container service to copy
332 // package uri's from external media onto secure containers
333 // or internal storage.
334 private IMediaContainerService mContainerService = null;
335
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700336 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800337 static final int MCS_BOUND = 3;
338 static final int END_COPY = 4;
339 static final int INIT_COPY = 5;
340 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800341 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800342 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800343 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800344 static final int MCS_RECONNECT = 10;
345 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700346 static final int UPDATED_MEDIA_STATUS = 12;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800347
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700348 // Delay time in millisecs
349 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800350 final private DefaultContainerConnection mDefContainerConn =
351 new DefaultContainerConnection();
352 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800353 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800354 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800355 IMediaContainerService imcs =
356 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800357 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800358 }
359
360 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800361 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800362 }
363 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700364
Christopher Tate1bb69062010-02-19 17:02:12 -0800365 // Recordkeeping of restore-after-install operations that are currently in flight
366 // between the Package Manager and the Backup Manager
367 class PostInstallData {
368 public InstallArgs args;
369 public PackageInstalledInfo res;
370
371 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
372 args = _a;
373 res = _r;
374 }
375 };
376 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
377 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
378
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700379 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800380 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800381 final ArrayList<HandlerParams> mPendingInstalls =
382 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800383
384 private boolean connectToService() {
385 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
386 " DefaultContainerService");
387 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
388 if (mContext.bindService(service, mDefContainerConn,
389 Context.BIND_AUTO_CREATE)) {
390 mBound = true;
391 return true;
392 }
393 return false;
394 }
395
396 private void disconnectService() {
397 mContainerService = null;
398 mBound = false;
399 mContext.unbindService(mDefContainerConn);
400 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800401
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700402 PackageHandler(Looper looper) {
403 super(looper);
404 }
405 public void handleMessage(Message msg) {
406 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800407 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800408 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800409 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800410 int idx = mPendingInstalls.size();
411 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
412 // If a bind was already initiated we dont really
413 // need to do anything. The pending install
414 // will be processed later on.
415 if (!mBound) {
416 // If this is the only one pending we might
417 // have to bind to the service again.
418 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800419 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800420 params.serviceError();
421 return;
422 } else {
423 // Once we bind to the service, the first
424 // pending request will be processed.
425 mPendingInstalls.add(idx, params);
426 }
427 } else {
428 mPendingInstalls.add(idx, params);
429 // Already bound to the service. Just make
430 // sure we trigger off processing the first request.
431 if (idx == 0) {
432 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800433 }
434 }
435 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800436 }
437 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800438 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800439 if (msg.obj != null) {
440 mContainerService = (IMediaContainerService) msg.obj;
441 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800442 if (mContainerService == null) {
443 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800444 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800445 for (HandlerParams params : mPendingInstalls) {
446 mPendingInstalls.remove(0);
447 // Indicate service bind error
448 params.serviceError();
449 }
450 mPendingInstalls.clear();
451 } else if (mPendingInstalls.size() > 0) {
452 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800453 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800454 params.startCopy();
455 }
456 } else {
457 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800458 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800459 }
460 break;
461 }
462 case MCS_RECONNECT : {
463 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
464 if (mPendingInstalls.size() > 0) {
465 if (mBound) {
466 disconnectService();
467 }
468 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800469 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 for (HandlerParams params : mPendingInstalls) {
471 mPendingInstalls.remove(0);
472 // Indicate service bind error
473 params.serviceError();
474 }
475 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800476 }
477 }
478 break;
479 }
480 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800481 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
482 // Delete pending install
483 if (mPendingInstalls.size() > 0) {
484 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800485 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800486 if (mPendingInstalls.size() == 0) {
487 if (mBound) {
488 disconnectService();
489 }
490 } else {
491 // There are more pending requests in queue.
492 // Just post MCS_BOUND message to trigger processing
493 // of next pending install.
494 mHandler.sendEmptyMessage(MCS_BOUND);
495 }
496 break;
497 }
498 case MCS_GIVE_UP: {
499 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
500 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800501 break;
502 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700503 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800504 String packages[];
505 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700506 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700507 int uids[];
508 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800509 if (mPendingBroadcasts == null) {
510 return;
511 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700512 size = mPendingBroadcasts.size();
513 if (size <= 0) {
514 // Nothing to be done. Just return
515 return;
516 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800517 packages = new String[size];
518 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700519 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800520 Iterator<HashMap.Entry<String, ArrayList<String>>>
521 it = mPendingBroadcasts.entrySet().iterator();
522 int i = 0;
523 while (it.hasNext() && i < size) {
524 HashMap.Entry<String, ArrayList<String>> ent = it.next();
525 packages[i] = ent.getKey();
526 components[i] = ent.getValue();
527 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700528 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800529 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700530 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800531 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700532 mPendingBroadcasts.clear();
533 }
534 // Send broadcasts
535 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800536 sendPackageChangedBroadcast(packages[i], true,
537 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700538 }
539 break;
540 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800541 case START_CLEANING_PACKAGE: {
542 String packageName = (String)msg.obj;
543 synchronized (mPackages) {
544 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
545 mSettings.mPackagesToBeCleaned.add(packageName);
546 }
547 }
548 startCleaningPackages();
549 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800550 case POST_INSTALL: {
551 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
552 PostInstallData data = mRunningInstalls.get(msg.arg1);
553 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800554 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800555
556 if (data != null) {
557 InstallArgs args = data.args;
558 PackageInstalledInfo res = data.res;
559
560 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
561 res.removedInfo.sendBroadcast(false, true);
562 Bundle extras = new Bundle(1);
563 extras.putInt(Intent.EXTRA_UID, res.uid);
564 final boolean update = res.removedInfo.removedPackage != null;
565 if (update) {
566 extras.putBoolean(Intent.EXTRA_REPLACING, true);
567 }
568 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
569 res.pkg.applicationInfo.packageName,
570 extras);
571 if (update) {
572 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
573 res.pkg.applicationInfo.packageName,
574 extras);
575 }
576 if (res.removedInfo.args != null) {
577 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800578 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800579 }
580 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800581 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800582 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800583 // We delete after a gc for applications on sdcard.
584 if (deleteOld) {
585 synchronized (mInstallLock) {
586 res.removedInfo.args.doPostDeleteLI(true);
587 }
588 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800589 if (args.observer != null) {
590 try {
591 args.observer.packageInstalled(res.name, res.returnCode);
592 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800593 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800594 }
595 }
596 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800597 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800598 }
599 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700600 case UPDATED_MEDIA_STATUS: {
601 try {
602 PackageHelper.getMountService().finishMediaUpdate();
603 } catch (RemoteException e) {
604 Log.e(TAG, "MountService not running?");
605 }
606 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700607 }
608 }
609 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800610
611 static boolean installOnSd(int flags) {
612 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700613 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800614 return false;
615 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700616 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
617 return true;
618 }
619 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800620 }
621
622 static boolean isFwdLocked(int flags) {
623 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
624 return true;
625 }
626 return false;
627 }
628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 public static final IPackageManager main(Context context, boolean factoryTest) {
630 PackageManagerService m = new PackageManagerService(context, factoryTest);
631 ServiceManager.addService("package", m);
632 return m;
633 }
634
635 static String[] splitString(String str, char sep) {
636 int count = 1;
637 int i = 0;
638 while ((i=str.indexOf(sep, i)) >= 0) {
639 count++;
640 i++;
641 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 String[] res = new String[count];
644 i=0;
645 count = 0;
646 int lastI=0;
647 while ((i=str.indexOf(sep, i)) >= 0) {
648 res[count] = str.substring(lastI, i);
649 count++;
650 i++;
651 lastI = i;
652 }
653 res[count] = str.substring(lastI, str.length());
654 return res;
655 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800658 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800662 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 mContext = context;
666 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700667 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 mMetrics = new DisplayMetrics();
669 mSettings = new Settings();
670 mSettings.addSharedUserLP("android.uid.system",
671 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
672 mSettings.addSharedUserLP("android.uid.phone",
673 MULTIPLE_APPLICATION_UIDS
674 ? RADIO_UID : FIRST_APPLICATION_UID,
675 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400676 mSettings.addSharedUserLP("android.uid.log",
677 MULTIPLE_APPLICATION_UIDS
678 ? LOG_UID : FIRST_APPLICATION_UID,
679 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680
681 String separateProcesses = SystemProperties.get("debug.separate_processes");
682 if (separateProcesses != null && separateProcesses.length() > 0) {
683 if ("*".equals(separateProcesses)) {
684 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
685 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800686 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 } else {
688 mDefParseFlags = 0;
689 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800690 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 + separateProcesses);
692 }
693 } else {
694 mDefParseFlags = 0;
695 mSeparateProcesses = null;
696 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 Installer installer = new Installer();
699 // Little hacky thing to check if installd is here, to determine
700 // whether we are running on the simulator and thus need to take
701 // care of building the /data file structure ourself.
702 // (apparently the sim now has a working installer)
703 if (installer.ping() && Process.supportsProcesses()) {
704 mInstaller = installer;
705 } else {
706 mInstaller = null;
707 }
708
709 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
710 Display d = wm.getDefaultDisplay();
711 d.getMetrics(mMetrics);
712
713 synchronized (mInstallLock) {
714 synchronized (mPackages) {
715 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700716 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 File dataDir = Environment.getDataDirectory();
719 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800720 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
722
723 if (mInstaller == null) {
724 // Make sure these dirs exist, when we are running in
725 // the simulator.
726 // Make a wide-open directory for random misc stuff.
727 File miscDir = new File(dataDir, "misc");
728 miscDir.mkdirs();
729 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800730 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 mDrmAppPrivateInstallDir.mkdirs();
732 }
733
734 readPermissions();
735
736 mRestoredSettings = mSettings.readLP();
737 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800738
739 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800741
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800742 // Set flag to monitor and not change apk file paths when
743 // scanning install directories.
744 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700745 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800746 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800747 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700748 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700753 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700756 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 /**
759 * Out of paranoia, ensure that everything in the boot class
760 * path has been dexed.
761 */
762 String bootClassPath = System.getProperty("java.boot.class.path");
763 if (bootClassPath != null) {
764 String[] paths = splitString(bootClassPath, ':');
765 for (int i=0; i<paths.length; i++) {
766 try {
767 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
768 libFiles.add(paths[i]);
769 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700770 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 }
772 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800773 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800775 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 }
777 }
778 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800779 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 /**
783 * Also ensure all external libraries have had dexopt run on them.
784 */
785 if (mSharedLibraries.size() > 0) {
786 Iterator<String> libs = mSharedLibraries.values().iterator();
787 while (libs.hasNext()) {
788 String lib = libs.next();
789 try {
790 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
791 libFiles.add(lib);
792 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700793 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 }
795 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800796 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800798 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 }
800 }
801 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 // Gross hack for now: we know this file doesn't contain any
804 // code, so don't dexopt it to avoid the resulting log spew.
805 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 /**
808 * And there are a number of commands implemented in Java, which
809 * we currently need to do the dexopt on so that they can be
810 * run from a non-root shell.
811 */
812 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700813 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 for (int i=0; i<frameworkFiles.length; i++) {
815 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
816 String path = libPath.getPath();
817 // Skip the file if we alrady did it.
818 if (libFiles.contains(path)) {
819 continue;
820 }
821 // Skip the file if it is not a type we want to dexopt.
822 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
823 continue;
824 }
825 try {
826 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
827 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700828 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 }
830 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800831 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800833 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
835 }
836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800837
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700838 if (didDexOpt) {
839 // If we had to do a dexopt of one of the previous
840 // things, then something on the system has changed.
841 // Consider this significant, and wipe away all other
842 // existing dexopt files to ensure we don't leave any
843 // dangling around.
844 String[] files = mDalvikCacheDir.list();
845 if (files != null) {
846 for (int i=0; i<files.length; i++) {
847 String fn = files[i];
848 if (fn.startsWith("data@app@")
849 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800850 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700851 (new File(mDalvikCacheDir, fn)).delete();
852 }
853 }
854 }
855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800857
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800858 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 mFrameworkInstallObserver = new AppDirObserver(
860 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
861 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700862 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
863 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800864 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800865
866 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
868 mSystemInstallObserver = new AppDirObserver(
869 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
870 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700871 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
872 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800873
874 if (mInstaller != null) {
875 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
876 mInstaller.moveFiles();
877 }
878
879 // Prune any system packages that no longer exist.
880 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
881 while (psit.hasNext()) {
882 PackageSetting ps = psit.next();
883 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800884 && !mPackages.containsKey(ps.name)
885 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800886 psit.remove();
887 String msg = "System package " + ps.name
888 + " no longer exists; wiping its data";
889 reportSettingsProblem(Log.WARN, msg);
890 if (mInstaller != null) {
891 // XXX how to set useEncryptedFSDir for packages that
892 // are not encrypted?
893 mInstaller.remove(ps.name, true);
894 }
895 }
896 }
897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 mAppInstallDir = new File(dataDir, "app");
899 if (mInstaller == null) {
900 // Make sure these dirs exist, when we are running in
901 // the simulator.
902 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
903 }
904 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800905 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 //clean up list
907 for(int i = 0; i < deletePkgsList.size(); i++) {
908 //clean up here
909 cleanupInstallFailedPackage(deletePkgsList.get(i));
910 }
911 //delete tmp files
912 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800913
914 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 SystemClock.uptimeMillis());
916 mAppInstallObserver = new AppDirObserver(
917 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
918 mAppInstallObserver.startWatching();
919 scanDirLI(mAppInstallDir, 0, scanMode);
920
921 mDrmAppInstallObserver = new AppDirObserver(
922 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
923 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800924 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800926 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800928 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 + ((SystemClock.uptimeMillis()-startTime)/1000f)
930 + " seconds");
931
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700932 updatePermissionsLP(null, null, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933
934 mSettings.writeLP();
935
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800936 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 // Now after opening every single application zip, make sure they
940 // are all flushed. Not really needed, but keeps things nice and
941 // tidy.
942 Runtime.getRuntime().gc();
943 } // synchronized (mPackages)
944 } // synchronized (mInstallLock)
945 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 @Override
948 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
949 throws RemoteException {
950 try {
951 return super.onTransact(code, data, reply, flags);
952 } catch (RuntimeException e) {
953 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800954 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 }
956 throw e;
957 }
958 }
959
Dianne Hackborne6620b22010-01-22 14:46:21 -0800960 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800961 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800963 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
964 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800966 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800967 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 }
969 } else {
970 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800971 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 File dataDir = new File(pkg.applicationInfo.dataDir);
973 dataDir.delete();
974 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800975 if (ps.codePath != null) {
976 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800977 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800978 }
979 }
980 if (ps.resourcePath != null) {
981 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800982 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800983 }
984 }
985 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 }
987
988 void readPermissions() {
989 // Read permissions from .../etc/permission directory.
990 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
991 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800992 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 return;
994 }
995 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800996 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 return;
998 }
999
1000 // Iterate over the files in the directory and scan .xml files
1001 for (File f : libraryDir.listFiles()) {
1002 // We'll read platform.xml last
1003 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1004 continue;
1005 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001008 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 continue;
1010 }
1011 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001012 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 continue;
1014 }
1015
1016 readPermissionsFromXml(f);
1017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1020 final File permFile = new File(Environment.getRootDirectory(),
1021 "etc/permissions/platform.xml");
1022 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001023
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001024 StringBuilder sb = new StringBuilder(128);
1025 sb.append("Libs:");
1026 Iterator<String> it = mSharedLibraries.keySet().iterator();
1027 while (it.hasNext()) {
1028 sb.append(' ');
1029 String name = it.next();
1030 sb.append(name);
1031 sb.append(':');
1032 sb.append(mSharedLibraries.get(name));
1033 }
1034 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001035
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001036 sb.setLength(0);
1037 sb.append("Features:");
1038 it = mAvailableFeatures.keySet().iterator();
1039 while (it.hasNext()) {
1040 sb.append(' ');
1041 sb.append(it.next());
1042 }
1043 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001045
1046 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 FileReader permReader = null;
1048 try {
1049 permReader = new FileReader(permFile);
1050 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001051 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 return;
1053 }
1054
1055 try {
1056 XmlPullParser parser = Xml.newPullParser();
1057 parser.setInput(permReader);
1058
1059 XmlUtils.beginDocument(parser, "permissions");
1060
1061 while (true) {
1062 XmlUtils.nextElement(parser);
1063 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1064 break;
1065 }
1066
1067 String name = parser.getName();
1068 if ("group".equals(name)) {
1069 String gidStr = parser.getAttributeValue(null, "gid");
1070 if (gidStr != null) {
1071 int gid = Integer.parseInt(gidStr);
1072 mGlobalGids = appendInt(mGlobalGids, gid);
1073 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001074 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 + parser.getPositionDescription());
1076 }
1077
1078 XmlUtils.skipCurrentTag(parser);
1079 continue;
1080 } else if ("permission".equals(name)) {
1081 String perm = parser.getAttributeValue(null, "name");
1082 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001083 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 + parser.getPositionDescription());
1085 XmlUtils.skipCurrentTag(parser);
1086 continue;
1087 }
1088 perm = perm.intern();
1089 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 } else if ("assign-permission".equals(name)) {
1092 String perm = parser.getAttributeValue(null, "name");
1093 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001094 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 + parser.getPositionDescription());
1096 XmlUtils.skipCurrentTag(parser);
1097 continue;
1098 }
1099 String uidStr = parser.getAttributeValue(null, "uid");
1100 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001101 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 + parser.getPositionDescription());
1103 XmlUtils.skipCurrentTag(parser);
1104 continue;
1105 }
1106 int uid = Process.getUidForName(uidStr);
1107 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001108 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 + uidStr + "\" at "
1110 + parser.getPositionDescription());
1111 XmlUtils.skipCurrentTag(parser);
1112 continue;
1113 }
1114 perm = perm.intern();
1115 HashSet<String> perms = mSystemPermissions.get(uid);
1116 if (perms == null) {
1117 perms = new HashSet<String>();
1118 mSystemPermissions.put(uid, perms);
1119 }
1120 perms.add(perm);
1121 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 } else if ("library".equals(name)) {
1124 String lname = parser.getAttributeValue(null, "name");
1125 String lfile = parser.getAttributeValue(null, "file");
1126 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001127 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 + parser.getPositionDescription());
1129 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001130 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 + parser.getPositionDescription());
1132 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001133 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001134 mSharedLibraries.put(lname, lfile);
1135 }
1136 XmlUtils.skipCurrentTag(parser);
1137 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001138
Dianne Hackborn49237342009-08-27 20:08:01 -07001139 } else if ("feature".equals(name)) {
1140 String fname = parser.getAttributeValue(null, "name");
1141 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001142 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001143 + parser.getPositionDescription());
1144 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001145 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001146 FeatureInfo fi = new FeatureInfo();
1147 fi.name = fname;
1148 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 }
1150 XmlUtils.skipCurrentTag(parser);
1151 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 } else {
1154 XmlUtils.skipCurrentTag(parser);
1155 continue;
1156 }
1157
1158 }
1159 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001160 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001162 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 }
1164 }
1165
1166 void readPermission(XmlPullParser parser, String name)
1167 throws IOException, XmlPullParserException {
1168
1169 name = name.intern();
1170
1171 BasePermission bp = mSettings.mPermissions.get(name);
1172 if (bp == null) {
1173 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1174 mSettings.mPermissions.put(name, bp);
1175 }
1176 int outerDepth = parser.getDepth();
1177 int type;
1178 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1179 && (type != XmlPullParser.END_TAG
1180 || parser.getDepth() > outerDepth)) {
1181 if (type == XmlPullParser.END_TAG
1182 || type == XmlPullParser.TEXT) {
1183 continue;
1184 }
1185
1186 String tagName = parser.getName();
1187 if ("group".equals(tagName)) {
1188 String gidStr = parser.getAttributeValue(null, "gid");
1189 if (gidStr != null) {
1190 int gid = Process.getGidForName(gidStr);
1191 bp.gids = appendInt(bp.gids, gid);
1192 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001193 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 + parser.getPositionDescription());
1195 }
1196 }
1197 XmlUtils.skipCurrentTag(parser);
1198 }
1199 }
1200
1201 static int[] appendInt(int[] cur, int val) {
1202 if (cur == null) {
1203 return new int[] { val };
1204 }
1205 final int N = cur.length;
1206 for (int i=0; i<N; i++) {
1207 if (cur[i] == val) {
1208 return cur;
1209 }
1210 }
1211 int[] ret = new int[N+1];
1212 System.arraycopy(cur, 0, ret, 0, N);
1213 ret[N] = val;
1214 return ret;
1215 }
1216
1217 static int[] appendInts(int[] cur, int[] add) {
1218 if (add == null) return cur;
1219 if (cur == null) return add;
1220 final int N = add.length;
1221 for (int i=0; i<N; i++) {
1222 cur = appendInt(cur, add[i]);
1223 }
1224 return cur;
1225 }
1226
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001227 static int[] removeInt(int[] cur, int val) {
1228 if (cur == null) {
1229 return null;
1230 }
1231 final int N = cur.length;
1232 for (int i=0; i<N; i++) {
1233 if (cur[i] == val) {
1234 int[] ret = new int[N-1];
1235 if (i > 0) {
1236 System.arraycopy(cur, 0, ret, 0, i);
1237 }
1238 if (i < (N-1)) {
1239 System.arraycopy(cur, i, ret, i+1, N-i-1);
1240 }
1241 return ret;
1242 }
1243 }
1244 return cur;
1245 }
1246
1247 static int[] removeInts(int[] cur, int[] rem) {
1248 if (rem == null) return cur;
1249 if (cur == null) return cur;
1250 final int N = rem.length;
1251 for (int i=0; i<N; i++) {
1252 cur = removeInt(cur, rem[i]);
1253 }
1254 return cur;
1255 }
1256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001258 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1259 // The package has been uninstalled but has retained data and resources.
1260 return PackageParser.generatePackageInfo(p, null, flags);
1261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 final PackageSetting ps = (PackageSetting)p.mExtras;
1263 if (ps == null) {
1264 return null;
1265 }
1266 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1267 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1268 }
1269
1270 public PackageInfo getPackageInfo(String packageName, int flags) {
1271 synchronized (mPackages) {
1272 PackageParser.Package p = mPackages.get(packageName);
1273 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001274 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 + ": " + p);
1276 if (p != null) {
1277 return generatePackageInfo(p, flags);
1278 }
1279 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1280 return generatePackageInfoFromSettingsLP(packageName, flags);
1281 }
1282 }
1283 return null;
1284 }
1285
Dianne Hackborn47096932010-02-11 15:57:09 -08001286 public String[] currentToCanonicalPackageNames(String[] names) {
1287 String[] out = new String[names.length];
1288 synchronized (mPackages) {
1289 for (int i=names.length-1; i>=0; i--) {
1290 PackageSetting ps = mSettings.mPackages.get(names[i]);
1291 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1292 }
1293 }
1294 return out;
1295 }
1296
1297 public String[] canonicalToCurrentPackageNames(String[] names) {
1298 String[] out = new String[names.length];
1299 synchronized (mPackages) {
1300 for (int i=names.length-1; i>=0; i--) {
1301 String cur = mSettings.mRenamedPackages.get(names[i]);
1302 out[i] = cur != null ? cur : names[i];
1303 }
1304 }
1305 return out;
1306 }
1307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 public int getPackageUid(String packageName) {
1309 synchronized (mPackages) {
1310 PackageParser.Package p = mPackages.get(packageName);
1311 if(p != null) {
1312 return p.applicationInfo.uid;
1313 }
1314 PackageSetting ps = mSettings.mPackages.get(packageName);
1315 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1316 return -1;
1317 }
1318 p = ps.pkg;
1319 return p != null ? p.applicationInfo.uid : -1;
1320 }
1321 }
1322
1323 public int[] getPackageGids(String packageName) {
1324 synchronized (mPackages) {
1325 PackageParser.Package p = mPackages.get(packageName);
1326 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001327 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 + ": " + p);
1329 if (p != null) {
1330 final PackageSetting ps = (PackageSetting)p.mExtras;
1331 final SharedUserSetting suid = ps.sharedUser;
1332 return suid != null ? suid.gids : ps.gids;
1333 }
1334 }
1335 // stupid thing to indicate an error.
1336 return new int[0];
1337 }
1338
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001339 static final PermissionInfo generatePermissionInfo(
1340 BasePermission bp, int flags) {
1341 if (bp.perm != null) {
1342 return PackageParser.generatePermissionInfo(bp.perm, flags);
1343 }
1344 PermissionInfo pi = new PermissionInfo();
1345 pi.name = bp.name;
1346 pi.packageName = bp.sourcePackage;
1347 pi.nonLocalizedLabel = bp.name;
1348 pi.protectionLevel = bp.protectionLevel;
1349 return pi;
1350 }
1351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 public PermissionInfo getPermissionInfo(String name, int flags) {
1353 synchronized (mPackages) {
1354 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001355 if (p != null) {
1356 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 }
1358 return null;
1359 }
1360 }
1361
1362 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1363 synchronized (mPackages) {
1364 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1365 for (BasePermission p : mSettings.mPermissions.values()) {
1366 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001367 if (p.perm == null || p.perm.info.group == null) {
1368 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 }
1370 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001371 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1373 }
1374 }
1375 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 if (out.size() > 0) {
1378 return out;
1379 }
1380 return mPermissionGroups.containsKey(group) ? out : null;
1381 }
1382 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1385 synchronized (mPackages) {
1386 return PackageParser.generatePermissionGroupInfo(
1387 mPermissionGroups.get(name), flags);
1388 }
1389 }
1390
1391 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1392 synchronized (mPackages) {
1393 final int N = mPermissionGroups.size();
1394 ArrayList<PermissionGroupInfo> out
1395 = new ArrayList<PermissionGroupInfo>(N);
1396 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1397 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1398 }
1399 return out;
1400 }
1401 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1404 PackageSetting ps = mSettings.mPackages.get(packageName);
1405 if(ps != null) {
1406 if(ps.pkg == null) {
1407 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1408 if(pInfo != null) {
1409 return pInfo.applicationInfo;
1410 }
1411 return null;
1412 }
1413 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1414 }
1415 return null;
1416 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1419 PackageSetting ps = mSettings.mPackages.get(packageName);
1420 if(ps != null) {
1421 if(ps.pkg == null) {
1422 ps.pkg = new PackageParser.Package(packageName);
1423 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001424 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1425 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1426 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1427 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429 return generatePackageInfo(ps.pkg, flags);
1430 }
1431 return null;
1432 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1435 synchronized (mPackages) {
1436 PackageParser.Package p = mPackages.get(packageName);
1437 if (Config.LOGV) Log.v(
1438 TAG, "getApplicationInfo " + packageName
1439 + ": " + p);
1440 if (p != null) {
1441 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001442 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 }
1444 if ("android".equals(packageName)||"system".equals(packageName)) {
1445 return mAndroidApplication;
1446 }
1447 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1448 return generateApplicationInfoFromSettingsLP(packageName, flags);
1449 }
1450 }
1451 return null;
1452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001453
1454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1456 mContext.enforceCallingOrSelfPermission(
1457 android.Manifest.permission.CLEAR_APP_CACHE, null);
1458 // Queue up an async operation since clearing cache may take a little while.
1459 mHandler.post(new Runnable() {
1460 public void run() {
1461 mHandler.removeCallbacks(this);
1462 int retCode = -1;
1463 if (mInstaller != null) {
1464 retCode = mInstaller.freeCache(freeStorageSize);
1465 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001466 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
1468 } //end if mInstaller
1469 if (observer != null) {
1470 try {
1471 observer.onRemoveCompleted(null, (retCode >= 0));
1472 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001473 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 }
1475 }
1476 }
1477 });
1478 }
1479
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001480 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001481 mContext.enforceCallingOrSelfPermission(
1482 android.Manifest.permission.CLEAR_APP_CACHE, null);
1483 // Queue up an async operation since clearing cache may take a little while.
1484 mHandler.post(new Runnable() {
1485 public void run() {
1486 mHandler.removeCallbacks(this);
1487 int retCode = -1;
1488 if (mInstaller != null) {
1489 retCode = mInstaller.freeCache(freeStorageSize);
1490 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001491 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001492 }
1493 }
1494 if(pi != null) {
1495 try {
1496 // Callback via pending intent
1497 int code = (retCode >= 0) ? 1 : 0;
1498 pi.sendIntent(null, code, null,
1499 null, null);
1500 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001501 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001502 }
1503 }
1504 }
1505 });
1506 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1509 synchronized (mPackages) {
1510 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001511
1512 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001514 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516 if (mResolveComponentName.equals(component)) {
1517 return mResolveActivity;
1518 }
1519 }
1520 return null;
1521 }
1522
1523 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1524 synchronized (mPackages) {
1525 PackageParser.Activity a = mReceivers.mActivities.get(component);
1526 if (Config.LOGV) Log.v(
1527 TAG, "getReceiverInfo " + component + ": " + a);
1528 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1529 return PackageParser.generateActivityInfo(a, flags);
1530 }
1531 }
1532 return null;
1533 }
1534
1535 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1536 synchronized (mPackages) {
1537 PackageParser.Service s = mServices.mServices.get(component);
1538 if (Config.LOGV) Log.v(
1539 TAG, "getServiceInfo " + component + ": " + s);
1540 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1541 return PackageParser.generateServiceInfo(s, flags);
1542 }
1543 }
1544 return null;
1545 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 public String[] getSystemSharedLibraryNames() {
1548 Set<String> libSet;
1549 synchronized (mPackages) {
1550 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001551 int size = libSet.size();
1552 if (size > 0) {
1553 String[] libs = new String[size];
1554 libSet.toArray(libs);
1555 return libs;
1556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001558 return null;
1559 }
1560
1561 public FeatureInfo[] getSystemAvailableFeatures() {
1562 Collection<FeatureInfo> featSet;
1563 synchronized (mPackages) {
1564 featSet = mAvailableFeatures.values();
1565 int size = featSet.size();
1566 if (size > 0) {
1567 FeatureInfo[] features = new FeatureInfo[size+1];
1568 featSet.toArray(features);
1569 FeatureInfo fi = new FeatureInfo();
1570 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1571 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1572 features[size] = fi;
1573 return features;
1574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 }
1576 return null;
1577 }
1578
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001579 public boolean hasSystemFeature(String name) {
1580 synchronized (mPackages) {
1581 return mAvailableFeatures.containsKey(name);
1582 }
1583 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 public int checkPermission(String permName, String pkgName) {
1586 synchronized (mPackages) {
1587 PackageParser.Package p = mPackages.get(pkgName);
1588 if (p != null && p.mExtras != null) {
1589 PackageSetting ps = (PackageSetting)p.mExtras;
1590 if (ps.sharedUser != null) {
1591 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1592 return PackageManager.PERMISSION_GRANTED;
1593 }
1594 } else if (ps.grantedPermissions.contains(permName)) {
1595 return PackageManager.PERMISSION_GRANTED;
1596 }
1597 }
1598 }
1599 return PackageManager.PERMISSION_DENIED;
1600 }
1601
1602 public int checkUidPermission(String permName, int uid) {
1603 synchronized (mPackages) {
1604 Object obj = mSettings.getUserIdLP(uid);
1605 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001606 GrantedPermissions gp = (GrantedPermissions)obj;
1607 if (gp.grantedPermissions.contains(permName)) {
1608 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
1610 } else {
1611 HashSet<String> perms = mSystemPermissions.get(uid);
1612 if (perms != null && perms.contains(permName)) {
1613 return PackageManager.PERMISSION_GRANTED;
1614 }
1615 }
1616 }
1617 return PackageManager.PERMISSION_DENIED;
1618 }
1619
1620 private BasePermission findPermissionTreeLP(String permName) {
1621 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1622 if (permName.startsWith(bp.name) &&
1623 permName.length() > bp.name.length() &&
1624 permName.charAt(bp.name.length()) == '.') {
1625 return bp;
1626 }
1627 }
1628 return null;
1629 }
1630
1631 private BasePermission checkPermissionTreeLP(String permName) {
1632 if (permName != null) {
1633 BasePermission bp = findPermissionTreeLP(permName);
1634 if (bp != null) {
1635 if (bp.uid == Binder.getCallingUid()) {
1636 return bp;
1637 }
1638 throw new SecurityException("Calling uid "
1639 + Binder.getCallingUid()
1640 + " is not allowed to add to permission tree "
1641 + bp.name + " owned by uid " + bp.uid);
1642 }
1643 }
1644 throw new SecurityException("No permission tree found for " + permName);
1645 }
1646
1647 public boolean addPermission(PermissionInfo info) {
1648 synchronized (mPackages) {
1649 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1650 throw new SecurityException("Label must be specified in permission");
1651 }
1652 BasePermission tree = checkPermissionTreeLP(info.name);
1653 BasePermission bp = mSettings.mPermissions.get(info.name);
1654 boolean added = bp == null;
1655 if (added) {
1656 bp = new BasePermission(info.name, tree.sourcePackage,
1657 BasePermission.TYPE_DYNAMIC);
1658 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1659 throw new SecurityException(
1660 "Not allowed to modify non-dynamic permission "
1661 + info.name);
1662 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001663 bp.protectionLevel = info.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 bp.perm = new PackageParser.Permission(tree.perm.owner,
1665 new PermissionInfo(info));
1666 bp.perm.info.packageName = tree.perm.info.packageName;
1667 bp.uid = tree.uid;
1668 if (added) {
1669 mSettings.mPermissions.put(info.name, bp);
1670 }
1671 mSettings.writeLP();
1672 return added;
1673 }
1674 }
1675
1676 public void removePermission(String name) {
1677 synchronized (mPackages) {
1678 checkPermissionTreeLP(name);
1679 BasePermission bp = mSettings.mPermissions.get(name);
1680 if (bp != null) {
1681 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1682 throw new SecurityException(
1683 "Not allowed to modify non-dynamic permission "
1684 + name);
1685 }
1686 mSettings.mPermissions.remove(name);
1687 mSettings.writeLP();
1688 }
1689 }
1690 }
1691
Dianne Hackborn854060af2009-07-09 18:14:31 -07001692 public boolean isProtectedBroadcast(String actionName) {
1693 synchronized (mPackages) {
1694 return mProtectedBroadcasts.contains(actionName);
1695 }
1696 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 public int checkSignatures(String pkg1, String pkg2) {
1699 synchronized (mPackages) {
1700 PackageParser.Package p1 = mPackages.get(pkg1);
1701 PackageParser.Package p2 = mPackages.get(pkg2);
1702 if (p1 == null || p1.mExtras == null
1703 || p2 == null || p2.mExtras == null) {
1704 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1705 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001706 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 }
1708 }
1709
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001710 public int checkUidSignatures(int uid1, int uid2) {
1711 synchronized (mPackages) {
1712 Signature[] s1;
1713 Signature[] s2;
1714 Object obj = mSettings.getUserIdLP(uid1);
1715 if (obj != null) {
1716 if (obj instanceof SharedUserSetting) {
1717 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1718 } else if (obj instanceof PackageSetting) {
1719 s1 = ((PackageSetting)obj).signatures.mSignatures;
1720 } else {
1721 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1722 }
1723 } else {
1724 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1725 }
1726 obj = mSettings.getUserIdLP(uid2);
1727 if (obj != null) {
1728 if (obj instanceof SharedUserSetting) {
1729 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1730 } else if (obj instanceof PackageSetting) {
1731 s2 = ((PackageSetting)obj).signatures.mSignatures;
1732 } else {
1733 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1734 }
1735 } else {
1736 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1737 }
1738 return checkSignaturesLP(s1, s2);
1739 }
1740 }
1741
1742 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1743 if (s1 == null) {
1744 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1746 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1747 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001748 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1750 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001751 final int N1 = s1.length;
1752 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 for (int i=0; i<N1; i++) {
1754 boolean match = false;
1755 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001756 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 match = true;
1758 break;
1759 }
1760 }
1761 if (!match) {
1762 return PackageManager.SIGNATURE_NO_MATCH;
1763 }
1764 }
1765 return PackageManager.SIGNATURE_MATCH;
1766 }
1767
1768 public String[] getPackagesForUid(int uid) {
1769 synchronized (mPackages) {
1770 Object obj = mSettings.getUserIdLP(uid);
1771 if (obj instanceof SharedUserSetting) {
1772 SharedUserSetting sus = (SharedUserSetting)obj;
1773 final int N = sus.packages.size();
1774 String[] res = new String[N];
1775 Iterator<PackageSetting> it = sus.packages.iterator();
1776 int i=0;
1777 while (it.hasNext()) {
1778 res[i++] = it.next().name;
1779 }
1780 return res;
1781 } else if (obj instanceof PackageSetting) {
1782 PackageSetting ps = (PackageSetting)obj;
1783 return new String[] { ps.name };
1784 }
1785 }
1786 return null;
1787 }
1788
1789 public String getNameForUid(int uid) {
1790 synchronized (mPackages) {
1791 Object obj = mSettings.getUserIdLP(uid);
1792 if (obj instanceof SharedUserSetting) {
1793 SharedUserSetting sus = (SharedUserSetting)obj;
1794 return sus.name + ":" + sus.userId;
1795 } else if (obj instanceof PackageSetting) {
1796 PackageSetting ps = (PackageSetting)obj;
1797 return ps.name;
1798 }
1799 }
1800 return null;
1801 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 public int getUidForSharedUser(String sharedUserName) {
1804 if(sharedUserName == null) {
1805 return -1;
1806 }
1807 synchronized (mPackages) {
1808 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1809 if(suid == null) {
1810 return -1;
1811 }
1812 return suid.userId;
1813 }
1814 }
1815
1816 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1817 int flags) {
1818 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001819 return chooseBestActivity(intent, resolvedType, flags, query);
1820 }
1821
Mihai Predaeae850c2009-05-13 10:13:48 +02001822 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1823 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 if (query != null) {
1825 final int N = query.size();
1826 if (N == 1) {
1827 return query.get(0);
1828 } else if (N > 1) {
1829 // If there is more than one activity with the same priority,
1830 // then let the user decide between them.
1831 ResolveInfo r0 = query.get(0);
1832 ResolveInfo r1 = query.get(1);
1833 if (false) {
1834 System.out.println(r0.activityInfo.name +
1835 "=" + r0.priority + " vs " +
1836 r1.activityInfo.name +
1837 "=" + r1.priority);
1838 }
1839 // If the first activity has a higher priority, or a different
1840 // default, then it is always desireable to pick it.
1841 if (r0.priority != r1.priority
1842 || r0.preferredOrder != r1.preferredOrder
1843 || r0.isDefault != r1.isDefault) {
1844 return query.get(0);
1845 }
1846 // If we have saved a preference for a preferred activity for
1847 // this Intent, use that.
1848 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1849 flags, query, r0.priority);
1850 if (ri != null) {
1851 return ri;
1852 }
1853 return mResolveInfo;
1854 }
1855 }
1856 return null;
1857 }
1858
1859 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1860 int flags, List<ResolveInfo> query, int priority) {
1861 synchronized (mPackages) {
1862 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1863 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001864 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1866 if (prefs != null && prefs.size() > 0) {
1867 // First figure out how good the original match set is.
1868 // We will only allow preferred activities that came
1869 // from the same match quality.
1870 int match = 0;
1871 final int N = query.size();
1872 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1873 for (int j=0; j<N; j++) {
1874 ResolveInfo ri = query.get(j);
1875 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1876 + ": 0x" + Integer.toHexString(match));
1877 if (ri.match > match) match = ri.match;
1878 }
1879 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1880 + Integer.toHexString(match));
1881 match &= IntentFilter.MATCH_CATEGORY_MASK;
1882 final int M = prefs.size();
1883 for (int i=0; i<M; i++) {
1884 PreferredActivity pa = prefs.get(i);
1885 if (pa.mMatch != match) {
1886 continue;
1887 }
1888 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1889 if (DEBUG_PREFERRED) {
1890 Log.v(TAG, "Got preferred activity:");
1891 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1892 }
1893 if (ai != null) {
1894 for (int j=0; j<N; j++) {
1895 ResolveInfo ri = query.get(j);
1896 if (!ri.activityInfo.applicationInfo.packageName
1897 .equals(ai.applicationInfo.packageName)) {
1898 continue;
1899 }
1900 if (!ri.activityInfo.name.equals(ai.name)) {
1901 continue;
1902 }
1903
1904 // Okay we found a previously set preferred app.
1905 // If the result set is different from when this
1906 // was created, we need to clear it and re-ask the
1907 // user their preference.
1908 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001909 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 + intent + " type " + resolvedType);
1911 mSettings.mPreferredActivities.removeFilter(pa);
1912 return null;
1913 }
1914
1915 // Yay!
1916 return ri;
1917 }
1918 }
1919 }
1920 }
1921 }
1922 return null;
1923 }
1924
1925 public List<ResolveInfo> queryIntentActivities(Intent intent,
1926 String resolvedType, int flags) {
1927 ComponentName comp = intent.getComponent();
1928 if (comp != null) {
1929 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1930 ActivityInfo ai = getActivityInfo(comp, flags);
1931 if (ai != null) {
1932 ResolveInfo ri = new ResolveInfo();
1933 ri.activityInfo = ai;
1934 list.add(ri);
1935 }
1936 return list;
1937 }
1938
1939 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001940 String pkgName = intent.getPackage();
1941 if (pkgName == null) {
1942 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1943 resolvedType, flags);
1944 }
1945 PackageParser.Package pkg = mPackages.get(pkgName);
1946 if (pkg != null) {
1947 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1948 resolvedType, flags, pkg.activities);
1949 }
1950 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 }
1952 }
1953
1954 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1955 Intent[] specifics, String[] specificTypes, Intent intent,
1956 String resolvedType, int flags) {
1957 final String resultsAction = intent.getAction();
1958
1959 List<ResolveInfo> results = queryIntentActivities(
1960 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1961 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1962
1963 int specificsPos = 0;
1964 int N;
1965
1966 // todo: note that the algorithm used here is O(N^2). This
1967 // isn't a problem in our current environment, but if we start running
1968 // into situations where we have more than 5 or 10 matches then this
1969 // should probably be changed to something smarter...
1970
1971 // First we go through and resolve each of the specific items
1972 // that were supplied, taking care of removing any corresponding
1973 // duplicate items in the generic resolve list.
1974 if (specifics != null) {
1975 for (int i=0; i<specifics.length; i++) {
1976 final Intent sintent = specifics[i];
1977 if (sintent == null) {
1978 continue;
1979 }
1980
1981 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1982 String action = sintent.getAction();
1983 if (resultsAction != null && resultsAction.equals(action)) {
1984 // If this action was explicitly requested, then don't
1985 // remove things that have it.
1986 action = null;
1987 }
1988 ComponentName comp = sintent.getComponent();
1989 ResolveInfo ri = null;
1990 ActivityInfo ai = null;
1991 if (comp == null) {
1992 ri = resolveIntent(
1993 sintent,
1994 specificTypes != null ? specificTypes[i] : null,
1995 flags);
1996 if (ri == null) {
1997 continue;
1998 }
1999 if (ri == mResolveInfo) {
2000 // ACK! Must do something better with this.
2001 }
2002 ai = ri.activityInfo;
2003 comp = new ComponentName(ai.applicationInfo.packageName,
2004 ai.name);
2005 } else {
2006 ai = getActivityInfo(comp, flags);
2007 if (ai == null) {
2008 continue;
2009 }
2010 }
2011
2012 // Look for any generic query activities that are duplicates
2013 // of this specific one, and remove them from the results.
2014 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2015 N = results.size();
2016 int j;
2017 for (j=specificsPos; j<N; j++) {
2018 ResolveInfo sri = results.get(j);
2019 if ((sri.activityInfo.name.equals(comp.getClassName())
2020 && sri.activityInfo.applicationInfo.packageName.equals(
2021 comp.getPackageName()))
2022 || (action != null && sri.filter.matchAction(action))) {
2023 results.remove(j);
2024 if (Config.LOGV) Log.v(
2025 TAG, "Removing duplicate item from " + j
2026 + " due to specific " + specificsPos);
2027 if (ri == null) {
2028 ri = sri;
2029 }
2030 j--;
2031 N--;
2032 }
2033 }
2034
2035 // Add this specific item to its proper place.
2036 if (ri == null) {
2037 ri = new ResolveInfo();
2038 ri.activityInfo = ai;
2039 }
2040 results.add(specificsPos, ri);
2041 ri.specificIndex = i;
2042 specificsPos++;
2043 }
2044 }
2045
2046 // Now we go through the remaining generic results and remove any
2047 // duplicate actions that are found here.
2048 N = results.size();
2049 for (int i=specificsPos; i<N-1; i++) {
2050 final ResolveInfo rii = results.get(i);
2051 if (rii.filter == null) {
2052 continue;
2053 }
2054
2055 // Iterate over all of the actions of this result's intent
2056 // filter... typically this should be just one.
2057 final Iterator<String> it = rii.filter.actionsIterator();
2058 if (it == null) {
2059 continue;
2060 }
2061 while (it.hasNext()) {
2062 final String action = it.next();
2063 if (resultsAction != null && resultsAction.equals(action)) {
2064 // If this action was explicitly requested, then don't
2065 // remove things that have it.
2066 continue;
2067 }
2068 for (int j=i+1; j<N; j++) {
2069 final ResolveInfo rij = results.get(j);
2070 if (rij.filter != null && rij.filter.hasAction(action)) {
2071 results.remove(j);
2072 if (Config.LOGV) Log.v(
2073 TAG, "Removing duplicate item from " + j
2074 + " due to action " + action + " at " + i);
2075 j--;
2076 N--;
2077 }
2078 }
2079 }
2080
2081 // If the caller didn't request filter information, drop it now
2082 // so we don't have to marshall/unmarshall it.
2083 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2084 rii.filter = null;
2085 }
2086 }
2087
2088 // Filter out the caller activity if so requested.
2089 if (caller != null) {
2090 N = results.size();
2091 for (int i=0; i<N; i++) {
2092 ActivityInfo ainfo = results.get(i).activityInfo;
2093 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2094 && caller.getClassName().equals(ainfo.name)) {
2095 results.remove(i);
2096 break;
2097 }
2098 }
2099 }
2100
2101 // If the caller didn't request filter information,
2102 // drop them now so we don't have to
2103 // marshall/unmarshall it.
2104 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2105 N = results.size();
2106 for (int i=0; i<N; i++) {
2107 results.get(i).filter = null;
2108 }
2109 }
2110
2111 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2112 return results;
2113 }
2114
2115 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2116 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002117 ComponentName comp = intent.getComponent();
2118 if (comp != null) {
2119 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2120 ActivityInfo ai = getReceiverInfo(comp, flags);
2121 if (ai != null) {
2122 ResolveInfo ri = new ResolveInfo();
2123 ri.activityInfo = ai;
2124 list.add(ri);
2125 }
2126 return list;
2127 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002130 String pkgName = intent.getPackage();
2131 if (pkgName == null) {
2132 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2133 resolvedType, flags);
2134 }
2135 PackageParser.Package pkg = mPackages.get(pkgName);
2136 if (pkg != null) {
2137 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2138 resolvedType, flags, pkg.receivers);
2139 }
2140 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 }
2142 }
2143
2144 public ResolveInfo resolveService(Intent intent, String resolvedType,
2145 int flags) {
2146 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2147 flags);
2148 if (query != null) {
2149 if (query.size() >= 1) {
2150 // If there is more than one service with the same priority,
2151 // just arbitrarily pick the first one.
2152 return query.get(0);
2153 }
2154 }
2155 return null;
2156 }
2157
2158 public List<ResolveInfo> queryIntentServices(Intent intent,
2159 String resolvedType, int flags) {
2160 ComponentName comp = intent.getComponent();
2161 if (comp != null) {
2162 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2163 ServiceInfo si = getServiceInfo(comp, flags);
2164 if (si != null) {
2165 ResolveInfo ri = new ResolveInfo();
2166 ri.serviceInfo = si;
2167 list.add(ri);
2168 }
2169 return list;
2170 }
2171
2172 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002173 String pkgName = intent.getPackage();
2174 if (pkgName == null) {
2175 return (List<ResolveInfo>)mServices.queryIntent(intent,
2176 resolvedType, flags);
2177 }
2178 PackageParser.Package pkg = mPackages.get(pkgName);
2179 if (pkg != null) {
2180 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2181 resolvedType, flags, pkg.services);
2182 }
2183 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 }
2185 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 public List<PackageInfo> getInstalledPackages(int flags) {
2188 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2189
2190 synchronized (mPackages) {
2191 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2192 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2193 while (i.hasNext()) {
2194 final PackageSetting ps = i.next();
2195 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2196 if(psPkg != null) {
2197 finalList.add(psPkg);
2198 }
2199 }
2200 }
2201 else {
2202 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2203 while (i.hasNext()) {
2204 final PackageParser.Package p = i.next();
2205 if (p.applicationInfo != null) {
2206 PackageInfo pi = generatePackageInfo(p, flags);
2207 if(pi != null) {
2208 finalList.add(pi);
2209 }
2210 }
2211 }
2212 }
2213 }
2214 return finalList;
2215 }
2216
2217 public List<ApplicationInfo> getInstalledApplications(int flags) {
2218 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2219 synchronized(mPackages) {
2220 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2221 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2222 while (i.hasNext()) {
2223 final PackageSetting ps = i.next();
2224 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2225 if(ai != null) {
2226 finalList.add(ai);
2227 }
2228 }
2229 }
2230 else {
2231 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2232 while (i.hasNext()) {
2233 final PackageParser.Package p = i.next();
2234 if (p.applicationInfo != null) {
2235 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2236 if(ai != null) {
2237 finalList.add(ai);
2238 }
2239 }
2240 }
2241 }
2242 }
2243 return finalList;
2244 }
2245
2246 public List<ApplicationInfo> getPersistentApplications(int flags) {
2247 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2248
2249 synchronized (mPackages) {
2250 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2251 while (i.hasNext()) {
2252 PackageParser.Package p = i.next();
2253 if (p.applicationInfo != null
2254 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2255 && (!mSafeMode || (p.applicationInfo.flags
2256 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2257 finalList.add(p.applicationInfo);
2258 }
2259 }
2260 }
2261
2262 return finalList;
2263 }
2264
2265 public ProviderInfo resolveContentProvider(String name, int flags) {
2266 synchronized (mPackages) {
2267 final PackageParser.Provider provider = mProviders.get(name);
2268 return provider != null
2269 && mSettings.isEnabledLP(provider.info, flags)
2270 && (!mSafeMode || (provider.info.applicationInfo.flags
2271 &ApplicationInfo.FLAG_SYSTEM) != 0)
2272 ? PackageParser.generateProviderInfo(provider, flags)
2273 : null;
2274 }
2275 }
2276
Fred Quintana718d8a22009-04-29 17:53:20 -07002277 /**
2278 * @deprecated
2279 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 public void querySyncProviders(List outNames, List outInfo) {
2281 synchronized (mPackages) {
2282 Iterator<Map.Entry<String, PackageParser.Provider>> i
2283 = mProviders.entrySet().iterator();
2284
2285 while (i.hasNext()) {
2286 Map.Entry<String, PackageParser.Provider> entry = i.next();
2287 PackageParser.Provider p = entry.getValue();
2288
2289 if (p.syncable
2290 && (!mSafeMode || (p.info.applicationInfo.flags
2291 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2292 outNames.add(entry.getKey());
2293 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2294 }
2295 }
2296 }
2297 }
2298
2299 public List<ProviderInfo> queryContentProviders(String processName,
2300 int uid, int flags) {
2301 ArrayList<ProviderInfo> finalList = null;
2302
2303 synchronized (mPackages) {
2304 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2305 while (i.hasNext()) {
2306 PackageParser.Provider p = i.next();
2307 if (p.info.authority != null
2308 && (processName == null ||
2309 (p.info.processName.equals(processName)
2310 && p.info.applicationInfo.uid == uid))
2311 && mSettings.isEnabledLP(p.info, flags)
2312 && (!mSafeMode || (p.info.applicationInfo.flags
2313 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2314 if (finalList == null) {
2315 finalList = new ArrayList<ProviderInfo>(3);
2316 }
2317 finalList.add(PackageParser.generateProviderInfo(p,
2318 flags));
2319 }
2320 }
2321 }
2322
2323 if (finalList != null) {
2324 Collections.sort(finalList, mProviderInitOrderSorter);
2325 }
2326
2327 return finalList;
2328 }
2329
2330 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2331 int flags) {
2332 synchronized (mPackages) {
2333 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2334 return PackageParser.generateInstrumentationInfo(i, flags);
2335 }
2336 }
2337
2338 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2339 int flags) {
2340 ArrayList<InstrumentationInfo> finalList =
2341 new ArrayList<InstrumentationInfo>();
2342
2343 synchronized (mPackages) {
2344 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2345 while (i.hasNext()) {
2346 PackageParser.Instrumentation p = i.next();
2347 if (targetPackage == null
2348 || targetPackage.equals(p.info.targetPackage)) {
2349 finalList.add(PackageParser.generateInstrumentationInfo(p,
2350 flags));
2351 }
2352 }
2353 }
2354
2355 return finalList;
2356 }
2357
2358 private void scanDirLI(File dir, int flags, int scanMode) {
2359 Log.d(TAG, "Scanning app dir " + dir);
2360
2361 String[] files = dir.list();
2362
2363 int i;
2364 for (i=0; i<files.length; i++) {
2365 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002366 if (!isPackageFilename(files[i])) {
2367 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002368 continue;
2369 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002370 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002372 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002373 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2374 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002375 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002376 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002377 file.delete();
2378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 }
2380 }
2381
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002382 private static File getSettingsProblemFile() {
2383 File dataDir = Environment.getDataDirectory();
2384 File systemDir = new File(dataDir, "system");
2385 File fname = new File(systemDir, "uiderrors.txt");
2386 return fname;
2387 }
2388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 private static void reportSettingsProblem(int priority, String msg) {
2390 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002391 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 FileOutputStream out = new FileOutputStream(fname, true);
2393 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002394 SimpleDateFormat formatter = new SimpleDateFormat();
2395 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2396 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 pw.close();
2398 FileUtils.setPermissions(
2399 fname.toString(),
2400 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2401 -1, -1);
2402 } catch (java.io.IOException e) {
2403 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002404 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 }
2406
2407 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2408 PackageParser.Package pkg, File srcFile, int parseFlags) {
2409 if (GET_CERTIFICATES) {
2410 if (ps == null || !ps.codePath.equals(srcFile)
2411 || ps.getTimeStamp() != srcFile.lastModified()) {
2412 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2413 if (!pp.collectCertificates(pkg, parseFlags)) {
2414 mLastScanError = pp.getParseError();
2415 return false;
2416 }
2417 }
2418 }
2419 return true;
2420 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 /*
2423 * Scan a package and return the newly parsed package.
2424 * Returns null in case of errors and the error code is stored in mLastScanError
2425 */
2426 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002427 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002429 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002431 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002434 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 if (pkg == null) {
2436 mLastScanError = pp.getParseError();
2437 return null;
2438 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002439 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 PackageSetting updatedPkg;
2441 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002442 // Look to see if we already know about this package.
2443 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002444 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002445 // This package has been renamed to its original name. Let's
2446 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002447 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002448 }
2449 // If there was no original package, see one for the real package name.
2450 if (ps == null) {
2451 ps = mSettings.peekPackageLP(pkg.packageName);
2452 }
2453 // Check to see if this package could be hiding/updating a system
2454 // package. Must look for it either under the original or real
2455 // package name depending on our state.
2456 updatedPkg = mSettings.mDisabledSysPackages.get(
2457 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002459 // First check if this is a system package that may involve an update
2460 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2461 if (!ps.codePath.equals(scanFile)) {
2462 // The path has changed from what was last scanned... check the
2463 // version of the new path against what we have stored to determine
2464 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002465 if (pkg.mVersionCode < ps.versionCode) {
2466 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002467 // Ignore entry. Skip it.
2468 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2469 + "ignored: updated version " + ps.versionCode
2470 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002471 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2472 return null;
2473 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002474 // The current app on the system partion is better than
2475 // what we have updated to on the data partition; switch
2476 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002477 // At this point, its safely assumed that package installation for
2478 // apps in system partition will go through. If not there won't be a working
2479 // version of the app
2480 synchronized (mPackages) {
2481 // Just remove the loaded entries from package lists.
2482 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002483 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002484 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002485 + "reverting from " + ps.codePathString
2486 + ": new version " + pkg.mVersionCode
2487 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002488 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2489 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002490 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 }
2493 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002494 if (updatedPkg != null) {
2495 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2496 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2497 }
2498 // Verify certificates against what was last scanned
2499 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002500 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002501 return null;
2502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 // The apk is forward locked (not public) if its code and resources
2504 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002505 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002507 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002508 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002509
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002510 String codePath = null;
2511 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002512 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2513 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002514 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002515 } else {
2516 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002517 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002518 }
2519 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002520 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002521 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002522 codePath = pkg.mScanPath;
2523 // Set application objects path explicitly.
2524 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002526 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 }
2528
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002529 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2530 String destCodePath, String destResPath) {
2531 pkg.mPath = pkg.mScanPath = destCodePath;
2532 pkg.applicationInfo.sourceDir = destCodePath;
2533 pkg.applicationInfo.publicSourceDir = destResPath;
2534 }
2535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 private static String fixProcessName(String defProcessName,
2537 String processName, int uid) {
2538 if (processName == null) {
2539 return defProcessName;
2540 }
2541 return processName;
2542 }
2543
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002544 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2546 if (pkg.mSignatures != null) {
2547 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2548 updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002549 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 + " signatures do not match the previously installed version; ignoring!");
2551 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2552 return false;
2553 }
2554
2555 if (pkgSetting.sharedUser != null) {
2556 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2557 pkg.mSignatures, updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002558 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 + " has no signatures that match those in shared user "
2560 + pkgSetting.sharedUser.name + "; ignoring!");
2561 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2562 return false;
2563 }
2564 }
2565 } else {
2566 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2567 }
2568 return true;
2569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002570
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002571 public boolean performDexOpt(String packageName) {
2572 if (!mNoDexOpt) {
2573 return false;
2574 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002575
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002576 PackageParser.Package p;
2577 synchronized (mPackages) {
2578 p = mPackages.get(packageName);
2579 if (p == null || p.mDidDexOpt) {
2580 return false;
2581 }
2582 }
2583 synchronized (mInstallLock) {
2584 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2585 }
2586 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002587
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002588 static final int DEX_OPT_SKIPPED = 0;
2589 static final int DEX_OPT_PERFORMED = 1;
2590 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002591
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002592 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2593 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002594 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002595 String path = pkg.mScanPath;
2596 int ret = 0;
2597 try {
2598 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002599 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002600 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002601 pkg.mDidDexOpt = true;
2602 performed = true;
2603 }
2604 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002605 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002606 ret = -1;
2607 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002608 Slog.w(TAG, "Exception reading apk: " + path, e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002609 ret = -1;
2610 }
2611 if (ret < 0) {
2612 //error from installer
2613 return DEX_OPT_FAILED;
2614 }
2615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002616
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002617 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2618 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002619
2620 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2621 return Environment.isEncryptedFilesystemEnabled() &&
2622 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2623 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002624
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002625 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2626 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002627 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002628 + " to " + newPkg.packageName
2629 + ": old package not in system partition");
2630 return false;
2631 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002632 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002633 + " to " + newPkg.packageName
2634 + ": old package still exists");
2635 return false;
2636 }
2637 return true;
2638 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002639
2640 private File getDataPathForPackage(PackageParser.Package pkg) {
2641 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2642 File dataPath;
2643 if (useEncryptedFSDir) {
2644 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2645 } else {
2646 dataPath = new File(mAppDataDir, pkg.packageName);
2647 }
2648 return dataPath;
2649 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002650
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002651 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2652 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002653 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002654 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2655 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002656 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002657 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002658 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2659 return null;
2660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 mScanningPath = scanFile;
2662 if (pkg == null) {
2663 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2664 return null;
2665 }
2666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2668 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2669 }
2670
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002671 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 synchronized (mPackages) {
2673 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002674 Slog.w(TAG, "*************************************************");
2675 Slog.w(TAG, "Core android package being redefined. Skipping.");
2676 Slog.w(TAG, " file=" + mScanningPath);
2677 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2679 return null;
2680 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 // Set up information for our fall-back user intent resolution
2683 // activity.
2684 mPlatformPackage = pkg;
2685 pkg.mVersionCode = mSdkVersion;
2686 mAndroidApplication = pkg.applicationInfo;
2687 mResolveActivity.applicationInfo = mAndroidApplication;
2688 mResolveActivity.name = ResolverActivity.class.getName();
2689 mResolveActivity.packageName = mAndroidApplication.packageName;
2690 mResolveActivity.processName = mAndroidApplication.processName;
2691 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2692 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2693 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2694 mResolveActivity.exported = true;
2695 mResolveActivity.enabled = true;
2696 mResolveInfo.activityInfo = mResolveActivity;
2697 mResolveInfo.priority = 0;
2698 mResolveInfo.preferredOrder = 0;
2699 mResolveInfo.match = 0;
2700 mResolveComponentName = new ComponentName(
2701 mAndroidApplication.packageName, mResolveActivity.name);
2702 }
2703 }
2704
2705 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002706 TAG, "Scanning package " + pkg.packageName);
2707 if (mPackages.containsKey(pkg.packageName)
2708 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002709 Slog.w(TAG, "*************************************************");
2710 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002712 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2714 return null;
2715 }
2716
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002717 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002718 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2719 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 SharedUserSetting suid = null;
2722 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002723
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002724 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2725 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002726 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002727 pkg.mRealPackage = null;
2728 pkg.mAdoptPermissions = null;
2729 }
2730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 synchronized (mPackages) {
2732 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002733 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2734 if (mTmpSharedLibraries == null ||
2735 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2736 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2737 }
2738 int num = 0;
2739 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2740 for (int i=0; i<N; i++) {
2741 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002743 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002745 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2747 return null;
2748 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002749 mTmpSharedLibraries[num] = file;
2750 num++;
2751 }
2752 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2753 for (int i=0; i<N; i++) {
2754 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2755 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002756 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002757 + " desires unavailable shared library "
2758 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2759 } else {
2760 mTmpSharedLibraries[num] = file;
2761 num++;
2762 }
2763 }
2764 if (num > 0) {
2765 pkg.usesLibraryFiles = new String[num];
2766 System.arraycopy(mTmpSharedLibraries, 0,
2767 pkg.usesLibraryFiles, 0, num);
2768 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002769
Dianne Hackborn49237342009-08-27 20:08:01 -07002770 if (pkg.reqFeatures != null) {
2771 N = pkg.reqFeatures.size();
2772 for (int i=0; i<N; i++) {
2773 FeatureInfo fi = pkg.reqFeatures.get(i);
2774 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2775 // Don't care.
2776 continue;
2777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002778
Dianne Hackborn49237342009-08-27 20:08:01 -07002779 if (fi.name != null) {
2780 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002781 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002782 + " requires unavailable feature "
2783 + fi.name + "; failing!");
2784 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2785 return null;
2786 }
2787 }
2788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 }
2790 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 if (pkg.mSharedUserId != null) {
2793 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2794 pkg.applicationInfo.flags, true);
2795 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002796 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 + " for shared user failed");
2798 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2799 return null;
2800 }
2801 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2802 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2803 + suid.userId + "): packages=" + suid.packages);
2804 }
2805 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002806
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002807 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002808 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002809 Log.w(TAG, "WAITING FOR DEBUGGER");
2810 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002811 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2812 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002813 }
2814 }
2815
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002816 // Check if we are renaming from an original package name.
2817 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002818 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002819 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002820 // This package may need to be renamed to a previously
2821 // installed name. Let's check on that...
2822 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002823 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002824 // This package had originally been installed as the
2825 // original name, and we have already taken care of
2826 // transitioning to the new one. Just update the new
2827 // one to continue using the old name.
2828 realName = pkg.mRealPackage;
2829 if (!pkg.packageName.equals(renamed)) {
2830 // Callers into this function may have already taken
2831 // care of renaming the package; only do it here if
2832 // it is not already done.
2833 pkg.setPackageName(renamed);
2834 }
2835
Dianne Hackbornc1552392010-03-03 16:19:01 -08002836 } else {
2837 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2838 if ((origPackage=mSettings.peekPackageLP(
2839 pkg.mOriginalPackages.get(i))) != null) {
2840 // We do have the package already installed under its
2841 // original name... should we use it?
2842 if (!verifyPackageUpdate(origPackage, pkg)) {
2843 // New package is not compatible with original.
2844 origPackage = null;
2845 continue;
2846 } else if (origPackage.sharedUser != null) {
2847 // Make sure uid is compatible between packages.
2848 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002849 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002850 + " to " + pkg.packageName + ": old uid "
2851 + origPackage.sharedUser.name
2852 + " differs from " + pkg.mSharedUserId);
2853 origPackage = null;
2854 continue;
2855 }
2856 } else {
2857 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2858 + pkg.packageName + " to old name " + origPackage.name);
2859 }
2860 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002861 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002862 }
2863 }
2864 }
2865
2866 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002867 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002868 + " was transferred to another, but its .apk remains");
2869 }
2870
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002871 // Just create the setting, don't add it yet. For already existing packages
2872 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002873 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 destResourceFile, pkg.applicationInfo.flags, true, false);
2875 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002876 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2878 return null;
2879 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002880
2881 if (pkgSetting.origPackage != null) {
2882 // If we are first transitioning from an original package,
2883 // fix up the new package's name now. We need to do this after
2884 // looking up the package under its new name, so getPackageLP
2885 // can take care of fiddling things correctly.
2886 pkg.setPackageName(origPackage.name);
2887
2888 // File a report about this.
2889 String msg = "New package " + pkgSetting.realName
2890 + " renamed to replace old package " + pkgSetting.name;
2891 reportSettingsProblem(Log.WARN, msg);
2892
2893 // Make a note of it.
2894 mTransferedPackages.add(origPackage.name);
2895
2896 // No longer need to retain this.
2897 pkgSetting.origPackage = null;
2898 }
2899
2900 if (realName != null) {
2901 // Make a note of it.
2902 mTransferedPackages.add(pkg.packageName);
2903 }
2904
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002905 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 pkg.applicationInfo.uid = pkgSetting.userId;
2910 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002911
2912 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002914 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2916 return null;
2917 }
2918 // The signature has changed, but this package is in the system
2919 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002920 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 // However... if this package is part of a shared user, but it
2922 // doesn't match the signature of the shared user, let's fail.
2923 // What this means is that you can't change the signatures
2924 // associated with an overall shared user, which doesn't seem all
2925 // that unreasonable.
2926 if (pkgSetting.sharedUser != null) {
2927 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2928 pkg.mSignatures, false)) {
2929 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2930 return null;
2931 }
2932 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002933 // File a report about this.
2934 String msg = "System package " + pkg.packageName
2935 + " signature changed; retaining data.";
2936 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002938
The Android Open Source Project10592532009-03-18 17:39:46 -07002939 // Verify that this new package doesn't have any content providers
2940 // that conflict with existing packages. Only do this if the
2941 // package isn't already installed, since we don't want to break
2942 // things that are installed.
2943 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2944 int N = pkg.providers.size();
2945 int i;
2946 for (i=0; i<N; i++) {
2947 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002948 if (p.info.authority != null) {
2949 String names[] = p.info.authority.split(";");
2950 for (int j = 0; j < names.length; j++) {
2951 if (mProviders.containsKey(names[j])) {
2952 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002953 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002954 " (in package " + pkg.applicationInfo.packageName +
2955 ") is already used by "
2956 + ((other != null && other.getComponentName() != null)
2957 ? other.getComponentName().getPackageName() : "?"));
2958 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2959 return null;
2960 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002961 }
2962 }
2963 }
2964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 }
2966
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002967 final String pkgName = pkg.packageName;
2968
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002969 if (pkg.mAdoptPermissions != null) {
2970 // This package wants to adopt ownership of permissions from
2971 // another package.
2972 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2973 String origName = pkg.mAdoptPermissions.get(i);
2974 PackageSetting orig = mSettings.peekPackageLP(origName);
2975 if (orig != null) {
2976 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002977 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002978 + origName + " to " + pkg.packageName);
2979 mSettings.transferPermissions(origName, pkg.packageName);
2980 }
2981 }
2982 }
2983 }
2984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 long scanFileTime = scanFile.lastModified();
2986 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2987 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2988 pkg.applicationInfo.processName = fixProcessName(
2989 pkg.applicationInfo.packageName,
2990 pkg.applicationInfo.processName,
2991 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992
2993 File dataPath;
2994 if (mPlatformPackage == pkg) {
2995 // The system package is special.
2996 dataPath = new File (Environment.getDataDirectory(), "system");
2997 pkg.applicationInfo.dataDir = dataPath.getPath();
2998 } else {
2999 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003000 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003001 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003002
3003 boolean uidError = false;
3004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 if (dataPath.exists()) {
3006 mOutPermissions[1] = 0;
3007 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3008 if (mOutPermissions[1] == pkg.applicationInfo.uid
3009 || !Process.supportsProcesses()) {
3010 pkg.applicationInfo.dataDir = dataPath.getPath();
3011 } else {
3012 boolean recovered = false;
3013 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3014 // If this is a system app, we can at least delete its
3015 // current data so the application will still work.
3016 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003017 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003018 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 // Old data gone!
3020 String msg = "System package " + pkg.packageName
3021 + " has changed from uid: "
3022 + mOutPermissions[1] + " to "
3023 + pkg.applicationInfo.uid + "; old data erased";
3024 reportSettingsProblem(Log.WARN, msg);
3025 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003028 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 pkg.applicationInfo.uid);
3030 if (ret == -1) {
3031 // Ack should not happen!
3032 msg = "System package " + pkg.packageName
3033 + " could not have data directory re-created after delete.";
3034 reportSettingsProblem(Log.WARN, msg);
3035 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3036 return null;
3037 }
3038 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 if (!recovered) {
3041 mHasSystemUidErrors = true;
3042 }
3043 }
3044 if (!recovered) {
3045 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3046 + pkg.applicationInfo.uid + "/fs_"
3047 + mOutPermissions[1];
3048 String msg = "Package " + pkg.packageName
3049 + " has mismatched uid: "
3050 + mOutPermissions[1] + " on disk, "
3051 + pkg.applicationInfo.uid + " in settings";
3052 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003053 mSettings.mReadMessages.append(msg);
3054 mSettings.mReadMessages.append('\n');
3055 uidError = true;
3056 if (!pkgSetting.uidError) {
3057 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 }
3060 }
3061 }
3062 pkg.applicationInfo.dataDir = dataPath.getPath();
3063 } else {
3064 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3065 Log.v(TAG, "Want this data dir: " + dataPath);
3066 //invoke installer to do the actual installation
3067 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003068 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 pkg.applicationInfo.uid);
3070 if(ret < 0) {
3071 // Error from installer
3072 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3073 return null;
3074 }
3075 } else {
3076 dataPath.mkdirs();
3077 if (dataPath.exists()) {
3078 FileUtils.setPermissions(
3079 dataPath.toString(),
3080 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3081 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3082 }
3083 }
3084 if (dataPath.exists()) {
3085 pkg.applicationInfo.dataDir = dataPath.getPath();
3086 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003087 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 pkg.applicationInfo.dataDir = null;
3089 }
3090 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003091
3092 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 }
3094
3095 // Perform shared library installation and dex validation and
3096 // optimization, if this is not a system app.
3097 if (mInstaller != null) {
3098 String path = scanFile.getPath();
3099 if (scanFileNewer) {
3100 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003101 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3102 if (err != PackageManager.INSTALL_SUCCEEDED) {
3103 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 return null;
3105 }
3106 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003107 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003108
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003109 if ((scanMode&SCAN_NO_DEX) == 0) {
3110 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3112 return null;
3113 }
3114 }
3115 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117 if (mFactoryTest && pkg.requestedPermissions.contains(
3118 android.Manifest.permission.FACTORY_TEST)) {
3119 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3120 }
3121
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003122 // Request the ActivityManager to kill the process(only for existing packages)
3123 // so that we do not end up in a confused state while the user is still using the older
3124 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003125 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003126 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003127 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003128 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003131 // We don't expect installation to fail beyond this point,
3132 if ((scanMode&SCAN_MONITOR) != 0) {
3133 mAppDirs.put(pkg.mPath, pkg);
3134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003136 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003138 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003139 // Make sure we don't accidentally delete its data.
3140 mSettings.mPackagesToBeCleaned.remove(pkgName);
3141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 int N = pkg.providers.size();
3143 StringBuilder r = null;
3144 int i;
3145 for (i=0; i<N; i++) {
3146 PackageParser.Provider p = pkg.providers.get(i);
3147 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3148 p.info.processName, pkg.applicationInfo.uid);
3149 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3150 p.info.name), p);
3151 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003152 if (p.info.authority != null) {
3153 String names[] = p.info.authority.split(";");
3154 p.info.authority = null;
3155 for (int j = 0; j < names.length; j++) {
3156 if (j == 1 && p.syncable) {
3157 // We only want the first authority for a provider to possibly be
3158 // syncable, so if we already added this provider using a different
3159 // authority clear the syncable flag. We copy the provider before
3160 // changing it because the mProviders object contains a reference
3161 // to a provider that we don't want to change.
3162 // Only do this for the second authority since the resulting provider
3163 // object can be the same for all future authorities for this provider.
3164 p = new PackageParser.Provider(p);
3165 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003167 if (!mProviders.containsKey(names[j])) {
3168 mProviders.put(names[j], p);
3169 if (p.info.authority == null) {
3170 p.info.authority = names[j];
3171 } else {
3172 p.info.authority = p.info.authority + ";" + names[j];
3173 }
3174 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3175 Log.d(TAG, "Registered content provider: " + names[j] +
3176 ", className = " + p.info.name +
3177 ", isSyncable = " + p.info.isSyncable);
3178 } else {
3179 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003180 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003181 " (in package " + pkg.applicationInfo.packageName +
3182 "): name already used by "
3183 + ((other != null && other.getComponentName() != null)
3184 ? other.getComponentName().getPackageName() : "?"));
3185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 }
3187 }
3188 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3189 if (r == null) {
3190 r = new StringBuilder(256);
3191 } else {
3192 r.append(' ');
3193 }
3194 r.append(p.info.name);
3195 }
3196 }
3197 if (r != null) {
3198 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3199 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 N = pkg.services.size();
3202 r = null;
3203 for (i=0; i<N; i++) {
3204 PackageParser.Service s = pkg.services.get(i);
3205 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3206 s.info.processName, pkg.applicationInfo.uid);
3207 mServices.addService(s);
3208 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3209 if (r == null) {
3210 r = new StringBuilder(256);
3211 } else {
3212 r.append(' ');
3213 }
3214 r.append(s.info.name);
3215 }
3216 }
3217 if (r != null) {
3218 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3219 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 N = pkg.receivers.size();
3222 r = null;
3223 for (i=0; i<N; i++) {
3224 PackageParser.Activity a = pkg.receivers.get(i);
3225 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3226 a.info.processName, pkg.applicationInfo.uid);
3227 mReceivers.addActivity(a, "receiver");
3228 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3229 if (r == null) {
3230 r = new StringBuilder(256);
3231 } else {
3232 r.append(' ');
3233 }
3234 r.append(a.info.name);
3235 }
3236 }
3237 if (r != null) {
3238 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3239 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241 N = pkg.activities.size();
3242 r = null;
3243 for (i=0; i<N; i++) {
3244 PackageParser.Activity a = pkg.activities.get(i);
3245 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3246 a.info.processName, pkg.applicationInfo.uid);
3247 mActivities.addActivity(a, "activity");
3248 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3249 if (r == null) {
3250 r = new StringBuilder(256);
3251 } else {
3252 r.append(' ');
3253 }
3254 r.append(a.info.name);
3255 }
3256 }
3257 if (r != null) {
3258 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3259 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 N = pkg.permissionGroups.size();
3262 r = null;
3263 for (i=0; i<N; i++) {
3264 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3265 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3266 if (cur == null) {
3267 mPermissionGroups.put(pg.info.name, pg);
3268 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3269 if (r == null) {
3270 r = new StringBuilder(256);
3271 } else {
3272 r.append(' ');
3273 }
3274 r.append(pg.info.name);
3275 }
3276 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003277 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 + pg.info.packageName + " ignored: original from "
3279 + cur.info.packageName);
3280 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3281 if (r == null) {
3282 r = new StringBuilder(256);
3283 } else {
3284 r.append(' ');
3285 }
3286 r.append("DUP:");
3287 r.append(pg.info.name);
3288 }
3289 }
3290 }
3291 if (r != null) {
3292 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3293 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 N = pkg.permissions.size();
3296 r = null;
3297 for (i=0; i<N; i++) {
3298 PackageParser.Permission p = pkg.permissions.get(i);
3299 HashMap<String, BasePermission> permissionMap =
3300 p.tree ? mSettings.mPermissionTrees
3301 : mSettings.mPermissions;
3302 p.group = mPermissionGroups.get(p.info.group);
3303 if (p.info.group == null || p.group != null) {
3304 BasePermission bp = permissionMap.get(p.info.name);
3305 if (bp == null) {
3306 bp = new BasePermission(p.info.name, p.info.packageName,
3307 BasePermission.TYPE_NORMAL);
3308 permissionMap.put(p.info.name, bp);
3309 }
3310 if (bp.perm == null) {
3311 if (bp.sourcePackage == null
3312 || bp.sourcePackage.equals(p.info.packageName)) {
3313 BasePermission tree = findPermissionTreeLP(p.info.name);
3314 if (tree == null
3315 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003316 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 bp.perm = p;
3318 bp.uid = pkg.applicationInfo.uid;
3319 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3320 if (r == null) {
3321 r = new StringBuilder(256);
3322 } else {
3323 r.append(' ');
3324 }
3325 r.append(p.info.name);
3326 }
3327 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003328 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 + p.info.packageName + " ignored: base tree "
3330 + tree.name + " is from package "
3331 + tree.sourcePackage);
3332 }
3333 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003334 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 + p.info.packageName + " ignored: original from "
3336 + bp.sourcePackage);
3337 }
3338 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3339 if (r == null) {
3340 r = new StringBuilder(256);
3341 } else {
3342 r.append(' ');
3343 }
3344 r.append("DUP:");
3345 r.append(p.info.name);
3346 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003347 if (bp.perm == p) {
3348 bp.protectionLevel = p.info.protectionLevel;
3349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003351 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 + p.info.packageName + " ignored: no group "
3353 + p.group);
3354 }
3355 }
3356 if (r != null) {
3357 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3358 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 N = pkg.instrumentation.size();
3361 r = null;
3362 for (i=0; i<N; i++) {
3363 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3364 a.info.packageName = pkg.applicationInfo.packageName;
3365 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3366 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3367 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003368 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3370 if (r == null) {
3371 r = new StringBuilder(256);
3372 } else {
3373 r.append(' ');
3374 }
3375 r.append(a.info.name);
3376 }
3377 }
3378 if (r != null) {
3379 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3380 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003381
Dianne Hackborn854060af2009-07-09 18:14:31 -07003382 if (pkg.protectedBroadcasts != null) {
3383 N = pkg.protectedBroadcasts.size();
3384 for (i=0; i<N; i++) {
3385 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3386 }
3387 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 pkgSetting.setTimeStamp(scanFileTime);
3390 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 return pkg;
3393 }
3394
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003395 private void killApplication(String pkgName, int uid) {
3396 // Request the ActivityManager to kill the process(only for existing packages)
3397 // so that we do not end up in a confused state while the user is still using the older
3398 // version of the application while the new one gets installed.
3399 IActivityManager am = ActivityManagerNative.getDefault();
3400 if (am != null) {
3401 try {
3402 am.killApplicationWithUid(pkgName, uid);
3403 } catch (RemoteException e) {
3404 }
3405 }
3406 }
3407
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003408 // The following constants are returned by cachePackageSharedLibsForAbiLI
3409 // to indicate if native shared libraries were found in the package.
3410 // Values are:
3411 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3412 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3413 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3414 // in package (and not installed)
3415 //
3416 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3417 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3418 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003420 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3421 // and automatically copy them to /data/data/<appname>/lib if present.
3422 //
3423 // NOTE: this method may throw an IOException if the library cannot
3424 // be copied to its final destination, e.g. if there isn't enough
3425 // room left on the data partition, or a ZipException if the package
3426 // file is malformed.
3427 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003428 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3429 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003430 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3431 final String apkLib = "lib/";
3432 final int apkLibLen = apkLib.length();
3433 final int cpuAbiLen = cpuAbi.length();
3434 final String libPrefix = "lib";
3435 final int libPrefixLen = libPrefix.length();
3436 final String libSuffix = ".so";
3437 final int libSuffixLen = libSuffix.length();
3438 boolean hasNativeLibraries = false;
3439 boolean installedNativeLibraries = false;
3440
3441 // the minimum length of a valid native shared library of the form
3442 // lib/<something>/lib<name>.so.
3443 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3444
3445 ZipFile zipFile = new ZipFile(scanFile);
3446 Enumeration<ZipEntry> entries =
3447 (Enumeration<ZipEntry>) zipFile.entries();
3448
3449 while (entries.hasMoreElements()) {
3450 ZipEntry entry = entries.nextElement();
3451 // skip directories
3452 if (entry.isDirectory()) {
3453 continue;
3454 }
3455 String entryName = entry.getName();
3456
3457 // check that the entry looks like lib/<something>/lib<name>.so
3458 // here, but don't check the ABI just yet.
3459 //
3460 // - must be sufficiently long
3461 // - must end with libSuffix, i.e. ".so"
3462 // - must start with apkLib, i.e. "lib/"
3463 if (entryName.length() < minEntryLen ||
3464 !entryName.endsWith(libSuffix) ||
3465 !entryName.startsWith(apkLib) ) {
3466 continue;
3467 }
3468
3469 // file name must start with libPrefix, i.e. "lib"
3470 int lastSlash = entryName.lastIndexOf('/');
3471
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003472 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003473 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3474 continue;
3475 }
3476
3477 hasNativeLibraries = true;
3478
3479 // check the cpuAbi now, between lib/ and /lib<name>.so
3480 //
3481 if (lastSlash != apkLibLen + cpuAbiLen ||
3482 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3483 continue;
3484
3485 // extract the library file name, ensure it doesn't contain
3486 // weird characters. we're guaranteed here that it doesn't contain
3487 // a directory separator though.
3488 String libFileName = entryName.substring(lastSlash+1);
3489 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3490 continue;
3491 }
3492
3493 installedNativeLibraries = true;
3494
3495 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3496 File.separator + libFileName;
3497 File sharedLibraryFile = new File(sharedLibraryFilePath);
3498 if (! sharedLibraryFile.exists() ||
3499 sharedLibraryFile.length() != entry.getSize() ||
3500 sharedLibraryFile.lastModified() != entry.getTime()) {
3501 if (Config.LOGD) {
3502 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003504 if (mInstaller == null) {
3505 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003506 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003507 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003508 sharedLibraryFile);
3509 }
3510 }
3511 if (!hasNativeLibraries)
3512 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3513
3514 if (!installedNativeLibraries)
3515 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3516
3517 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3518 }
3519
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003520 // Find the gdbserver executable program in a package at
3521 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3522 //
3523 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3524 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3525 //
3526 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3527 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3528 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3529 final String GDBSERVER = "gdbserver";
3530 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3531
3532 ZipFile zipFile = new ZipFile(scanFile);
3533 Enumeration<ZipEntry> entries =
3534 (Enumeration<ZipEntry>) zipFile.entries();
3535
3536 while (entries.hasMoreElements()) {
3537 ZipEntry entry = entries.nextElement();
3538 // skip directories
3539 if (entry.isDirectory()) {
3540 continue;
3541 }
3542 String entryName = entry.getName();
3543
3544 if (!entryName.equals(apkGdbServerPath)) {
3545 continue;
3546 }
3547
3548 String installGdbServerPath = installGdbServerDir.getPath() +
3549 "/" + GDBSERVER;
3550 File installGdbServerFile = new File(installGdbServerPath);
3551 if (! installGdbServerFile.exists() ||
3552 installGdbServerFile.length() != entry.getSize() ||
3553 installGdbServerFile.lastModified() != entry.getTime()) {
3554 if (Config.LOGD) {
3555 Log.d(TAG, "Caching gdbserver " + entry.getName());
3556 }
3557 if (mInstaller == null) {
3558 installGdbServerDir.mkdir();
3559 }
3560 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3561 installGdbServerFile);
3562 }
3563 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3564 }
3565 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3566 }
3567
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003568 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3569 // and copy them to /data/data/<appname>/lib.
3570 //
3571 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3572 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3573 // one if ro.product.cpu.abi2 is defined.
3574 //
3575 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3576 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003577 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003578 try {
3579 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3580
3581 // some architectures are capable of supporting several CPU ABIs
3582 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3583 // this is indicated by the definition of the ro.product.cpu.abi2
3584 // system property.
3585 //
3586 // only scan the package twice in case of ABI mismatch
3587 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003588 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003589 if (cpuAbi2 != null) {
3590 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003592
3593 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003594 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003595 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003597
3598 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3599 cpuAbi = cpuAbi2;
3600 }
3601 }
3602
3603 // for debuggable packages, also extract gdbserver from lib/<abi>
3604 // into /data/data/<appname>/lib too.
3605 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3606 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3607 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3608 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3609 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003612 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003613 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003614 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003616 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003617 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003619 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 }
3621
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003622 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003624 File binaryDir,
3625 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 InputStream inputStream = zipFile.getInputStream(entry);
3627 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003628 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003630 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 // now need to be left as world readable and owned by the system.
3632 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3633 ! tempFile.setLastModified(entry.getTime()) ||
3634 FileUtils.setPermissions(tempFilePath,
3635 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003636 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003638 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 // Failed to properly write file.
3640 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003641 throw new IOException("Couldn't create cached binary "
3642 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 }
3644 } finally {
3645 inputStream.close();
3646 }
3647 }
3648
3649 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3650 if (chatty && Config.LOGD) Log.d(
3651 TAG, "Removing package " + pkg.applicationInfo.packageName );
3652
3653 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 mPackages.remove(pkg.applicationInfo.packageName);
3657 if (pkg.mPath != null) {
3658 mAppDirs.remove(pkg.mPath);
3659 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 PackageSetting ps = (PackageSetting)pkg.mExtras;
3662 if (ps != null && ps.sharedUser != null) {
3663 // XXX don't do this until the data is removed.
3664 if (false) {
3665 ps.sharedUser.packages.remove(ps);
3666 if (ps.sharedUser.packages.size() == 0) {
3667 // Remove.
3668 }
3669 }
3670 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 int N = pkg.providers.size();
3673 StringBuilder r = null;
3674 int i;
3675 for (i=0; i<N; i++) {
3676 PackageParser.Provider p = pkg.providers.get(i);
3677 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3678 p.info.name));
3679 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 /* The is another ContentProvider with this authority when
3682 * this app was installed so this authority is null,
3683 * Ignore it as we don't have to unregister the provider.
3684 */
3685 continue;
3686 }
3687 String names[] = p.info.authority.split(";");
3688 for (int j = 0; j < names.length; j++) {
3689 if (mProviders.get(names[j]) == p) {
3690 mProviders.remove(names[j]);
3691 if (chatty && Config.LOGD) Log.d(
3692 TAG, "Unregistered content provider: " + names[j] +
3693 ", className = " + p.info.name +
3694 ", isSyncable = " + p.info.isSyncable);
3695 }
3696 }
3697 if (chatty) {
3698 if (r == null) {
3699 r = new StringBuilder(256);
3700 } else {
3701 r.append(' ');
3702 }
3703 r.append(p.info.name);
3704 }
3705 }
3706 if (r != null) {
3707 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 N = pkg.services.size();
3711 r = null;
3712 for (i=0; i<N; i++) {
3713 PackageParser.Service s = pkg.services.get(i);
3714 mServices.removeService(s);
3715 if (chatty) {
3716 if (r == null) {
3717 r = new StringBuilder(256);
3718 } else {
3719 r.append(' ');
3720 }
3721 r.append(s.info.name);
3722 }
3723 }
3724 if (r != null) {
3725 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728 N = pkg.receivers.size();
3729 r = null;
3730 for (i=0; i<N; i++) {
3731 PackageParser.Activity a = pkg.receivers.get(i);
3732 mReceivers.removeActivity(a, "receiver");
3733 if (chatty) {
3734 if (r == null) {
3735 r = new StringBuilder(256);
3736 } else {
3737 r.append(' ');
3738 }
3739 r.append(a.info.name);
3740 }
3741 }
3742 if (r != null) {
3743 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 N = pkg.activities.size();
3747 r = null;
3748 for (i=0; i<N; i++) {
3749 PackageParser.Activity a = pkg.activities.get(i);
3750 mActivities.removeActivity(a, "activity");
3751 if (chatty) {
3752 if (r == null) {
3753 r = new StringBuilder(256);
3754 } else {
3755 r.append(' ');
3756 }
3757 r.append(a.info.name);
3758 }
3759 }
3760 if (r != null) {
3761 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3762 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 N = pkg.permissions.size();
3765 r = null;
3766 for (i=0; i<N; i++) {
3767 PackageParser.Permission p = pkg.permissions.get(i);
3768 boolean tree = false;
3769 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3770 if (bp == null) {
3771 tree = true;
3772 bp = mSettings.mPermissionTrees.get(p.info.name);
3773 }
3774 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003775 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 if (chatty) {
3777 if (r == null) {
3778 r = new StringBuilder(256);
3779 } else {
3780 r.append(' ');
3781 }
3782 r.append(p.info.name);
3783 }
3784 }
3785 }
3786 if (r != null) {
3787 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3788 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 N = pkg.instrumentation.size();
3791 r = null;
3792 for (i=0; i<N; i++) {
3793 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003794 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 if (chatty) {
3796 if (r == null) {
3797 r = new StringBuilder(256);
3798 } else {
3799 r.append(' ');
3800 }
3801 r.append(a.info.name);
3802 }
3803 }
3804 if (r != null) {
3805 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3806 }
3807 }
3808 }
3809
3810 private static final boolean isPackageFilename(String name) {
3811 return name != null && name.endsWith(".apk");
3812 }
3813
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003814 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3815 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3816 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3817 return true;
3818 }
3819 }
3820 return false;
3821 }
3822
3823 private void updatePermissionsLP(String changingPkg,
3824 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 // Make sure there are no dangling permission trees.
3826 Iterator<BasePermission> it = mSettings.mPermissionTrees
3827 .values().iterator();
3828 while (it.hasNext()) {
3829 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003830 if (bp.packageSetting == null) {
3831 // We may not yet have parsed the package, so just see if
3832 // we still know about its settings.
3833 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3834 }
3835 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003836 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 + " from package " + bp.sourcePackage);
3838 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003839 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3840 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3841 Slog.i(TAG, "Removing old permission tree: " + bp.name
3842 + " from package " + bp.sourcePackage);
3843 grantPermissions = true;
3844 it.remove();
3845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 }
3847 }
3848
3849 // Make sure all dynamic permissions have been assigned to a package,
3850 // and make sure there are no dangling permissions.
3851 it = mSettings.mPermissions.values().iterator();
3852 while (it.hasNext()) {
3853 BasePermission bp = it.next();
3854 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3855 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3856 + bp.name + " pkg=" + bp.sourcePackage
3857 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003858 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 BasePermission tree = findPermissionTreeLP(bp.name);
3860 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003861 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 bp.perm = new PackageParser.Permission(tree.perm.owner,
3863 new PermissionInfo(bp.pendingInfo));
3864 bp.perm.info.packageName = tree.perm.info.packageName;
3865 bp.perm.info.name = bp.name;
3866 bp.uid = tree.uid;
3867 }
3868 }
3869 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003870 if (bp.packageSetting == null) {
3871 // We may not yet have parsed the package, so just see if
3872 // we still know about its settings.
3873 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3874 }
3875 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003876 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 + " from package " + bp.sourcePackage);
3878 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003879 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3880 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3881 Slog.i(TAG, "Removing old permission: " + bp.name
3882 + " from package " + bp.sourcePackage);
3883 grantPermissions = true;
3884 it.remove();
3885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 }
3887 }
3888
3889 // Now update the permissions for all packages, in particular
3890 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003891 if (grantPermissions) {
3892 for (PackageParser.Package pkg : mPackages.values()) {
3893 if (pkg != pkgInfo) {
3894 grantPermissionsLP(pkg, false);
3895 }
3896 }
3897 }
3898
3899 if (pkgInfo != null) {
3900 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 }
3902 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3905 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3906 if (ps == null) {
3907 return;
3908 }
3909 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003910 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 if (replace) {
3913 ps.permissionsFixed = false;
3914 if (gp == ps) {
3915 gp.grantedPermissions.clear();
3916 gp.gids = mGlobalGids;
3917 }
3918 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 if (gp.gids == null) {
3921 gp.gids = mGlobalGids;
3922 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 final int N = pkg.requestedPermissions.size();
3925 for (int i=0; i<N; i++) {
3926 String name = pkg.requestedPermissions.get(i);
3927 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 if (false) {
3929 if (gp != ps) {
3930 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003931 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 }
3933 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003934 if (bp != null && bp.packageSetting != null) {
3935 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003937 boolean allowedSig = false;
3938 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3939 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 allowed = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003941 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3942 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3943 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003945 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003947 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3949 // For updated system applications, the signatureOrSystem permission
3950 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003951 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3953 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3954 if(sysPs.grantedPermissions.contains(perm)) {
3955 allowed = true;
3956 } else {
3957 allowed = false;
3958 }
3959 } else {
3960 allowed = true;
3961 }
3962 }
3963 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003964 if (allowed) {
3965 allowedSig = true;
3966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 } else {
3968 allowed = false;
3969 }
3970 if (false) {
3971 if (gp != ps) {
3972 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3973 }
3974 }
3975 if (allowed) {
3976 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3977 && ps.permissionsFixed) {
3978 // If this is an existing, non-system package, then
3979 // we can't add any new permissions to it.
Dianne 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);
4004 }
4005 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004006 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 + " to package " + pkg.packageName
4008 + " because it was previously installed without");
4009 }
4010 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004011 if (gp.grantedPermissions.remove(perm)) {
4012 changedPermission = true;
4013 gp.gids = removeInts(gp.gids, bp.gids);
4014 Slog.i(TAG, "Un-granting permission " + perm
4015 + " from package " + pkg.packageName
4016 + " (protectionLevel=" + bp.protectionLevel
4017 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4018 + ")");
4019 } else {
4020 Slog.w(TAG, "Not granting permission " + perm
4021 + " to package " + pkg.packageName
4022 + " (protectionLevel=" + bp.protectionLevel
4023 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4024 + ")");
4025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 }
4027 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004028 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 + " in package " + pkg.packageName);
4030 }
4031 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004032
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004033 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004034 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4035 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 // This is the first that we have heard about this package, so the
4037 // permissions we have now selected are fixed until explicitly
4038 // changed.
4039 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 }
4041 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 private final class ActivityIntentResolver
4044 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004045 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004047 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 }
4049
Mihai Preda074edef2009-05-18 17:13:31 +02004050 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004052 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4054 }
4055
Mihai Predaeae850c2009-05-13 10:13:48 +02004056 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4057 ArrayList<PackageParser.Activity> packageActivities) {
4058 if (packageActivities == null) {
4059 return null;
4060 }
4061 mFlags = flags;
4062 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4063 int N = packageActivities.size();
4064 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4065 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004066
4067 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004068 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004069 intentFilters = packageActivities.get(i).intents;
4070 if (intentFilters != null && intentFilters.size() > 0) {
4071 listCut.add(intentFilters);
4072 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004073 }
4074 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4075 }
4076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004078 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079 if (SHOW_INFO || Config.LOGV) Log.v(
4080 TAG, " " + type + " " +
4081 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4082 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4083 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004084 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4086 if (SHOW_INFO || Config.LOGV) {
4087 Log.v(TAG, " IntentFilter:");
4088 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4089 }
4090 if (!intent.debugCheck()) {
4091 Log.w(TAG, "==> For Activity " + a.info.name);
4092 }
4093 addFilter(intent);
4094 }
4095 }
4096
4097 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004098 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 if (SHOW_INFO || Config.LOGV) Log.v(
4100 TAG, " " + type + " " +
4101 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4102 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4103 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004104 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4106 if (SHOW_INFO || Config.LOGV) {
4107 Log.v(TAG, " IntentFilter:");
4108 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4109 }
4110 removeFilter(intent);
4111 }
4112 }
4113
4114 @Override
4115 protected boolean allowFilterResult(
4116 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4117 ActivityInfo filterAi = filter.activity.info;
4118 for (int i=dest.size()-1; i>=0; i--) {
4119 ActivityInfo destAi = dest.get(i).activityInfo;
4120 if (destAi.name == filterAi.name
4121 && destAi.packageName == filterAi.packageName) {
4122 return false;
4123 }
4124 }
4125 return true;
4126 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004129 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4130 return info.activity.owner.packageName;
4131 }
4132
4133 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4135 int match) {
4136 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4137 return null;
4138 }
4139 final PackageParser.Activity activity = info.activity;
4140 if (mSafeMode && (activity.info.applicationInfo.flags
4141 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4142 return null;
4143 }
4144 final ResolveInfo res = new ResolveInfo();
4145 res.activityInfo = PackageParser.generateActivityInfo(activity,
4146 mFlags);
4147 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4148 res.filter = info;
4149 }
4150 res.priority = info.getPriority();
4151 res.preferredOrder = activity.owner.mPreferredOrder;
4152 //System.out.println("Result: " + res.activityInfo.className +
4153 // " = " + res.priority);
4154 res.match = match;
4155 res.isDefault = info.hasDefault;
4156 res.labelRes = info.labelRes;
4157 res.nonLocalizedLabel = info.nonLocalizedLabel;
4158 res.icon = info.icon;
4159 return res;
4160 }
4161
4162 @Override
4163 protected void sortResults(List<ResolveInfo> results) {
4164 Collections.sort(results, mResolvePrioritySorter);
4165 }
4166
4167 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004168 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004170 out.print(prefix); out.print(
4171 Integer.toHexString(System.identityHashCode(filter.activity)));
4172 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004173 out.print(filter.activity.getComponentShortName());
4174 out.print(" filter ");
4175 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 }
4177
4178// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4179// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4180// final List<ResolveInfo> retList = Lists.newArrayList();
4181// while (i.hasNext()) {
4182// final ResolveInfo resolveInfo = i.next();
4183// if (isEnabledLP(resolveInfo.activityInfo)) {
4184// retList.add(resolveInfo);
4185// }
4186// }
4187// return retList;
4188// }
4189
4190 // Keys are String (activity class name), values are Activity.
4191 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4192 = new HashMap<ComponentName, PackageParser.Activity>();
4193 private int mFlags;
4194 }
4195
4196 private final class ServiceIntentResolver
4197 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004198 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004200 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201 }
4202
Mihai Preda074edef2009-05-18 17:13:31 +02004203 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004205 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4207 }
4208
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004209 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4210 ArrayList<PackageParser.Service> packageServices) {
4211 if (packageServices == null) {
4212 return null;
4213 }
4214 mFlags = flags;
4215 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4216 int N = packageServices.size();
4217 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4218 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4219
4220 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4221 for (int i = 0; i < N; ++i) {
4222 intentFilters = packageServices.get(i).intents;
4223 if (intentFilters != null && intentFilters.size() > 0) {
4224 listCut.add(intentFilters);
4225 }
4226 }
4227 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4228 }
4229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004231 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004232 if (SHOW_INFO || Config.LOGV) Log.v(
4233 TAG, " " + (s.info.nonLocalizedLabel != null
4234 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4235 if (SHOW_INFO || Config.LOGV) Log.v(
4236 TAG, " Class=" + s.info.name);
4237 int NI = s.intents.size();
4238 int j;
4239 for (j=0; j<NI; j++) {
4240 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4241 if (SHOW_INFO || Config.LOGV) {
4242 Log.v(TAG, " IntentFilter:");
4243 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4244 }
4245 if (!intent.debugCheck()) {
4246 Log.w(TAG, "==> For Service " + s.info.name);
4247 }
4248 addFilter(intent);
4249 }
4250 }
4251
4252 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004253 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 if (SHOW_INFO || Config.LOGV) Log.v(
4255 TAG, " " + (s.info.nonLocalizedLabel != null
4256 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4257 if (SHOW_INFO || Config.LOGV) Log.v(
4258 TAG, " Class=" + s.info.name);
4259 int NI = s.intents.size();
4260 int j;
4261 for (j=0; j<NI; j++) {
4262 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4263 if (SHOW_INFO || Config.LOGV) {
4264 Log.v(TAG, " IntentFilter:");
4265 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4266 }
4267 removeFilter(intent);
4268 }
4269 }
4270
4271 @Override
4272 protected boolean allowFilterResult(
4273 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4274 ServiceInfo filterSi = filter.service.info;
4275 for (int i=dest.size()-1; i>=0; i--) {
4276 ServiceInfo destAi = dest.get(i).serviceInfo;
4277 if (destAi.name == filterSi.name
4278 && destAi.packageName == filterSi.packageName) {
4279 return false;
4280 }
4281 }
4282 return true;
4283 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004285 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004286 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4287 return info.service.owner.packageName;
4288 }
4289
4290 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4292 int match) {
4293 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4294 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4295 return null;
4296 }
4297 final PackageParser.Service service = info.service;
4298 if (mSafeMode && (service.info.applicationInfo.flags
4299 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4300 return null;
4301 }
4302 final ResolveInfo res = new ResolveInfo();
4303 res.serviceInfo = PackageParser.generateServiceInfo(service,
4304 mFlags);
4305 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4306 res.filter = filter;
4307 }
4308 res.priority = info.getPriority();
4309 res.preferredOrder = service.owner.mPreferredOrder;
4310 //System.out.println("Result: " + res.activityInfo.className +
4311 // " = " + res.priority);
4312 res.match = match;
4313 res.isDefault = info.hasDefault;
4314 res.labelRes = info.labelRes;
4315 res.nonLocalizedLabel = info.nonLocalizedLabel;
4316 res.icon = info.icon;
4317 return res;
4318 }
4319
4320 @Override
4321 protected void sortResults(List<ResolveInfo> results) {
4322 Collections.sort(results, mResolvePrioritySorter);
4323 }
4324
4325 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004326 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004328 out.print(prefix); out.print(
4329 Integer.toHexString(System.identityHashCode(filter.service)));
4330 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004331 out.print(filter.service.getComponentShortName());
4332 out.print(" filter ");
4333 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 }
4335
4336// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4337// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4338// final List<ResolveInfo> retList = Lists.newArrayList();
4339// while (i.hasNext()) {
4340// final ResolveInfo resolveInfo = (ResolveInfo) i;
4341// if (isEnabledLP(resolveInfo.serviceInfo)) {
4342// retList.add(resolveInfo);
4343// }
4344// }
4345// return retList;
4346// }
4347
4348 // Keys are String (activity class name), values are Activity.
4349 private final HashMap<ComponentName, PackageParser.Service> mServices
4350 = new HashMap<ComponentName, PackageParser.Service>();
4351 private int mFlags;
4352 };
4353
4354 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4355 new Comparator<ResolveInfo>() {
4356 public int compare(ResolveInfo r1, ResolveInfo r2) {
4357 int v1 = r1.priority;
4358 int v2 = r2.priority;
4359 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4360 if (v1 != v2) {
4361 return (v1 > v2) ? -1 : 1;
4362 }
4363 v1 = r1.preferredOrder;
4364 v2 = r2.preferredOrder;
4365 if (v1 != v2) {
4366 return (v1 > v2) ? -1 : 1;
4367 }
4368 if (r1.isDefault != r2.isDefault) {
4369 return r1.isDefault ? -1 : 1;
4370 }
4371 v1 = r1.match;
4372 v2 = r2.match;
4373 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4374 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4375 }
4376 };
4377
4378 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4379 new Comparator<ProviderInfo>() {
4380 public int compare(ProviderInfo p1, ProviderInfo p2) {
4381 final int v1 = p1.initOrder;
4382 final int v2 = p2.initOrder;
4383 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4384 }
4385 };
4386
4387 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4388 IActivityManager am = ActivityManagerNative.getDefault();
4389 if (am != null) {
4390 try {
4391 final Intent intent = new Intent(action,
4392 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4393 if (extras != null) {
4394 intent.putExtras(extras);
4395 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004396 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397 am.broadcastIntent(
4398 null, intent,
4399 null, null, 0, null, null, null, false, false);
4400 } catch (RemoteException ex) {
4401 }
4402 }
4403 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004404
4405 public String nextPackageToClean(String lastPackage) {
4406 synchronized (mPackages) {
4407 if (!mMediaMounted) {
4408 // If the external storage is no longer mounted at this point,
4409 // the caller may not have been able to delete all of this
4410 // packages files and can not delete any more. Bail.
4411 return null;
4412 }
4413 if (lastPackage != null) {
4414 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4415 }
4416 return mSettings.mPackagesToBeCleaned.size() > 0
4417 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4418 }
4419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004421 void schedulePackageCleaning(String packageName) {
4422 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4423 }
4424
4425 void startCleaningPackages() {
4426 synchronized (mPackages) {
4427 if (!mMediaMounted) {
4428 return;
4429 }
4430 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4431 return;
4432 }
4433 }
4434 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4435 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4436 IActivityManager am = ActivityManagerNative.getDefault();
4437 if (am != null) {
4438 try {
4439 am.startService(null, intent, null);
4440 } catch (RemoteException e) {
4441 }
4442 }
4443 }
4444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 private final class AppDirObserver extends FileObserver {
4446 public AppDirObserver(String path, int mask, boolean isrom) {
4447 super(path, mask);
4448 mRootDir = path;
4449 mIsRom = isrom;
4450 }
4451
4452 public void onEvent(int event, String path) {
4453 String removedPackage = null;
4454 int removedUid = -1;
4455 String addedPackage = null;
4456 int addedUid = -1;
4457
4458 synchronized (mInstallLock) {
4459 String fullPathStr = null;
4460 File fullPath = null;
4461 if (path != null) {
4462 fullPath = new File(mRootDir, path);
4463 fullPathStr = fullPath.getPath();
4464 }
4465
4466 if (Config.LOGV) Log.v(
4467 TAG, "File " + fullPathStr + " changed: "
4468 + Integer.toHexString(event));
4469
4470 if (!isPackageFilename(path)) {
4471 if (Config.LOGV) Log.v(
4472 TAG, "Ignoring change of non-package file: " + fullPathStr);
4473 return;
4474 }
4475
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004476 // Ignore packages that are being installed or
4477 // have just been installed.
4478 if (ignoreCodePath(fullPathStr)) {
4479 return;
4480 }
4481 PackageParser.Package p = null;
4482 synchronized (mPackages) {
4483 p = mAppDirs.get(fullPathStr);
4484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004486 if (p != null) {
4487 removePackageLI(p, true);
4488 removedPackage = p.applicationInfo.packageName;
4489 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004490 }
4491 }
4492
4493 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004494 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004495 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004496 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4497 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 PackageParser.PARSE_CHATTY |
4499 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004500 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 if (p != null) {
4502 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004503 updatePermissionsLP(p.packageName, p,
4504 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 }
4506 addedPackage = p.applicationInfo.packageName;
4507 addedUid = p.applicationInfo.uid;
4508 }
4509 }
4510 }
4511
4512 synchronized (mPackages) {
4513 mSettings.writeLP();
4514 }
4515 }
4516
4517 if (removedPackage != null) {
4518 Bundle extras = new Bundle(1);
4519 extras.putInt(Intent.EXTRA_UID, removedUid);
4520 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4521 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4522 }
4523 if (addedPackage != null) {
4524 Bundle extras = new Bundle(1);
4525 extras.putInt(Intent.EXTRA_UID, addedUid);
4526 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4527 }
4528 }
4529
4530 private final String mRootDir;
4531 private final boolean mIsRom;
4532 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534 /* Called when a downloaded package installation has been confirmed by the user */
4535 public void installPackage(
4536 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004537 installPackage(packageURI, observer, flags, null);
4538 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004539
Jacek Surazski65e13172009-04-28 15:26:38 +02004540 /* Called when a downloaded package installation has been confirmed by the user */
4541 public void installPackage(
4542 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4543 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 mContext.enforceCallingOrSelfPermission(
4545 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004546
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004547 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004548 msg.obj = new InstallParams(packageURI, observer, flags,
4549 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004550 mHandler.sendMessage(msg);
4551 }
4552
Christopher Tate1bb69062010-02-19 17:02:12 -08004553 public void finishPackageInstall(int token) {
4554 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4555 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4556 mHandler.sendMessage(msg);
4557 }
4558
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004559 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004560 // Queue up an async operation since the package installation may take a little while.
4561 mHandler.post(new Runnable() {
4562 public void run() {
4563 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004564 // Result object to be returned
4565 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004566 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004567 res.uid = -1;
4568 res.pkg = null;
4569 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004570 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004571 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004572 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004573 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004574 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004575 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004577
4578 // A restore should be performed at this point if (a) the install
4579 // succeeded, (b) the operation is not an update, and (c) the new
4580 // package has a backupAgent defined.
4581 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004582 boolean doRestore = (!update
4583 && res.pkg != null
4584 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004585
4586 // Set up the post-install work request bookkeeping. This will be used
4587 // and cleaned up by the post-install event handling regardless of whether
4588 // there's a restore pass performed. Token values are >= 1.
4589 int token;
4590 if (mNextInstallToken < 0) mNextInstallToken = 1;
4591 token = mNextInstallToken++;
4592
4593 PostInstallData data = new PostInstallData(args, res);
4594 mRunningInstalls.put(token, data);
4595 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4596
4597 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4598 // Pass responsibility to the Backup Manager. It will perform a
4599 // restore if appropriate, then pass responsibility back to the
4600 // Package Manager to run the post-install observer callbacks
4601 // and broadcasts.
4602 IBackupManager bm = IBackupManager.Stub.asInterface(
4603 ServiceManager.getService(Context.BACKUP_SERVICE));
4604 if (bm != null) {
4605 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4606 + " to BM for possible restore");
4607 try {
4608 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4609 } catch (RemoteException e) {
4610 // can't happen; the backup manager is local
4611 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004612 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004613 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004614 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004615 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004616 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004617 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004619 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004620
4621 if (!doRestore) {
4622 // No restore possible, or the Backup Manager was mysteriously not
4623 // available -- just fire the post-install work request directly.
4624 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4625 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4626 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004628 }
4629 });
4630 }
4631
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004632 abstract class HandlerParams {
4633 final static int MAX_RETRIES = 4;
4634 int retry = 0;
4635 final void startCopy() {
4636 try {
4637 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4638 retry++;
4639 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004640 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004641 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4642 handleServiceError();
4643 return;
4644 } else {
4645 handleStartCopy();
4646 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4647 mHandler.sendEmptyMessage(MCS_UNBIND);
4648 }
4649 } catch (RemoteException e) {
4650 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4651 mHandler.sendEmptyMessage(MCS_RECONNECT);
4652 }
4653 handleReturnCode();
4654 }
4655
4656 final void serviceError() {
4657 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4658 handleServiceError();
4659 handleReturnCode();
4660 }
4661 abstract void handleStartCopy() throws RemoteException;
4662 abstract void handleServiceError();
4663 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004664 }
4665
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004666 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004667 final IPackageInstallObserver observer;
4668 int flags;
4669 final Uri packageURI;
4670 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004671 private InstallArgs mArgs;
4672 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004673 InstallParams(Uri packageURI,
4674 IPackageInstallObserver observer, int flags,
4675 String installerPackageName) {
4676 this.packageURI = packageURI;
4677 this.flags = flags;
4678 this.observer = observer;
4679 this.installerPackageName = installerPackageName;
4680 }
4681
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004682 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4683 String packageName = pkgLite.packageName;
4684 int installLocation = pkgLite.installLocation;
4685 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4686 synchronized (mPackages) {
4687 PackageParser.Package pkg = mPackages.get(packageName);
4688 if (pkg != null) {
4689 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4690 // Check for updated system application.
4691 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4692 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004693 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004694 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4695 }
4696 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4697 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004698 if (onSd) {
4699 // Install flag overrides everything.
4700 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4701 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004702 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004703 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4704 // Application explicitly specified internal.
4705 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4706 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4707 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004708 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004709 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004710 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4711 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4712 }
4713 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004714 }
4715 }
4716 } else {
4717 // Invalid install. Return error code
4718 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4719 }
4720 }
4721 }
4722 // All the special cases have been taken care of.
4723 // Return result based on recommended install location.
4724 if (onSd) {
4725 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4726 }
4727 return pkgLite.recommendedInstallLocation;
4728 }
4729
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004730 /*
4731 * Invoke remote method to get package information and install
4732 * location values. Override install location based on default
4733 * policy if needed and then create install arguments based
4734 * on the install location.
4735 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004736 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004737 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004738 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4739 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004740 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4741 if (onInt && onSd) {
4742 // Check if both bits are set.
4743 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4744 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4745 } else if (fwdLocked && onSd) {
4746 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004747 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004748 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004749 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004750 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004751 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004752 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004753 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4754 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4755 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4756 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4757 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004758 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4759 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4760 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004761 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4762 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004763 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004764 // Override with defaults if needed.
4765 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004766 if (!onSd && !onInt) {
4767 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004768 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4769 // Set the flag to install on external media.
4770 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004771 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004772 } else {
4773 // Make sure the flag for installing on external
4774 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004775 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004776 flags &= ~PackageManager.INSTALL_EXTERNAL;
4777 }
4778 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004779 }
4780 }
4781 // Create the file args now.
4782 mArgs = createInstallArgs(this);
4783 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4784 // Create copy only if we are not in an erroneous state.
4785 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004786 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004787 }
4788 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004789 }
4790
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004791 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004792 void handleReturnCode() {
4793 processPendingInstall(mArgs, mRet);
4794 }
4795
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004796 @Override
4797 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004798 mArgs = createInstallArgs(this);
4799 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004800 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004801 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004802
4803 /*
4804 * Utility class used in movePackage api.
4805 * srcArgs and targetArgs are not set for invalid flags and make
4806 * sure to do null checks when invoking methods on them.
4807 * We probably want to return ErrorPrams for both failed installs
4808 * and moves.
4809 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004810 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004811 final IPackageMoveObserver observer;
4812 final int flags;
4813 final String packageName;
4814 final InstallArgs srcArgs;
4815 final InstallArgs targetArgs;
4816 int mRet;
4817 MoveParams(InstallArgs srcArgs,
4818 IPackageMoveObserver observer,
4819 int flags, String packageName) {
4820 this.srcArgs = srcArgs;
4821 this.observer = observer;
4822 this.flags = flags;
4823 this.packageName = packageName;
4824 if (srcArgs != null) {
4825 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4826 targetArgs = createInstallArgs(packageUri, flags, packageName);
4827 } else {
4828 targetArgs = null;
4829 }
4830 }
4831
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004832 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004833 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4834 // Check for storage space on target medium
4835 if (!targetArgs.checkFreeStorage(mContainerService)) {
4836 Log.w(TAG, "Insufficient storage to install");
4837 return;
4838 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004839 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004840 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004841 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004842 if (DEBUG_SD_INSTALL) {
4843 StringBuilder builder = new StringBuilder();
4844 if (srcArgs != null) {
4845 builder.append("src: ");
4846 builder.append(srcArgs.getCodePath());
4847 }
4848 if (targetArgs != null) {
4849 builder.append(" target : ");
4850 builder.append(targetArgs.getCodePath());
4851 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004852 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004853 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004854 }
4855
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004856 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004857 void handleReturnCode() {
4858 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004859 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4860 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4861 currentStatus = PackageManager.MOVE_SUCCEEDED;
4862 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4863 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4864 }
4865 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004866 }
4867
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004868 @Override
4869 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004870 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004871 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004872 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004873
4874 private InstallArgs createInstallArgs(InstallParams params) {
4875 if (installOnSd(params.flags)) {
4876 return new SdInstallArgs(params);
4877 } else {
4878 return new FileInstallArgs(params);
4879 }
4880 }
4881
4882 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4883 if (installOnSd(flags)) {
4884 return new SdInstallArgs(fullCodePath, fullResourcePath);
4885 } else {
4886 return new FileInstallArgs(fullCodePath, fullResourcePath);
4887 }
4888 }
4889
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004890 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4891 if (installOnSd(flags)) {
4892 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4893 return new SdInstallArgs(packageURI, cid);
4894 } else {
4895 return new FileInstallArgs(packageURI, pkgName);
4896 }
4897 }
4898
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004899 static abstract class InstallArgs {
4900 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004901 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004902 final int flags;
4903 final Uri packageURI;
4904 final String installerPackageName;
4905
4906 InstallArgs(Uri packageURI,
4907 IPackageInstallObserver observer, int flags,
4908 String installerPackageName) {
4909 this.packageURI = packageURI;
4910 this.flags = flags;
4911 this.observer = observer;
4912 this.installerPackageName = installerPackageName;
4913 }
4914
4915 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004916 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004917 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004918 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004919 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004920 abstract String getCodePath();
4921 abstract String getResourcePath();
4922 // Need installer lock especially for dex file removal.
4923 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004924 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004925 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004926 }
4927
4928 class FileInstallArgs extends InstallArgs {
4929 File installDir;
4930 String codeFileName;
4931 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004932 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004933
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004934 FileInstallArgs(InstallParams params) {
4935 super(params.packageURI, params.observer,
4936 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004937 }
4938
4939 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4940 super(null, null, 0, null);
4941 File codeFile = new File(fullCodePath);
4942 installDir = codeFile.getParentFile();
4943 codeFileName = fullCodePath;
4944 resourceFileName = fullResourcePath;
4945 }
4946
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004947 FileInstallArgs(Uri packageURI, String pkgName) {
4948 super(packageURI, null, 0, null);
4949 boolean fwdLocked = isFwdLocked(flags);
4950 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4951 String apkName = getNextCodePath(null, pkgName, ".apk");
4952 codeFileName = new File(installDir, apkName + ".apk").getPath();
4953 resourceFileName = getResourcePathFromCodePath();
4954 }
4955
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004956 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4957 return imcs.checkFreeStorage(false, packageURI);
4958 }
4959
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004960 String getCodePath() {
4961 return codeFileName;
4962 }
4963
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004964 void createCopyFile() {
4965 boolean fwdLocked = isFwdLocked(flags);
4966 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4967 codeFileName = createTempPackageFile(installDir).getPath();
4968 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004969 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004970 }
4971
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004972 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004973 if (temp) {
4974 // Generate temp file name
4975 createCopyFile();
4976 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004977 // Get a ParcelFileDescriptor to write to the output file
4978 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004979 if (!created) {
4980 try {
4981 codeFile.createNewFile();
4982 // Set permissions
4983 if (!setPermissions()) {
4984 // Failed setting permissions.
4985 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4986 }
4987 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004988 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004989 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4990 }
4991 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004992 ParcelFileDescriptor out = null;
4993 try {
4994 out = ParcelFileDescriptor.open(codeFile,
4995 ParcelFileDescriptor.MODE_READ_WRITE);
4996 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004997 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004998 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4999 }
5000 // Copy the resource now
5001 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5002 try {
5003 if (imcs.copyResource(packageURI, out)) {
5004 ret = PackageManager.INSTALL_SUCCEEDED;
5005 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005006 } finally {
5007 try { if (out != null) out.close(); } catch (IOException e) {}
5008 }
5009 return ret;
5010 }
5011
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005012 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005013 if (status != PackageManager.INSTALL_SUCCEEDED) {
5014 cleanUp();
5015 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005016 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005017 }
5018
5019 boolean doRename(int status, final String pkgName, String oldCodePath) {
5020 if (status != PackageManager.INSTALL_SUCCEEDED) {
5021 cleanUp();
5022 return false;
5023 } else {
5024 // Rename based on packageName
5025 File codeFile = new File(getCodePath());
5026 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5027 File desFile = new File(installDir, apkName + ".apk");
5028 if (!codeFile.renameTo(desFile)) {
5029 return false;
5030 }
5031 // Reset paths since the file has been renamed.
5032 codeFileName = desFile.getPath();
5033 resourceFileName = getResourcePathFromCodePath();
5034 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005035 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005036 // Failed setting permissions.
5037 return false;
5038 }
5039 return true;
5040 }
5041 }
5042
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005043 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005044 if (status != PackageManager.INSTALL_SUCCEEDED) {
5045 cleanUp();
5046 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005047 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005048 }
5049
5050 String getResourcePath() {
5051 return resourceFileName;
5052 }
5053
5054 String getResourcePathFromCodePath() {
5055 String codePath = getCodePath();
5056 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5057 String apkNameOnly = getApkName(codePath);
5058 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5059 } else {
5060 return codePath;
5061 }
5062 }
5063
5064 private boolean cleanUp() {
5065 boolean ret = true;
5066 String sourceDir = getCodePath();
5067 String publicSourceDir = getResourcePath();
5068 if (sourceDir != null) {
5069 File sourceFile = new File(sourceDir);
5070 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005071 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005072 ret = false;
5073 }
5074 // Delete application's code and resources
5075 sourceFile.delete();
5076 }
5077 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5078 final File publicSourceFile = new File(publicSourceDir);
5079 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005080 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005081 }
5082 if (publicSourceFile.exists()) {
5083 publicSourceFile.delete();
5084 }
5085 }
5086 return ret;
5087 }
5088
5089 void cleanUpResourcesLI() {
5090 String sourceDir = getCodePath();
5091 if (cleanUp() && mInstaller != null) {
5092 int retCode = mInstaller.rmdex(sourceDir);
5093 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005094 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005095 + " at location "
5096 + sourceDir + ", retcode=" + retCode);
5097 // we don't consider this to be a failure of the core package deletion
5098 }
5099 }
5100 }
5101
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005102 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005103 // TODO Do this in a more elegant way later on. for now just a hack
5104 if (!isFwdLocked(flags)) {
5105 final int filePermissions =
5106 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5107 |FileUtils.S_IROTH;
5108 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5109 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005110 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005111 getCodePath()
5112 + ". The return code was: " + retCode);
5113 // TODO Define new internal error
5114 return false;
5115 }
5116 return true;
5117 }
5118 return true;
5119 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005120
5121 boolean doPostDeleteLI(boolean delete) {
5122 cleanUpResourcesLI();
5123 return true;
5124 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005125 }
5126
5127 class SdInstallArgs extends InstallArgs {
5128 String cid;
5129 String cachePath;
5130 static final String RES_FILE_NAME = "pkg.apk";
5131
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005132 SdInstallArgs(InstallParams params) {
5133 super(params.packageURI, params.observer,
5134 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005135 }
5136
5137 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005138 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005139 // Extract cid from fullCodePath
5140 int eidx = fullCodePath.lastIndexOf("/");
5141 String subStr1 = fullCodePath.substring(0, eidx);
5142 int sidx = subStr1.lastIndexOf("/");
5143 cid = subStr1.substring(sidx+1, eidx);
5144 cachePath = subStr1;
5145 }
5146
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005147 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005148 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5149 this.cid = cid;
5150 }
5151
5152 SdInstallArgs(Uri packageURI, String cid) {
5153 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005154 this.cid = cid;
5155 }
5156
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005157 void createCopyFile() {
5158 cid = getTempContainerId();
5159 }
5160
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005161 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5162 return imcs.checkFreeStorage(true, packageURI);
5163 }
5164
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005165 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005166 if (temp) {
5167 createCopyFile();
5168 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005169 cachePath = imcs.copyResourceToContainer(
5170 packageURI, cid,
5171 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005172 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5173 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005174 }
5175
5176 @Override
5177 String getCodePath() {
5178 return cachePath + "/" + RES_FILE_NAME;
5179 }
5180
5181 @Override
5182 String getResourcePath() {
5183 return cachePath + "/" + RES_FILE_NAME;
5184 }
5185
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005186 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005187 if (status != PackageManager.INSTALL_SUCCEEDED) {
5188 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005189 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005190 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005191 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005192 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005193 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005194 if (cachePath == null) {
5195 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5196 }
5197 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005198 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005199 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005200 }
5201
5202 boolean doRename(int status, final String pkgName,
5203 String oldCodePath) {
5204 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005205 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005206 if (PackageHelper.isContainerMounted(cid)) {
5207 // Unmount the container
5208 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005209 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005210 return false;
5211 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005212 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005213 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005214 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005215 return false;
5216 }
5217 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005218 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005219 newCachePath = PackageHelper.mountSdDir(newCacheId,
5220 getEncryptKey(), Process.SYSTEM_UID);
5221 } else {
5222 newCachePath = PackageHelper.getSdDir(newCacheId);
5223 }
5224 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005225 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005226 return false;
5227 }
5228 Log.i(TAG, "Succesfully renamed " + cid +
5229 " at path: " + cachePath + " to " + newCacheId +
5230 " at new path: " + newCachePath);
5231 cid = newCacheId;
5232 cachePath = newCachePath;
5233 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005234 }
5235
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005236 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005237 if (status != PackageManager.INSTALL_SUCCEEDED) {
5238 cleanUp();
5239 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005240 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005241 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005242 PackageHelper.mountSdDir(cid,
5243 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005244 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005245 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005246 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005247 }
5248
5249 private void cleanUp() {
5250 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005251 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005252 }
5253
5254 void cleanUpResourcesLI() {
5255 String sourceFile = getCodePath();
5256 // Remove dex file
5257 if (mInstaller != null) {
5258 int retCode = mInstaller.rmdex(sourceFile.toString());
5259 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005260 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005261 + " at location "
5262 + sourceFile.toString() + ", retcode=" + retCode);
5263 // we don't consider this to be a failure of the core package deletion
5264 }
5265 }
5266 cleanUp();
5267 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005268
5269 boolean matchContainer(String app) {
5270 if (cid.startsWith(app)) {
5271 return true;
5272 }
5273 return false;
5274 }
5275
5276 String getPackageName() {
5277 int idx = cid.lastIndexOf("-");
5278 if (idx == -1) {
5279 return cid;
5280 }
5281 return cid.substring(0, idx);
5282 }
5283
5284 boolean doPostDeleteLI(boolean delete) {
5285 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005286 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005287 if (mounted) {
5288 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005289 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005290 }
5291 if (ret && delete) {
5292 cleanUpResourcesLI();
5293 }
5294 return ret;
5295 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005296 };
5297
5298 // Utility method used to create code paths based on package name and available index.
5299 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5300 String idxStr = "";
5301 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005302 // Fall back to default value of idx=1 if prefix is not
5303 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005304 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005305 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005306 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005307 if (subStr.endsWith(suffix)) {
5308 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005309 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005310 // If oldCodePath already contains prefix find out the
5311 // ending index to either increment or decrement.
5312 int sidx = subStr.lastIndexOf(prefix);
5313 if (sidx != -1) {
5314 subStr = subStr.substring(sidx + prefix.length());
5315 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005316 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5317 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005318 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005319 try {
5320 idx = Integer.parseInt(subStr);
5321 if (idx <= 1) {
5322 idx++;
5323 } else {
5324 idx--;
5325 }
5326 } catch(NumberFormatException e) {
5327 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005328 }
5329 }
5330 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005331 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005332 return prefix + idxStr;
5333 }
5334
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005335 // Utility method used to ignore ADD/REMOVE events
5336 // by directory observer.
5337 private static boolean ignoreCodePath(String fullPathStr) {
5338 String apkName = getApkName(fullPathStr);
5339 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5340 if (idx != -1 && ((idx+1) < apkName.length())) {
5341 // Make sure the package ends with a numeral
5342 String version = apkName.substring(idx+1);
5343 try {
5344 Integer.parseInt(version);
5345 return true;
5346 } catch (NumberFormatException e) {}
5347 }
5348 return false;
5349 }
5350
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005351 // Utility method that returns the relative package path with respect
5352 // to the installation directory. Like say for /data/data/com.test-1.apk
5353 // string com.test-1 is returned.
5354 static String getApkName(String codePath) {
5355 if (codePath == null) {
5356 return null;
5357 }
5358 int sidx = codePath.lastIndexOf("/");
5359 int eidx = codePath.lastIndexOf(".");
5360 if (eidx == -1) {
5361 eidx = codePath.length();
5362 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005363 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005364 return null;
5365 }
5366 return codePath.substring(sidx+1, eidx);
5367 }
5368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005369 class PackageInstalledInfo {
5370 String name;
5371 int uid;
5372 PackageParser.Package pkg;
5373 int returnCode;
5374 PackageRemovedInfo removedInfo;
5375 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005377 /*
5378 * Install a non-existing package.
5379 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005380 private void installNewPackageLI(PackageParser.Package pkg,
5381 int parseFlags,
5382 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005383 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005385 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005386
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005387 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005388 res.name = pkgName;
5389 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005390 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005391 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005392 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005393 + " without first uninstalling.");
5394 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5395 return;
5396 }
5397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005398 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005399 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005400 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005401 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005402 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5403 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5404 }
5405 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005406 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005407 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005408 res);
5409 // delete the partially installed application. the data directory will have to be
5410 // restored if it was already existing
5411 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5412 // remove package from internal structures. Note that we want deletePackageX to
5413 // delete the package data and cache directories that it created in
5414 // scanPackageLocked, unless those directories existed before we even tried to
5415 // install.
5416 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005417 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005418 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5419 res.removedInfo);
5420 }
5421 }
5422 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005423
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005424 private void replacePackageLI(PackageParser.Package pkg,
5425 int parseFlags,
5426 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005427 String installerPackageName, PackageInstalledInfo res) {
5428
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005429 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005430 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005431 // First find the old package info and check signatures
5432 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005433 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005434 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005435 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5437 return;
5438 }
5439 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005440 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005441 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005442 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005444 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 }
5446 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005449 PackageParser.Package pkg,
5450 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005451 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 PackageParser.Package newPackage = null;
5453 String pkgName = deletedPackage.packageName;
5454 boolean deletedPkg = true;
5455 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005456
Jacek Surazski65e13172009-04-28 15:26:38 +02005457 String oldInstallerPackageName = null;
5458 synchronized (mPackages) {
5459 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5460 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005461
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005462 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005464 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465 res.removedInfo)) {
5466 // If the existing package was'nt successfully deleted
5467 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5468 deletedPkg = false;
5469 } else {
5470 // Successfully deleted the old package. Now proceed with re-installation
5471 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005472 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005473 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005474 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5476 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005477 }
5478 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005479 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005480 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005481 res);
5482 updatedSettings = true;
5483 }
5484 }
5485
5486 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5487 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005488 // were keeping around in case we needed them (see below) can now be deleted.
5489 // This info will be set on the res.removedInfo to clean up later on as post
5490 // install action.
5491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005492 //update signature on the new package setting
5493 //this should always succeed, since we checked the
5494 //signature earlier.
5495 synchronized(mPackages) {
5496 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5497 parseFlags, true);
5498 }
5499 } else {
5500 // remove package from internal structures. Note that we want deletePackageX to
5501 // delete the package data and cache directories that it created in
5502 // scanPackageLocked, unless those directories existed before we even tried to
5503 // install.
5504 if(updatedSettings) {
5505 deletePackageLI(
5506 pkgName, true,
5507 PackageManager.DONT_DELETE_DATA,
5508 res.removedInfo);
5509 }
5510 // Since we failed to install the new package we need to restore the old
5511 // package that we deleted.
5512 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005513 File restoreFile = new File(deletedPackage.mPath);
5514 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005515 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005516 return;
5517 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005518 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5519 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005520 // Parse old package
5521 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5522 scanPackageLI(restoreFile, parseFlags, scanMode);
5523 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005524 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5525 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005526 mSettings.writeLP();
5527 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005528 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005529 Slog.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005531 }
5532 }
5533 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005536 PackageParser.Package pkg,
5537 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005538 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 PackageParser.Package newPackage = null;
5540 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005541 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 PackageParser.PARSE_IS_SYSTEM;
5543 String packageName = deletedPackage.packageName;
5544 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5545 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005546 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005547 return;
5548 }
5549 PackageParser.Package oldPkg;
5550 PackageSetting oldPkgSetting;
5551 synchronized (mPackages) {
5552 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005553 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005554 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5555 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005556 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557 return;
5558 }
5559 }
5560 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5561 res.removedInfo.removedPackage = packageName;
5562 // Remove existing system package
5563 removePackageLI(oldPkg, true);
5564 synchronized (mPackages) {
5565 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5566 }
5567
5568 // Successfully disabled the old package. Now proceed with re-installation
5569 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5570 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005571 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005573 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5575 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5576 }
5577 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005578 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 updatedSettings = true;
5580 }
5581
5582 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5583 //update signature on the new package setting
5584 //this should always succeed, since we checked the
5585 //signature earlier.
5586 synchronized(mPackages) {
5587 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5588 parseFlags, true);
5589 }
5590 } else {
5591 // Re installation failed. Restore old information
5592 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005593 if (newPackage != null) {
5594 removePackageLI(newPackage, true);
5595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005597 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005598 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005599 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005600 // Restore the old system information in Settings
5601 synchronized(mPackages) {
5602 if(updatedSettings) {
5603 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005604 mSettings.setInstallerPackageName(packageName,
5605 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 }
5607 mSettings.writeLP();
5608 }
5609 }
5610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005611
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005612 // Utility method used to move dex files during install.
5613 private int moveDexFiles(PackageParser.Package newPackage) {
5614 int retCode;
5615 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5616 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5617 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005618 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005619 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5620 }
5621 }
5622 return PackageManager.INSTALL_SUCCEEDED;
5623 }
5624
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005625 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005626 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005627 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005628 synchronized (mPackages) {
5629 //write settings. the installStatus will be incomplete at this stage.
5630 //note that the new package setting would have already been
5631 //added to mPackages. It hasn't been persisted yet.
5632 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5633 mSettings.writeLP();
5634 }
5635
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005636 if ((res.returnCode = moveDexFiles(newPackage))
5637 != PackageManager.INSTALL_SUCCEEDED) {
5638 // Discontinue if moving dex files failed.
5639 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005641 if((res.returnCode = setPermissionsLI(newPackage))
5642 != PackageManager.INSTALL_SUCCEEDED) {
5643 if (mInstaller != null) {
5644 mInstaller.rmdex(newPackage.mScanPath);
5645 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005646 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005648 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005651 updatePermissionsLP(newPackage.packageName, newPackage,
5652 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 res.name = pkgName;
5654 res.uid = newPackage.applicationInfo.uid;
5655 res.pkg = newPackage;
5656 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005657 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5659 //to update install status
5660 mSettings.writeLP();
5661 }
5662 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005663
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005664 private void installPackageLI(InstallArgs args,
5665 boolean newInstall, PackageInstalledInfo res) {
5666 int pFlags = args.flags;
5667 String installerPackageName = args.installerPackageName;
5668 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005669 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005670 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005671 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005672 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5673 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005674 // Result object to be returned
5675 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5676
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005677 // Retrieve PackageSettings and parse package
5678 int parseFlags = PackageParser.PARSE_CHATTY |
5679 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5680 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5681 parseFlags |= mDefParseFlags;
5682 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5683 pp.setSeparateProcesses(mSeparateProcesses);
5684 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5685 null, mMetrics, parseFlags);
5686 if (pkg == null) {
5687 res.returnCode = pp.getParseError();
5688 return;
5689 }
5690 String pkgName = res.name = pkg.packageName;
5691 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5692 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5693 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5694 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005696 }
5697 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5698 res.returnCode = pp.getParseError();
5699 return;
5700 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005701 // Get rid of all references to package scan path via parser.
5702 pp = null;
5703 String oldCodePath = null;
5704 boolean systemApp = false;
5705 synchronized (mPackages) {
5706 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005707 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5708 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005709 if (pkg.mOriginalPackages != null
5710 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005711 && mPackages.containsKey(oldName)) {
5712 // This package is derived from an original package,
5713 // and this device has been updating from that original
5714 // name. We must continue using the original name, so
5715 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005716 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005717 pkgName = pkg.packageName;
5718 replace = true;
5719 } else if (mPackages.containsKey(pkgName)) {
5720 // This package, under its official name, already exists
5721 // on the device; we should replace it.
5722 replace = true;
5723 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005724 }
5725 PackageSetting ps = mSettings.mPackages.get(pkgName);
5726 if (ps != null) {
5727 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5728 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5729 systemApp = (ps.pkg.applicationInfo.flags &
5730 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005731 }
5732 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005734
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005735 if (systemApp && onSd) {
5736 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005737 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005738 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5739 return;
5740 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005741
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005742 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5743 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5744 return;
5745 }
5746 // Set application objects path explicitly after the rename
5747 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005748 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005749 replacePackageLI(pkg, parseFlags, scanMode,
5750 installerPackageName, res);
5751 } else {
5752 installNewPackageLI(pkg, parseFlags, scanMode,
5753 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 }
5755 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005756
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005757 private int setPermissionsLI(PackageParser.Package newPackage) {
5758 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005759 int retCode = 0;
5760 // TODO Gross hack but fix later. Ideally move this to be a post installation
5761 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005762 if ((newPackage.applicationInfo.flags
5763 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5764 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765 try {
5766 extractPublicFiles(newPackage, destResourceFile);
5767 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005768 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 -08005769 " forward-locked app.");
5770 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5771 } finally {
5772 //TODO clean up the extracted public files
5773 }
5774 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005775 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005776 newPackage.applicationInfo.uid);
5777 } else {
5778 final int filePermissions =
5779 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005780 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005781 newPackage.applicationInfo.uid);
5782 }
5783 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005784 // The permissions on the resource file was set when it was copied for
5785 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005788 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005789 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005790 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005791 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005792 // TODO Define new internal error
5793 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 }
5795 return PackageManager.INSTALL_SUCCEEDED;
5796 }
5797
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005798 private boolean isForwardLocked(PackageParser.Package pkg) {
5799 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 }
5801
5802 private void extractPublicFiles(PackageParser.Package newPackage,
5803 File publicZipFile) throws IOException {
5804 final ZipOutputStream publicZipOutStream =
5805 new ZipOutputStream(new FileOutputStream(publicZipFile));
5806 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5807
5808 // Copy manifest, resources.arsc and res directory to public zip
5809
5810 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5811 while (privateZipEntries.hasMoreElements()) {
5812 final ZipEntry zipEntry = privateZipEntries.nextElement();
5813 final String zipEntryName = zipEntry.getName();
5814 if ("AndroidManifest.xml".equals(zipEntryName)
5815 || "resources.arsc".equals(zipEntryName)
5816 || zipEntryName.startsWith("res/")) {
5817 try {
5818 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5819 } catch (IOException e) {
5820 try {
5821 publicZipOutStream.close();
5822 throw e;
5823 } finally {
5824 publicZipFile.delete();
5825 }
5826 }
5827 }
5828 }
5829
5830 publicZipOutStream.close();
5831 FileUtils.setPermissions(
5832 publicZipFile.getAbsolutePath(),
5833 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5834 -1, -1);
5835 }
5836
5837 private static void copyZipEntry(ZipEntry zipEntry,
5838 ZipFile inZipFile,
5839 ZipOutputStream outZipStream) throws IOException {
5840 byte[] buffer = new byte[4096];
5841 int num;
5842
5843 ZipEntry newEntry;
5844 if (zipEntry.getMethod() == ZipEntry.STORED) {
5845 // Preserve the STORED method of the input entry.
5846 newEntry = new ZipEntry(zipEntry);
5847 } else {
5848 // Create a new entry so that the compressed len is recomputed.
5849 newEntry = new ZipEntry(zipEntry.getName());
5850 }
5851 outZipStream.putNextEntry(newEntry);
5852
5853 InputStream data = inZipFile.getInputStream(zipEntry);
5854 while ((num = data.read(buffer)) > 0) {
5855 outZipStream.write(buffer, 0, num);
5856 }
5857 outZipStream.flush();
5858 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 private void deleteTempPackageFiles() {
5861 FilenameFilter filter = new FilenameFilter() {
5862 public boolean accept(File dir, String name) {
5863 return name.startsWith("vmdl") && name.endsWith(".tmp");
5864 }
5865 };
5866 String tmpFilesList[] = mAppInstallDir.list(filter);
5867 if(tmpFilesList == null) {
5868 return;
5869 }
5870 for(int i = 0; i < tmpFilesList.length; i++) {
5871 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5872 tmpFile.delete();
5873 }
5874 }
5875
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005876 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 File tmpPackageFile;
5878 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005879 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005881 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005882 return null;
5883 }
5884 try {
5885 FileUtils.setPermissions(
5886 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5887 -1, -1);
5888 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005889 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 return null;
5891 }
5892 return tmpPackageFile;
5893 }
5894
5895 public void deletePackage(final String packageName,
5896 final IPackageDeleteObserver observer,
5897 final int flags) {
5898 mContext.enforceCallingOrSelfPermission(
5899 android.Manifest.permission.DELETE_PACKAGES, null);
5900 // Queue up an async operation since the package deletion may take a little while.
5901 mHandler.post(new Runnable() {
5902 public void run() {
5903 mHandler.removeCallbacks(this);
5904 final boolean succeded = deletePackageX(packageName, true, true, flags);
5905 if (observer != null) {
5906 try {
5907 observer.packageDeleted(succeded);
5908 } catch (RemoteException e) {
5909 Log.i(TAG, "Observer no longer exists.");
5910 } //end catch
5911 } //end if
5912 } //end run
5913 });
5914 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005916 /**
5917 * This method is an internal method that could be get invoked either
5918 * to delete an installed package or to clean up a failed installation.
5919 * After deleting an installed package, a broadcast is sent to notify any
5920 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005921 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005922 * installation wouldn't have sent the initial broadcast either
5923 * The key steps in deleting a package are
5924 * deleting the package information in internal structures like mPackages,
5925 * deleting the packages base directories through installd
5926 * updating mSettings to reflect current status
5927 * persisting settings for later use
5928 * sending a broadcast if necessary
5929 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005930 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5931 boolean deleteCodeAndResources, int flags) {
5932 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005933 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005935 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5936 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5937 try {
5938 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005939 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005940 return false;
5941 }
5942 } catch (RemoteException e) {
5943 }
5944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 synchronized (mInstallLock) {
5946 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5947 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005949 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005950 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5951 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5952
5953 // If the removed package was a system update, the old system packaged
5954 // was re-enabled; we need to broadcast this information
5955 if (systemUpdate) {
5956 Bundle extras = new Bundle(1);
5957 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5958 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5959
5960 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5961 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005964 // Force a gc here.
5965 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005966 // Delete the resources here after sending the broadcast to let
5967 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005968 if (info.args != null) {
5969 synchronized (mInstallLock) {
5970 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005971 }
5972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005973 return res;
5974 }
5975
5976 static class PackageRemovedInfo {
5977 String removedPackage;
5978 int uid = -1;
5979 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005980 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005981 // Clean up resources deleted packages.
5982 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 void sendBroadcast(boolean fullRemove, boolean replacing) {
5985 Bundle extras = new Bundle(1);
5986 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5987 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5988 if (replacing) {
5989 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5990 }
5991 if (removedPackage != null) {
5992 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5993 }
5994 if (removedUid >= 0) {
5995 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5996 }
5997 }
5998 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006000 /*
6001 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6002 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006003 * 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 -08006004 * delete a partially installed application.
6005 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006006 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 int flags) {
6008 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006009 if (outInfo != null) {
6010 outInfo.removedPackage = packageName;
6011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 removePackageLI(p, true);
6013 // Retrieve object to delete permissions for shared user later on
6014 PackageSetting deletedPs;
6015 synchronized (mPackages) {
6016 deletedPs = mSettings.mPackages.get(packageName);
6017 }
6018 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006019 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006020 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006021 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006023 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 + packageName + ", retcode=" + retCode);
6025 // we don't consider this to be a failure of the core package deletion
6026 }
6027 } else {
6028 //for emulator
6029 PackageParser.Package pkg = mPackages.get(packageName);
6030 File dataDir = new File(pkg.applicationInfo.dataDir);
6031 dataDir.delete();
6032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 }
6034 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006035 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006036 schedulePackageCleaning(packageName);
6037
6038 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6039 if (outInfo != null) {
6040 outInfo.removedUid = mSettings.removePackageLP(packageName);
6041 }
6042 if (deletedPs != null) {
6043 updatePermissionsLP(deletedPs.name, null, false, false);
6044 if (deletedPs.sharedUser != null) {
6045 // remove permissions associated with package
6046 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6047 }
6048 }
6049 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006050 // remove from preferred activities.
6051 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6052 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6053 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6054 removed.add(pa);
6055 }
6056 }
6057 for (PreferredActivity pa : removed) {
6058 mSettings.mPreferredActivities.removeFilter(pa);
6059 }
6060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006062 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006063 }
6064 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 /*
6067 * Tries to delete system package.
6068 */
6069 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006070 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 ApplicationInfo applicationInfo = p.applicationInfo;
6072 //applicable for non-partially installed applications only
6073 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006074 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006075 return false;
6076 }
6077 PackageSetting ps = null;
6078 // Confirm if the system package has been updated
6079 // An updated system app can be deleted. This will also have to restore
6080 // the system pkg from system partition
6081 synchronized (mPackages) {
6082 ps = mSettings.getDisabledSystemPkg(p.packageName);
6083 }
6084 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006085 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 return false;
6087 } else {
6088 Log.i(TAG, "Deleting system pkg from data partition");
6089 }
6090 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006091 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006092 boolean deleteCodeAndResources = false;
6093 if (ps.versionCode < p.mVersionCode) {
6094 // Delete code and resources for downgrades
6095 deleteCodeAndResources = true;
6096 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6097 flags &= ~PackageManager.DONT_DELETE_DATA;
6098 }
6099 } else {
6100 // Preserve data by setting flag
6101 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6102 flags |= PackageManager.DONT_DELETE_DATA;
6103 }
6104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6106 if (!ret) {
6107 return false;
6108 }
6109 synchronized (mPackages) {
6110 // Reinstate the old system package
6111 mSettings.enableSystemPackageLP(p.packageName);
6112 }
6113 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006114 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006116 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006118 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006119 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 return false;
6121 }
6122 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006123 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 mSettings.writeLP();
6125 }
6126 return true;
6127 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006129 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6130 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6131 ApplicationInfo applicationInfo = p.applicationInfo;
6132 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006133 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006134 return false;
6135 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006136 if (outInfo != null) {
6137 outInfo.uid = applicationInfo.uid;
6138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139
6140 // Delete package data from internal structures and also remove data if flag is set
6141 removePackageDataLI(p, outInfo, flags);
6142
6143 // Delete application code and resources
6144 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006145 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006146 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006147 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006148 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6149 PackageManager.INSTALL_FORWARD_LOCK : 0;
6150 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006151 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 }
6153 return true;
6154 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 /*
6157 * This method handles package deletion in general
6158 */
6159 private boolean deletePackageLI(String packageName,
6160 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6161 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006162 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006163 return false;
6164 }
6165 PackageParser.Package p;
6166 boolean dataOnly = false;
6167 synchronized (mPackages) {
6168 p = mPackages.get(packageName);
6169 if (p == null) {
6170 //this retrieves partially installed apps
6171 dataOnly = true;
6172 PackageSetting ps = mSettings.mPackages.get(packageName);
6173 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006174 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006175 return false;
6176 }
6177 p = ps.pkg;
6178 }
6179 }
6180 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006181 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 return false;
6183 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 if (dataOnly) {
6186 // Delete application data first
6187 removePackageDataLI(p, outInfo, flags);
6188 return true;
6189 }
6190 // At this point the package should have ApplicationInfo associated with it
6191 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006192 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 return false;
6194 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006195 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6197 Log.i(TAG, "Removing system package:"+p.packageName);
6198 // When an updated system application is deleted we delete the existing resources as well and
6199 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006200 ret = deleteSystemPackageLI(p, flags, outInfo);
6201 } else {
6202 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006203 // Kill application pre-emptively especially for apps on sd.
6204 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006205 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006207 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 public void clearApplicationUserData(final String packageName,
6211 final IPackageDataObserver observer) {
6212 mContext.enforceCallingOrSelfPermission(
6213 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6214 // Queue up an async operation since the package deletion may take a little while.
6215 mHandler.post(new Runnable() {
6216 public void run() {
6217 mHandler.removeCallbacks(this);
6218 final boolean succeeded;
6219 synchronized (mInstallLock) {
6220 succeeded = clearApplicationUserDataLI(packageName);
6221 }
6222 if (succeeded) {
6223 // invoke DeviceStorageMonitor's update method to clear any notifications
6224 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6225 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6226 if (dsm != null) {
6227 dsm.updateMemory();
6228 }
6229 }
6230 if(observer != null) {
6231 try {
6232 observer.onRemoveCompleted(packageName, succeeded);
6233 } catch (RemoteException e) {
6234 Log.i(TAG, "Observer no longer exists.");
6235 }
6236 } //end if observer
6237 } //end run
6238 });
6239 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 private boolean clearApplicationUserDataLI(String packageName) {
6242 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006243 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 return false;
6245 }
6246 PackageParser.Package p;
6247 boolean dataOnly = false;
6248 synchronized (mPackages) {
6249 p = mPackages.get(packageName);
6250 if(p == null) {
6251 dataOnly = true;
6252 PackageSetting ps = mSettings.mPackages.get(packageName);
6253 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006254 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 return false;
6256 }
6257 p = ps.pkg;
6258 }
6259 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006260 boolean useEncryptedFSDir = false;
6261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 if(!dataOnly) {
6263 //need to check this only for fully installed applications
6264 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006265 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 return false;
6267 }
6268 final ApplicationInfo applicationInfo = p.applicationInfo;
6269 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006270 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 return false;
6272 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006273 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 }
6275 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006276 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006278 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 + packageName);
6280 return false;
6281 }
6282 }
6283 return true;
6284 }
6285
6286 public void deleteApplicationCacheFiles(final String packageName,
6287 final IPackageDataObserver observer) {
6288 mContext.enforceCallingOrSelfPermission(
6289 android.Manifest.permission.DELETE_CACHE_FILES, null);
6290 // Queue up an async operation since the package deletion may take a little while.
6291 mHandler.post(new Runnable() {
6292 public void run() {
6293 mHandler.removeCallbacks(this);
6294 final boolean succeded;
6295 synchronized (mInstallLock) {
6296 succeded = deleteApplicationCacheFilesLI(packageName);
6297 }
6298 if(observer != null) {
6299 try {
6300 observer.onRemoveCompleted(packageName, succeded);
6301 } catch (RemoteException e) {
6302 Log.i(TAG, "Observer no longer exists.");
6303 }
6304 } //end if observer
6305 } //end run
6306 });
6307 }
6308
6309 private boolean deleteApplicationCacheFilesLI(String packageName) {
6310 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006311 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 return false;
6313 }
6314 PackageParser.Package p;
6315 synchronized (mPackages) {
6316 p = mPackages.get(packageName);
6317 }
6318 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006319 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 return false;
6321 }
6322 final ApplicationInfo applicationInfo = p.applicationInfo;
6323 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006324 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 return false;
6326 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006327 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006329 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006331 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 + packageName);
6333 return false;
6334 }
6335 }
6336 return true;
6337 }
6338
6339 public void getPackageSizeInfo(final String packageName,
6340 final IPackageStatsObserver observer) {
6341 mContext.enforceCallingOrSelfPermission(
6342 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6343 // Queue up an async operation since the package deletion may take a little while.
6344 mHandler.post(new Runnable() {
6345 public void run() {
6346 mHandler.removeCallbacks(this);
6347 PackageStats lStats = new PackageStats(packageName);
6348 final boolean succeded;
6349 synchronized (mInstallLock) {
6350 succeded = getPackageSizeInfoLI(packageName, lStats);
6351 }
6352 if(observer != null) {
6353 try {
6354 observer.onGetStatsCompleted(lStats, succeded);
6355 } catch (RemoteException e) {
6356 Log.i(TAG, "Observer no longer exists.");
6357 }
6358 } //end if observer
6359 } //end run
6360 });
6361 }
6362
6363 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6364 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006365 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 return false;
6367 }
6368 PackageParser.Package p;
6369 boolean dataOnly = false;
6370 synchronized (mPackages) {
6371 p = mPackages.get(packageName);
6372 if(p == null) {
6373 dataOnly = true;
6374 PackageSetting ps = mSettings.mPackages.get(packageName);
6375 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006376 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 return false;
6378 }
6379 p = ps.pkg;
6380 }
6381 }
6382 String publicSrcDir = null;
6383 if(!dataOnly) {
6384 final ApplicationInfo applicationInfo = p.applicationInfo;
6385 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006386 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 return false;
6388 }
6389 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6390 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006391 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 if (mInstaller != null) {
6393 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006394 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 if (res < 0) {
6396 return false;
6397 } else {
6398 return true;
6399 }
6400 }
6401 return true;
6402 }
6403
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 public void addPackageToPreferred(String packageName) {
6406 mContext.enforceCallingOrSelfPermission(
6407 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006408 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 }
6410
6411 public void removePackageFromPreferred(String packageName) {
6412 mContext.enforceCallingOrSelfPermission(
6413 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006414 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 }
6416
6417 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006418 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 }
6420
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006421 int getUidTargetSdkVersionLockedLP(int uid) {
6422 Object obj = mSettings.getUserIdLP(uid);
6423 if (obj instanceof SharedUserSetting) {
6424 SharedUserSetting sus = (SharedUserSetting)obj;
6425 final int N = sus.packages.size();
6426 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6427 Iterator<PackageSetting> it = sus.packages.iterator();
6428 int i=0;
6429 while (it.hasNext()) {
6430 PackageSetting ps = it.next();
6431 if (ps.pkg != null) {
6432 int v = ps.pkg.applicationInfo.targetSdkVersion;
6433 if (v < vers) vers = v;
6434 }
6435 }
6436 return vers;
6437 } else if (obj instanceof PackageSetting) {
6438 PackageSetting ps = (PackageSetting)obj;
6439 if (ps.pkg != null) {
6440 return ps.pkg.applicationInfo.targetSdkVersion;
6441 }
6442 }
6443 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6444 }
6445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006446 public void addPreferredActivity(IntentFilter filter, int match,
6447 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006449 if (mContext.checkCallingOrSelfPermission(
6450 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6451 != PackageManager.PERMISSION_GRANTED) {
6452 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6453 < Build.VERSION_CODES.FROYO) {
6454 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6455 + Binder.getCallingUid());
6456 return;
6457 }
6458 mContext.enforceCallingOrSelfPermission(
6459 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6460 }
6461
6462 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006463 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6464 mSettings.mPreferredActivities.addFilter(
6465 new PreferredActivity(filter, match, set, activity));
6466 mSettings.writeLP();
6467 }
6468 }
6469
Satish Sampath8dbe6122009-06-02 23:35:54 +01006470 public void replacePreferredActivity(IntentFilter filter, int match,
6471 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006472 if (filter.countActions() != 1) {
6473 throw new IllegalArgumentException(
6474 "replacePreferredActivity expects filter to have only 1 action.");
6475 }
6476 if (filter.countCategories() != 1) {
6477 throw new IllegalArgumentException(
6478 "replacePreferredActivity expects filter to have only 1 category.");
6479 }
6480 if (filter.countDataAuthorities() != 0
6481 || filter.countDataPaths() != 0
6482 || filter.countDataSchemes() != 0
6483 || filter.countDataTypes() != 0) {
6484 throw new IllegalArgumentException(
6485 "replacePreferredActivity expects filter to have no data authorities, " +
6486 "paths, schemes or types.");
6487 }
6488 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006489 if (mContext.checkCallingOrSelfPermission(
6490 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6491 != PackageManager.PERMISSION_GRANTED) {
6492 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6493 < Build.VERSION_CODES.FROYO) {
6494 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6495 + Binder.getCallingUid());
6496 return;
6497 }
6498 mContext.enforceCallingOrSelfPermission(
6499 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6500 }
6501
Satish Sampath8dbe6122009-06-02 23:35:54 +01006502 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6503 String action = filter.getAction(0);
6504 String category = filter.getCategory(0);
6505 while (it.hasNext()) {
6506 PreferredActivity pa = it.next();
6507 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6508 it.remove();
6509 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6510 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6511 }
6512 }
6513 addPreferredActivity(filter, match, set, activity);
6514 }
6515 }
6516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006517 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006519 int uid = Binder.getCallingUid();
6520 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006521 if (pkg == null || pkg.applicationInfo.uid != uid) {
6522 if (mContext.checkCallingOrSelfPermission(
6523 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6524 != PackageManager.PERMISSION_GRANTED) {
6525 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6526 < Build.VERSION_CODES.FROYO) {
6527 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6528 + Binder.getCallingUid());
6529 return;
6530 }
6531 mContext.enforceCallingOrSelfPermission(
6532 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6533 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006534 }
6535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 if (clearPackagePreferredActivitiesLP(packageName)) {
6537 mSettings.writeLP();
6538 }
6539 }
6540 }
6541
6542 boolean clearPackagePreferredActivitiesLP(String packageName) {
6543 boolean changed = false;
6544 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6545 while (it.hasNext()) {
6546 PreferredActivity pa = it.next();
6547 if (pa.mActivity.getPackageName().equals(packageName)) {
6548 it.remove();
6549 changed = true;
6550 }
6551 }
6552 return changed;
6553 }
6554
6555 public int getPreferredActivities(List<IntentFilter> outFilters,
6556 List<ComponentName> outActivities, String packageName) {
6557
6558 int num = 0;
6559 synchronized (mPackages) {
6560 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6561 while (it.hasNext()) {
6562 PreferredActivity pa = it.next();
6563 if (packageName == null
6564 || pa.mActivity.getPackageName().equals(packageName)) {
6565 if (outFilters != null) {
6566 outFilters.add(new IntentFilter(pa));
6567 }
6568 if (outActivities != null) {
6569 outActivities.add(pa.mActivity);
6570 }
6571 }
6572 }
6573 }
6574
6575 return num;
6576 }
6577
6578 public void setApplicationEnabledSetting(String appPackageName,
6579 int newState, int flags) {
6580 setEnabledSetting(appPackageName, null, newState, flags);
6581 }
6582
6583 public void setComponentEnabledSetting(ComponentName componentName,
6584 int newState, int flags) {
6585 setEnabledSetting(componentName.getPackageName(),
6586 componentName.getClassName(), newState, flags);
6587 }
6588
6589 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006590 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006591 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6592 || newState == COMPONENT_ENABLED_STATE_ENABLED
6593 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6594 throw new IllegalArgumentException("Invalid new component state: "
6595 + newState);
6596 }
6597 PackageSetting pkgSetting;
6598 final int uid = Binder.getCallingUid();
6599 final int permission = mContext.checkCallingPermission(
6600 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6601 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006602 boolean sendNow = false;
6603 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006604 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006605 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006606 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006608 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006610 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006612 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 }
6614 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006615 "Unknown component: " + packageName
6616 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 }
6618 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6619 throw new SecurityException(
6620 "Permission Denial: attempt to change component state from pid="
6621 + Binder.getCallingPid()
6622 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6623 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006624 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006625 // We're dealing with an application/package level state change
6626 pkgSetting.enabled = newState;
6627 } else {
6628 // We're dealing with a component level state change
6629 switch (newState) {
6630 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006631 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 break;
6633 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006634 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 break;
6636 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006637 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006638 break;
6639 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006640 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006641 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006642 }
6643 }
6644 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006645 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006646 components = mPendingBroadcasts.get(packageName);
6647 boolean newPackage = components == null;
6648 if (newPackage) {
6649 components = new ArrayList<String>();
6650 }
6651 if (!components.contains(componentName)) {
6652 components.add(componentName);
6653 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006654 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6655 sendNow = true;
6656 // Purge entry from pending broadcast list if another one exists already
6657 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006658 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006659 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006660 if (newPackage) {
6661 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006662 }
6663 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6664 // Schedule a message
6665 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6666 }
6667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006670 long callingId = Binder.clearCallingIdentity();
6671 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006672 if (sendNow) {
6673 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006674 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006676 } finally {
6677 Binder.restoreCallingIdentity(callingId);
6678 }
6679 }
6680
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006681 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006682 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6683 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6684 + " components=" + componentNames);
6685 Bundle extras = new Bundle(4);
6686 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6687 String nameList[] = new String[componentNames.size()];
6688 componentNames.toArray(nameList);
6689 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006690 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6691 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006692 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006693 }
6694
Jacek Surazski65e13172009-04-28 15:26:38 +02006695 public String getInstallerPackageName(String packageName) {
6696 synchronized (mPackages) {
6697 PackageSetting pkg = mSettings.mPackages.get(packageName);
6698 if (pkg == null) {
6699 throw new IllegalArgumentException("Unknown package: " + packageName);
6700 }
6701 return pkg.installerPackageName;
6702 }
6703 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006705 public int getApplicationEnabledSetting(String appPackageName) {
6706 synchronized (mPackages) {
6707 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6708 if (pkg == null) {
6709 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6710 }
6711 return pkg.enabled;
6712 }
6713 }
6714
6715 public int getComponentEnabledSetting(ComponentName componentName) {
6716 synchronized (mPackages) {
6717 final String packageNameStr = componentName.getPackageName();
6718 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6719 if (pkg == null) {
6720 throw new IllegalArgumentException("Unknown component: " + componentName);
6721 }
6722 final String classNameStr = componentName.getClassName();
6723 return pkg.currentEnabledStateLP(classNameStr);
6724 }
6725 }
6726
6727 public void enterSafeMode() {
6728 if (!mSystemReady) {
6729 mSafeMode = true;
6730 }
6731 }
6732
6733 public void systemReady() {
6734 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006735
6736 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006737 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006738 mContext.getContentResolver(),
6739 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006740 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006741 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006742 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006744 }
6745
6746 public boolean isSafeMode() {
6747 return mSafeMode;
6748 }
6749
6750 public boolean hasSystemUidErrors() {
6751 return mHasSystemUidErrors;
6752 }
6753
6754 static String arrayToString(int[] array) {
6755 StringBuffer buf = new StringBuffer(128);
6756 buf.append('[');
6757 if (array != null) {
6758 for (int i=0; i<array.length; i++) {
6759 if (i > 0) buf.append(", ");
6760 buf.append(array[i]);
6761 }
6762 }
6763 buf.append(']');
6764 return buf.toString();
6765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 @Override
6768 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6769 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6770 != PackageManager.PERMISSION_GRANTED) {
6771 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6772 + Binder.getCallingPid()
6773 + ", uid=" + Binder.getCallingUid()
6774 + " without permission "
6775 + android.Manifest.permission.DUMP);
6776 return;
6777 }
6778
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006779 String packageName = null;
6780
6781 int opti = 0;
6782 while (opti < args.length) {
6783 String opt = args[opti];
6784 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6785 break;
6786 }
6787 opti++;
6788 if ("-a".equals(opt)) {
6789 // Right now we only know how to print all.
6790 } else if ("-h".equals(opt)) {
6791 pw.println("Package manager dump options:");
6792 pw.println(" [-h] [cmd] ...");
6793 pw.println(" cmd may be one of:");
6794 pw.println(" [package.name]: info about given package");
6795 return;
6796 } else {
6797 pw.println("Unknown argument: " + opt + "; use -h for help");
6798 }
6799 }
6800
6801 // Is the caller requesting to dump a particular piece of data?
6802 if (opti < args.length) {
6803 String cmd = args[opti];
6804 opti++;
6805 // Is this a package name?
6806 if ("android".equals(cmd) || cmd.contains(".")) {
6807 packageName = cmd;
6808 }
6809 }
6810
6811 boolean printedTitle = false;
6812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006814 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6815 printedTitle = true;
6816 }
6817 if (mReceivers.dump(pw, printedTitle
6818 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6819 " ", packageName)) {
6820 printedTitle = true;
6821 }
6822 if (mServices.dump(pw, printedTitle
6823 ? "\nService Resolver Table:" : "Service Resolver Table:",
6824 " ", packageName)) {
6825 printedTitle = true;
6826 }
6827 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6828 ? "\nPreferred Activities:" : "Preferred Activities:",
6829 " ", packageName)) {
6830 printedTitle = true;
6831 }
6832 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006833 {
6834 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006835 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6836 continue;
6837 }
6838 if (!printedSomething) {
6839 if (printedTitle) pw.println(" ");
6840 pw.println("Permissions:");
6841 printedSomething = true;
6842 printedTitle = true;
6843 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006844 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6845 pw.print(Integer.toHexString(System.identityHashCode(p)));
6846 pw.println("):");
6847 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6848 pw.print(" uid="); pw.print(p.uid);
6849 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006850 pw.print(" type="); pw.print(p.type);
6851 pw.print(" prot="); pw.println(p.protectionLevel);
6852 if (p.packageSetting != null) {
6853 pw.print(" packageSetting="); pw.println(p.packageSetting);
6854 }
6855 if (p.perm != null) {
6856 pw.print(" perm="); pw.println(p.perm);
6857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006858 }
6859 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006860 printedSomething = false;
6861 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006862 {
6863 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006864 if (packageName != null && !packageName.equals(ps.realName)
6865 && !packageName.equals(ps.name)) {
6866 continue;
6867 }
6868 if (!printedSomething) {
6869 if (printedTitle) pw.println(" ");
6870 pw.println("Packages:");
6871 printedSomething = true;
6872 printedTitle = true;
6873 }
6874 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006875 pw.print(" Package [");
6876 pw.print(ps.realName != null ? ps.realName : ps.name);
6877 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006878 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6879 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006880 if (ps.realName != null) {
6881 pw.print(" compat name="); pw.println(ps.name);
6882 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006883 pw.print(" userId="); pw.print(ps.userId);
6884 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6885 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6886 pw.print(" pkg="); pw.println(ps.pkg);
6887 pw.print(" codePath="); pw.println(ps.codePathString);
6888 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006889 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006890 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006891 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006892 pw.print(" supportsScreens=[");
6893 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006894 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006895 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006896 if (!first) pw.print(", ");
6897 first = false;
6898 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006899 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006900 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006901 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006902 if (!first) pw.print(", ");
6903 first = false;
6904 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006905 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006906 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006907 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006908 if (!first) pw.print(", ");
6909 first = false;
6910 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006911 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006912 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006913 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006914 if (!first) pw.print(", ");
6915 first = false;
6916 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006918 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006919 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6920 if (!first) pw.print(", ");
6921 first = false;
6922 pw.print("anyDensity");
6923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006924 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006925 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006926 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6927 pw.print(" signatures="); pw.println(ps.signatures);
6928 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6929 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6930 pw.print(" installStatus="); pw.print(ps.installStatus);
6931 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006932 if (ps.disabledComponents.size() > 0) {
6933 pw.println(" disabledComponents:");
6934 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006935 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006936 }
6937 }
6938 if (ps.enabledComponents.size() > 0) {
6939 pw.println(" enabledComponents:");
6940 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006941 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006942 }
6943 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006944 if (ps.grantedPermissions.size() > 0) {
6945 pw.println(" grantedPermissions:");
6946 for (String s : ps.grantedPermissions) {
6947 pw.print(" "); pw.println(s);
6948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006950 }
6951 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006952 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006953 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006954 for (HashMap.Entry<String, String> e
6955 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006956 if (packageName != null && !packageName.equals(e.getKey())
6957 && !packageName.equals(e.getValue())) {
6958 continue;
6959 }
6960 if (!printedSomething) {
6961 if (printedTitle) pw.println(" ");
6962 pw.println("Renamed packages:");
6963 printedSomething = true;
6964 printedTitle = true;
6965 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006966 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6967 pw.println(e.getValue());
6968 }
6969 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006970 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006971 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006972 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006973 if (packageName != null && !packageName.equals(ps.realName)
6974 && !packageName.equals(ps.name)) {
6975 continue;
6976 }
6977 if (!printedSomething) {
6978 if (printedTitle) pw.println(" ");
6979 pw.println("Hidden system packages:");
6980 printedSomething = true;
6981 printedTitle = true;
6982 }
6983 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006984 pw.print(ps.realName != null ? ps.realName : ps.name);
6985 pw.print("] (");
6986 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6987 pw.println("):");
6988 if (ps.realName != null) {
6989 pw.print(" compat name="); pw.println(ps.name);
6990 }
6991 pw.print(" userId="); pw.println(ps.userId);
6992 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6993 pw.print(" codePath="); pw.println(ps.codePathString);
6994 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6995 }
6996 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006997 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998 {
6999 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007000 if (packageName != null && su != packageSharedUser) {
7001 continue;
7002 }
7003 if (!printedSomething) {
7004 if (printedTitle) pw.println(" ");
7005 pw.println("Shared users:");
7006 printedSomething = true;
7007 printedTitle = true;
7008 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007009 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7010 pw.print(Integer.toHexString(System.identityHashCode(su)));
7011 pw.println("):");
7012 pw.print(" userId="); pw.print(su.userId);
7013 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007014 pw.println(" grantedPermissions:");
7015 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007016 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007018 }
7019 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007020
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007021 if (packageName == null) {
7022 if (printedTitle) pw.println(" ");
7023 printedTitle = true;
7024 pw.println("Settings parse messages:");
7025 pw.println(mSettings.mReadMessages.toString());
7026
7027 pw.println(" ");
7028 pw.println("Package warning messages:");
7029 File fname = getSettingsProblemFile();
7030 FileInputStream in;
7031 try {
7032 in = new FileInputStream(fname);
7033 int avail = in.available();
7034 byte[] data = new byte[avail];
7035 in.read(data);
7036 pw.println(new String(data));
7037 } catch (FileNotFoundException e) {
7038 } catch (IOException e) {
7039 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007042
7043 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007044 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007045 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007046 if (packageName != null && !packageName.equals(p.info.packageName)) {
7047 continue;
7048 }
7049 if (!printedSomething) {
7050 if (printedTitle) pw.println(" ");
7051 pw.println("Registered ContentProviders:");
7052 printedSomething = true;
7053 printedTitle = true;
7054 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007055 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007056 pw.println(p.toString());
7057 }
7058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007059 }
7060
7061 static final class BasePermission {
7062 final static int TYPE_NORMAL = 0;
7063 final static int TYPE_BUILTIN = 1;
7064 final static int TYPE_DYNAMIC = 2;
7065
7066 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007067 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007068 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007069 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007070 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007071 PackageParser.Permission perm;
7072 PermissionInfo pendingInfo;
7073 int uid;
7074 int[] gids;
7075
7076 BasePermission(String _name, String _sourcePackage, int _type) {
7077 name = _name;
7078 sourcePackage = _sourcePackage;
7079 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007080 // Default to most conservative protection level.
7081 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7082 }
7083
7084 public String toString() {
7085 return "BasePermission{"
7086 + Integer.toHexString(System.identityHashCode(this))
7087 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007088 }
7089 }
7090
7091 static class PackageSignatures {
7092 private Signature[] mSignatures;
7093
7094 PackageSignatures(Signature[] sigs) {
7095 assignSignatures(sigs);
7096 }
7097
7098 PackageSignatures() {
7099 }
7100
7101 void writeXml(XmlSerializer serializer, String tagName,
7102 ArrayList<Signature> pastSignatures) throws IOException {
7103 if (mSignatures == null) {
7104 return;
7105 }
7106 serializer.startTag(null, tagName);
7107 serializer.attribute(null, "count",
7108 Integer.toString(mSignatures.length));
7109 for (int i=0; i<mSignatures.length; i++) {
7110 serializer.startTag(null, "cert");
7111 final Signature sig = mSignatures[i];
7112 final int sigHash = sig.hashCode();
7113 final int numPast = pastSignatures.size();
7114 int j;
7115 for (j=0; j<numPast; j++) {
7116 Signature pastSig = pastSignatures.get(j);
7117 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7118 serializer.attribute(null, "index", Integer.toString(j));
7119 break;
7120 }
7121 }
7122 if (j >= numPast) {
7123 pastSignatures.add(sig);
7124 serializer.attribute(null, "index", Integer.toString(numPast));
7125 serializer.attribute(null, "key", sig.toCharsString());
7126 }
7127 serializer.endTag(null, "cert");
7128 }
7129 serializer.endTag(null, tagName);
7130 }
7131
7132 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7133 throws IOException, XmlPullParserException {
7134 String countStr = parser.getAttributeValue(null, "count");
7135 if (countStr == null) {
7136 reportSettingsProblem(Log.WARN,
7137 "Error in package manager settings: <signatures> has"
7138 + " no count at " + parser.getPositionDescription());
7139 XmlUtils.skipCurrentTag(parser);
7140 }
7141 final int count = Integer.parseInt(countStr);
7142 mSignatures = new Signature[count];
7143 int pos = 0;
7144
7145 int outerDepth = parser.getDepth();
7146 int type;
7147 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7148 && (type != XmlPullParser.END_TAG
7149 || parser.getDepth() > outerDepth)) {
7150 if (type == XmlPullParser.END_TAG
7151 || type == XmlPullParser.TEXT) {
7152 continue;
7153 }
7154
7155 String tagName = parser.getName();
7156 if (tagName.equals("cert")) {
7157 if (pos < count) {
7158 String index = parser.getAttributeValue(null, "index");
7159 if (index != null) {
7160 try {
7161 int idx = Integer.parseInt(index);
7162 String key = parser.getAttributeValue(null, "key");
7163 if (key == null) {
7164 if (idx >= 0 && idx < pastSignatures.size()) {
7165 Signature sig = pastSignatures.get(idx);
7166 if (sig != null) {
7167 mSignatures[pos] = pastSignatures.get(idx);
7168 pos++;
7169 } else {
7170 reportSettingsProblem(Log.WARN,
7171 "Error in package manager settings: <cert> "
7172 + "index " + index + " is not defined at "
7173 + parser.getPositionDescription());
7174 }
7175 } else {
7176 reportSettingsProblem(Log.WARN,
7177 "Error in package manager settings: <cert> "
7178 + "index " + index + " is out of bounds at "
7179 + parser.getPositionDescription());
7180 }
7181 } else {
7182 while (pastSignatures.size() <= idx) {
7183 pastSignatures.add(null);
7184 }
7185 Signature sig = new Signature(key);
7186 pastSignatures.set(idx, sig);
7187 mSignatures[pos] = sig;
7188 pos++;
7189 }
7190 } catch (NumberFormatException e) {
7191 reportSettingsProblem(Log.WARN,
7192 "Error in package manager settings: <cert> "
7193 + "index " + index + " is not a number at "
7194 + parser.getPositionDescription());
7195 }
7196 } else {
7197 reportSettingsProblem(Log.WARN,
7198 "Error in package manager settings: <cert> has"
7199 + " no index at " + parser.getPositionDescription());
7200 }
7201 } else {
7202 reportSettingsProblem(Log.WARN,
7203 "Error in package manager settings: too "
7204 + "many <cert> tags, expected " + count
7205 + " at " + parser.getPositionDescription());
7206 }
7207 } else {
7208 reportSettingsProblem(Log.WARN,
7209 "Unknown element under <cert>: "
7210 + parser.getName());
7211 }
7212 XmlUtils.skipCurrentTag(parser);
7213 }
7214
7215 if (pos < count) {
7216 // Should never happen -- there is an error in the written
7217 // settings -- but if it does we don't want to generate
7218 // a bad array.
7219 Signature[] newSigs = new Signature[pos];
7220 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7221 mSignatures = newSigs;
7222 }
7223 }
7224
7225 /**
7226 * If any of the given 'sigs' is contained in the existing signatures,
7227 * then completely replace the current signatures with the ones in
7228 * 'sigs'. This is used for updating an existing package to a newly
7229 * installed version.
7230 */
7231 boolean updateSignatures(Signature[] sigs, boolean update) {
7232 if (mSignatures == null) {
7233 if (update) {
7234 assignSignatures(sigs);
7235 }
7236 return true;
7237 }
7238 if (sigs == null) {
7239 return false;
7240 }
7241
7242 for (int i=0; i<sigs.length; i++) {
7243 Signature sig = sigs[i];
7244 for (int j=0; j<mSignatures.length; j++) {
7245 if (mSignatures[j].equals(sig)) {
7246 if (update) {
7247 assignSignatures(sigs);
7248 }
7249 return true;
7250 }
7251 }
7252 }
7253 return false;
7254 }
7255
7256 /**
7257 * If any of the given 'sigs' is contained in the existing signatures,
7258 * then add in any new signatures found in 'sigs'. This is used for
7259 * including a new package into an existing shared user id.
7260 */
7261 boolean mergeSignatures(Signature[] sigs, boolean update) {
7262 if (mSignatures == null) {
7263 if (update) {
7264 assignSignatures(sigs);
7265 }
7266 return true;
7267 }
7268 if (sigs == null) {
7269 return false;
7270 }
7271
7272 Signature[] added = null;
7273 int addedCount = 0;
7274 boolean haveMatch = false;
7275 for (int i=0; i<sigs.length; i++) {
7276 Signature sig = sigs[i];
7277 boolean found = false;
7278 for (int j=0; j<mSignatures.length; j++) {
7279 if (mSignatures[j].equals(sig)) {
7280 found = true;
7281 haveMatch = true;
7282 break;
7283 }
7284 }
7285
7286 if (!found) {
7287 if (added == null) {
7288 added = new Signature[sigs.length];
7289 }
7290 added[i] = sig;
7291 addedCount++;
7292 }
7293 }
7294
7295 if (!haveMatch) {
7296 // Nothing matched -- reject the new signatures.
7297 return false;
7298 }
7299 if (added == null) {
7300 // Completely matched -- nothing else to do.
7301 return true;
7302 }
7303
7304 // Add additional signatures in.
7305 if (update) {
7306 Signature[] total = new Signature[addedCount+mSignatures.length];
7307 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
7308 int j = mSignatures.length;
7309 for (int i=0; i<added.length; i++) {
7310 if (added[i] != null) {
7311 total[j] = added[i];
7312 j++;
7313 }
7314 }
7315 mSignatures = total;
7316 }
7317 return true;
7318 }
7319
7320 private void assignSignatures(Signature[] sigs) {
7321 if (sigs == null) {
7322 mSignatures = null;
7323 return;
7324 }
7325 mSignatures = new Signature[sigs.length];
7326 for (int i=0; i<sigs.length; i++) {
7327 mSignatures[i] = sigs[i];
7328 }
7329 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007331 @Override
7332 public String toString() {
7333 StringBuffer buf = new StringBuffer(128);
7334 buf.append("PackageSignatures{");
7335 buf.append(Integer.toHexString(System.identityHashCode(this)));
7336 buf.append(" [");
7337 if (mSignatures != null) {
7338 for (int i=0; i<mSignatures.length; i++) {
7339 if (i > 0) buf.append(", ");
7340 buf.append(Integer.toHexString(
7341 System.identityHashCode(mSignatures[i])));
7342 }
7343 }
7344 buf.append("]}");
7345 return buf.toString();
7346 }
7347 }
7348
7349 static class PreferredActivity extends IntentFilter {
7350 final int mMatch;
7351 final String[] mSetPackages;
7352 final String[] mSetClasses;
7353 final String[] mSetComponents;
7354 final ComponentName mActivity;
7355 final String mShortActivity;
7356 String mParseError;
7357
7358 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7359 ComponentName activity) {
7360 super(filter);
7361 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7362 mActivity = activity;
7363 mShortActivity = activity.flattenToShortString();
7364 mParseError = null;
7365 if (set != null) {
7366 final int N = set.length;
7367 String[] myPackages = new String[N];
7368 String[] myClasses = new String[N];
7369 String[] myComponents = new String[N];
7370 for (int i=0; i<N; i++) {
7371 ComponentName cn = set[i];
7372 if (cn == null) {
7373 mSetPackages = null;
7374 mSetClasses = null;
7375 mSetComponents = null;
7376 return;
7377 }
7378 myPackages[i] = cn.getPackageName().intern();
7379 myClasses[i] = cn.getClassName().intern();
7380 myComponents[i] = cn.flattenToShortString().intern();
7381 }
7382 mSetPackages = myPackages;
7383 mSetClasses = myClasses;
7384 mSetComponents = myComponents;
7385 } else {
7386 mSetPackages = null;
7387 mSetClasses = null;
7388 mSetComponents = null;
7389 }
7390 }
7391
7392 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7393 IOException {
7394 mShortActivity = parser.getAttributeValue(null, "name");
7395 mActivity = ComponentName.unflattenFromString(mShortActivity);
7396 if (mActivity == null) {
7397 mParseError = "Bad activity name " + mShortActivity;
7398 }
7399 String matchStr = parser.getAttributeValue(null, "match");
7400 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7401 String setCountStr = parser.getAttributeValue(null, "set");
7402 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7403
7404 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7405 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7406 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7407
7408 int setPos = 0;
7409
7410 int outerDepth = parser.getDepth();
7411 int type;
7412 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7413 && (type != XmlPullParser.END_TAG
7414 || parser.getDepth() > outerDepth)) {
7415 if (type == XmlPullParser.END_TAG
7416 || type == XmlPullParser.TEXT) {
7417 continue;
7418 }
7419
7420 String tagName = parser.getName();
7421 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7422 // + parser.getDepth() + " tag=" + tagName);
7423 if (tagName.equals("set")) {
7424 String name = parser.getAttributeValue(null, "name");
7425 if (name == null) {
7426 if (mParseError == null) {
7427 mParseError = "No name in set tag in preferred activity "
7428 + mShortActivity;
7429 }
7430 } else if (setPos >= setCount) {
7431 if (mParseError == null) {
7432 mParseError = "Too many set tags in preferred activity "
7433 + mShortActivity;
7434 }
7435 } else {
7436 ComponentName cn = ComponentName.unflattenFromString(name);
7437 if (cn == null) {
7438 if (mParseError == null) {
7439 mParseError = "Bad set name " + name + " in preferred activity "
7440 + mShortActivity;
7441 }
7442 } else {
7443 myPackages[setPos] = cn.getPackageName();
7444 myClasses[setPos] = cn.getClassName();
7445 myComponents[setPos] = name;
7446 setPos++;
7447 }
7448 }
7449 XmlUtils.skipCurrentTag(parser);
7450 } else if (tagName.equals("filter")) {
7451 //Log.i(TAG, "Starting to parse filter...");
7452 readFromXml(parser);
7453 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7454 // + parser.getDepth() + " tag=" + parser.getName());
7455 } else {
7456 reportSettingsProblem(Log.WARN,
7457 "Unknown element under <preferred-activities>: "
7458 + parser.getName());
7459 XmlUtils.skipCurrentTag(parser);
7460 }
7461 }
7462
7463 if (setPos != setCount) {
7464 if (mParseError == null) {
7465 mParseError = "Not enough set tags (expected " + setCount
7466 + " but found " + setPos + ") in " + mShortActivity;
7467 }
7468 }
7469
7470 mSetPackages = myPackages;
7471 mSetClasses = myClasses;
7472 mSetComponents = myComponents;
7473 }
7474
7475 public void writeToXml(XmlSerializer serializer) throws IOException {
7476 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7477 serializer.attribute(null, "name", mShortActivity);
7478 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7479 serializer.attribute(null, "set", Integer.toString(NS));
7480 for (int s=0; s<NS; s++) {
7481 serializer.startTag(null, "set");
7482 serializer.attribute(null, "name", mSetComponents[s]);
7483 serializer.endTag(null, "set");
7484 }
7485 serializer.startTag(null, "filter");
7486 super.writeToXml(serializer);
7487 serializer.endTag(null, "filter");
7488 }
7489
7490 boolean sameSet(List<ResolveInfo> query, int priority) {
7491 if (mSetPackages == null) return false;
7492 final int NQ = query.size();
7493 final int NS = mSetPackages.length;
7494 int numMatch = 0;
7495 for (int i=0; i<NQ; i++) {
7496 ResolveInfo ri = query.get(i);
7497 if (ri.priority != priority) continue;
7498 ActivityInfo ai = ri.activityInfo;
7499 boolean good = false;
7500 for (int j=0; j<NS; j++) {
7501 if (mSetPackages[j].equals(ai.packageName)
7502 && mSetClasses[j].equals(ai.name)) {
7503 numMatch++;
7504 good = true;
7505 break;
7506 }
7507 }
7508 if (!good) return false;
7509 }
7510 return numMatch == NS;
7511 }
7512 }
7513
7514 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007515 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007517 HashSet<String> grantedPermissions = new HashSet<String>();
7518 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007520 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007521 setFlags(pkgFlags);
7522 }
7523
7524 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007525 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007526 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08007527 (pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) |
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08007528 (pkgFlags & ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007529 }
7530 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007532 /**
7533 * Settings base class for pending and resolved classes.
7534 */
7535 static class PackageSettingBase extends GrantedPermissions {
7536 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007537 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007538 File codePath;
7539 String codePathString;
7540 File resourcePath;
7541 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 private long timeStamp;
7543 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007544 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007545
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007546 boolean uidError;
7547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548 PackageSignatures signatures = new PackageSignatures();
7549
7550 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 /* Explicitly disabled components */
7553 HashSet<String> disabledComponents = new HashSet<String>(0);
7554 /* Explicitly enabled components */
7555 HashSet<String> enabledComponents = new HashSet<String>(0);
7556 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7557 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007558
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007559 PackageSettingBase origPackage;
7560
Jacek Surazski65e13172009-04-28 15:26:38 +02007561 /* package name of the app that installed this package */
7562 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007563
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007564 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007565 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007566 super(pkgFlags);
7567 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007568 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007569 init(codePath, resourcePath, pVersionCode);
7570 }
7571
7572 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 this.codePath = codePath;
7574 this.codePathString = codePath.toString();
7575 this.resourcePath = resourcePath;
7576 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007577 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007578 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007579
Jacek Surazski65e13172009-04-28 15:26:38 +02007580 public void setInstallerPackageName(String packageName) {
7581 installerPackageName = packageName;
7582 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007583
Jacek Surazski65e13172009-04-28 15:26:38 +02007584 String getInstallerPackageName() {
7585 return installerPackageName;
7586 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 public void setInstallStatus(int newStatus) {
7589 installStatus = newStatus;
7590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592 public int getInstallStatus() {
7593 return installStatus;
7594 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007596 public void setTimeStamp(long newStamp) {
7597 if (newStamp != timeStamp) {
7598 timeStamp = newStamp;
7599 timeStampString = Long.toString(newStamp);
7600 }
7601 }
7602
7603 public void setTimeStamp(long newStamp, String newStampStr) {
7604 timeStamp = newStamp;
7605 timeStampString = newStampStr;
7606 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 public long getTimeStamp() {
7609 return timeStamp;
7610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007612 public String getTimeStampStr() {
7613 return timeStampString;
7614 }
7615
7616 public void copyFrom(PackageSettingBase base) {
7617 grantedPermissions = base.grantedPermissions;
7618 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007620 timeStamp = base.timeStamp;
7621 timeStampString = base.timeStampString;
7622 signatures = base.signatures;
7623 permissionsFixed = base.permissionsFixed;
7624 disabledComponents = base.disabledComponents;
7625 enabledComponents = base.enabledComponents;
7626 enabled = base.enabled;
7627 installStatus = base.installStatus;
7628 }
7629
7630 void enableComponentLP(String componentClassName) {
7631 disabledComponents.remove(componentClassName);
7632 enabledComponents.add(componentClassName);
7633 }
7634
7635 void disableComponentLP(String componentClassName) {
7636 enabledComponents.remove(componentClassName);
7637 disabledComponents.add(componentClassName);
7638 }
7639
7640 void restoreComponentLP(String componentClassName) {
7641 enabledComponents.remove(componentClassName);
7642 disabledComponents.remove(componentClassName);
7643 }
7644
7645 int currentEnabledStateLP(String componentName) {
7646 if (enabledComponents.contains(componentName)) {
7647 return COMPONENT_ENABLED_STATE_ENABLED;
7648 } else if (disabledComponents.contains(componentName)) {
7649 return COMPONENT_ENABLED_STATE_DISABLED;
7650 } else {
7651 return COMPONENT_ENABLED_STATE_DEFAULT;
7652 }
7653 }
7654 }
7655
7656 /**
7657 * Settings data for a particular package we know about.
7658 */
7659 static final class PackageSetting extends PackageSettingBase {
7660 int userId;
7661 PackageParser.Package pkg;
7662 SharedUserSetting sharedUser;
7663
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007664 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007665 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007666 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007669 @Override
7670 public String toString() {
7671 return "PackageSetting{"
7672 + Integer.toHexString(System.identityHashCode(this))
7673 + " " + name + "/" + userId + "}";
7674 }
7675 }
7676
7677 /**
7678 * Settings data for a particular shared user ID we know about.
7679 */
7680 static final class SharedUserSetting extends GrantedPermissions {
7681 final String name;
7682 int userId;
7683 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7684 final PackageSignatures signatures = new PackageSignatures();
7685
7686 SharedUserSetting(String _name, int _pkgFlags) {
7687 super(_pkgFlags);
7688 name = _name;
7689 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007691 @Override
7692 public String toString() {
7693 return "SharedUserSetting{"
7694 + Integer.toHexString(System.identityHashCode(this))
7695 + " " + name + "/" + userId + "}";
7696 }
7697 }
7698
7699 /**
7700 * Holds information about dynamic settings.
7701 */
7702 private static final class Settings {
7703 private final File mSettingsFilename;
7704 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007705 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007706 private final HashMap<String, PackageSetting> mPackages =
7707 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 // List of replaced system applications
7709 final HashMap<String, PackageSetting> mDisabledSysPackages =
7710 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 // The user's preferred activities associated with particular intent
7713 // filters.
7714 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7715 new IntentResolver<PreferredActivity, PreferredActivity>() {
7716 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007717 protected String packageForFilter(PreferredActivity filter) {
7718 return filter.mActivity.getPackageName();
7719 }
7720 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007721 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007723 out.print(prefix); out.print(
7724 Integer.toHexString(System.identityHashCode(filter)));
7725 out.print(' ');
7726 out.print(filter.mActivity.flattenToShortString());
7727 out.print(" match=0x");
7728 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007729 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007730 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007731 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007732 out.print(prefix); out.print(" ");
7733 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007734 }
7735 }
7736 }
7737 };
7738 private final HashMap<String, SharedUserSetting> mSharedUsers =
7739 new HashMap<String, SharedUserSetting>();
7740 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7741 private final SparseArray<Object> mOtherUserIds =
7742 new SparseArray<Object>();
7743
7744 // For reading/writing settings file.
7745 private final ArrayList<Signature> mPastSignatures =
7746 new ArrayList<Signature>();
7747
7748 // Mapping from permission names to info about them.
7749 final HashMap<String, BasePermission> mPermissions =
7750 new HashMap<String, BasePermission>();
7751
7752 // Mapping from permission tree names to info about them.
7753 final HashMap<String, BasePermission> mPermissionTrees =
7754 new HashMap<String, BasePermission>();
7755
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007756 // Packages that have been uninstalled and still need their external
7757 // storage data deleted.
7758 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7759
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007760 // Packages that have been renamed since they were first installed.
7761 // Keys are the new names of the packages, values are the original
7762 // names. The packages appear everwhere else under their original
7763 // names.
7764 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007766 private final StringBuilder mReadMessages = new StringBuilder();
7767
7768 private static final class PendingPackage extends PackageSettingBase {
7769 final int sharedId;
7770
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007771 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007772 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007773 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007774 this.sharedId = sharedId;
7775 }
7776 }
7777 private final ArrayList<PendingPackage> mPendingPackages
7778 = new ArrayList<PendingPackage>();
7779
7780 Settings() {
7781 File dataDir = Environment.getDataDirectory();
7782 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007783 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7784 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007786 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 FileUtils.setPermissions(systemDir.toString(),
7788 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7789 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7790 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007791 FileUtils.setPermissions(systemSecureDir.toString(),
7792 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7793 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7794 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 mSettingsFilename = new File(systemDir, "packages.xml");
7796 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007797 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007798 }
7799
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007800 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007801 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007802 int pkgFlags, boolean create, boolean add) {
7803 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007804 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007805 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007806 return p;
7807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007808
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007809 PackageSetting peekPackageLP(String name) {
7810 return mPackages.get(name);
7811 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007812 PackageSetting p = mPackages.get(name);
7813 if (p != null && p.codePath.getPath().equals(codePath)) {
7814 return p;
7815 }
7816 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007817 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007820 void setInstallStatus(String pkgName, int status) {
7821 PackageSetting p = mPackages.get(pkgName);
7822 if(p != null) {
7823 if(p.getInstallStatus() != status) {
7824 p.setInstallStatus(status);
7825 }
7826 }
7827 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007828
Jacek Surazski65e13172009-04-28 15:26:38 +02007829 void setInstallerPackageName(String pkgName,
7830 String installerPkgName) {
7831 PackageSetting p = mPackages.get(pkgName);
7832 if(p != null) {
7833 p.setInstallerPackageName(installerPkgName);
7834 }
7835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007836
Jacek Surazski65e13172009-04-28 15:26:38 +02007837 String getInstallerPackageName(String pkgName) {
7838 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007839 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007840 }
7841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 int getInstallStatus(String pkgName) {
7843 PackageSetting p = mPackages.get(pkgName);
7844 if(p != null) {
7845 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 return -1;
7848 }
7849
7850 SharedUserSetting getSharedUserLP(String name,
7851 int pkgFlags, boolean create) {
7852 SharedUserSetting s = mSharedUsers.get(name);
7853 if (s == null) {
7854 if (!create) {
7855 return null;
7856 }
7857 s = new SharedUserSetting(name, pkgFlags);
7858 if (MULTIPLE_APPLICATION_UIDS) {
7859 s.userId = newUserIdLP(s);
7860 } else {
7861 s.userId = FIRST_APPLICATION_UID;
7862 }
7863 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7864 // < 0 means we couldn't assign a userid; fall out and return
7865 // s, which is currently null
7866 if (s.userId >= 0) {
7867 mSharedUsers.put(name, s);
7868 }
7869 }
7870
7871 return s;
7872 }
7873
7874 int disableSystemPackageLP(String name) {
7875 PackageSetting p = mPackages.get(name);
7876 if(p == null) {
7877 Log.w(TAG, "Package:"+name+" is not an installed package");
7878 return -1;
7879 }
7880 PackageSetting dp = mDisabledSysPackages.get(name);
7881 // always make sure the system package code and resource paths dont change
7882 if(dp == null) {
7883 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7884 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7885 }
7886 mDisabledSysPackages.put(name, p);
7887 }
7888 return removePackageLP(name);
7889 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007891 PackageSetting enableSystemPackageLP(String name) {
7892 PackageSetting p = mDisabledSysPackages.get(name);
7893 if(p == null) {
7894 Log.w(TAG, "Package:"+name+" is not disabled");
7895 return null;
7896 }
7897 // Reset flag in ApplicationInfo object
7898 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7899 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7900 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007901 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007902 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 mDisabledSysPackages.remove(name);
7904 return ret;
7905 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007906
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007907 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007908 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 PackageSetting p = mPackages.get(name);
7910 if (p != null) {
7911 if (p.userId == uid) {
7912 return p;
7913 }
7914 reportSettingsProblem(Log.ERROR,
7915 "Adding duplicate package, keeping first: " + name);
7916 return null;
7917 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007918 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919 p.userId = uid;
7920 if (addUserIdLP(uid, p, name)) {
7921 mPackages.put(name, p);
7922 return p;
7923 }
7924 return null;
7925 }
7926
7927 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7928 SharedUserSetting s = mSharedUsers.get(name);
7929 if (s != null) {
7930 if (s.userId == uid) {
7931 return s;
7932 }
7933 reportSettingsProblem(Log.ERROR,
7934 "Adding duplicate shared user, keeping first: " + name);
7935 return null;
7936 }
7937 s = new SharedUserSetting(name, pkgFlags);
7938 s.userId = uid;
7939 if (addUserIdLP(uid, s, name)) {
7940 mSharedUsers.put(name, s);
7941 return s;
7942 }
7943 return null;
7944 }
7945
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007946 // Transfer ownership of permissions from one package to another.
7947 private void transferPermissions(String origPkg, String newPkg) {
7948 // Transfer ownership of permissions to the new package.
7949 for (int i=0; i<2; i++) {
7950 HashMap<String, BasePermission> permissions =
7951 i == 0 ? mPermissionTrees : mPermissions;
7952 for (BasePermission bp : permissions.values()) {
7953 if (origPkg.equals(bp.sourcePackage)) {
7954 if (DEBUG_UPGRADE) Log.v(TAG,
7955 "Moving permission " + bp.name
7956 + " from pkg " + bp.sourcePackage
7957 + " to " + newPkg);
7958 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007959 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007960 bp.perm = null;
7961 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007962 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007963 }
7964 bp.uid = 0;
7965 bp.gids = null;
7966 }
7967 }
7968 }
7969 }
7970
7971 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007972 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007973 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 PackageSetting p = mPackages.get(name);
7975 if (p != null) {
7976 if (!p.codePath.equals(codePath)) {
7977 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007978 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007979 // This is an updated system app with versions in both system
7980 // and data partition. Just let the most recent version
7981 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007982 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007983 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007984 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007985 // Just a change in the code path is not an issue, but
7986 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007987 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007988 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007989 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007990 }
7991 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992 reportSettingsProblem(Log.WARN,
7993 "Package " + name + " shared user changed from "
7994 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7995 + " to "
7996 + (sharedUser != null ? sharedUser.name : "<nothing>")
7997 + "; replacing with new");
7998 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007999 } else {
8000 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8001 // If what we are scanning is a system package, then
8002 // make it so, regardless of whether it was previously
8003 // installed only in the data partition.
8004 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008006 }
8007 }
8008 if (p == null) {
8009 // Create a new PackageSettings entry. this can end up here because
8010 // of code path mismatch or user id mismatch of an updated system partition
8011 if (!create) {
8012 return null;
8013 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008014 if (origPackage != null) {
8015 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008016 p = new PackageSetting(origPackage.name, name, codePath,
8017 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008018 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8019 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008020 // Note that we will retain the new package's signature so
8021 // that we can keep its data.
8022 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008023 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008024 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008025 p.sharedUser = origPackage.sharedUser;
8026 p.userId = origPackage.userId;
8027 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008028 mRenamedPackages.put(name, origPackage.name);
8029 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008030 // Update new package state.
8031 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008032 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008033 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008034 p.setTimeStamp(codePath.lastModified());
8035 p.sharedUser = sharedUser;
8036 if (sharedUser != null) {
8037 p.userId = sharedUser.userId;
8038 } else if (MULTIPLE_APPLICATION_UIDS) {
8039 // Clone the setting here for disabled system packages
8040 PackageSetting dis = mDisabledSysPackages.get(name);
8041 if (dis != null) {
8042 // For disabled packages a new setting is created
8043 // from the existing user id. This still has to be
8044 // added to list of user id's
8045 // Copy signatures from previous setting
8046 if (dis.signatures.mSignatures != null) {
8047 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8048 }
8049 p.userId = dis.userId;
8050 // Clone permissions
8051 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008052 // Clone component info
8053 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8054 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8055 // Add new setting to list of user ids
8056 addUserIdLP(p.userId, p, name);
8057 } else {
8058 // Assign new user id
8059 p.userId = newUserIdLP(p);
8060 }
8061 } else {
8062 p.userId = FIRST_APPLICATION_UID;
8063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 }
8065 if (p.userId < 0) {
8066 reportSettingsProblem(Log.WARN,
8067 "Package " + name + " could not be assigned a valid uid");
8068 return null;
8069 }
8070 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008071 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008072 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008073 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 }
8075 }
8076 return p;
8077 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008078
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008079 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008080 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008081 String codePath = pkg.applicationInfo.sourceDir;
8082 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008083 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008084 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008085 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008086 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008087 p.codePath = new File(codePath);
8088 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008089 }
8090 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008091 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008092 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008093 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008094 p.resourcePath = new File(resourcePath);
8095 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008096 }
8097 // Update version code if needed
8098 if (pkg.mVersionCode != p.versionCode) {
8099 p.versionCode = pkg.mVersionCode;
8100 }
8101 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8102 }
8103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008104 // Utility method that adds a PackageSetting to mPackages and
8105 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008106 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008107 SharedUserSetting sharedUser) {
8108 mPackages.put(name, p);
8109 if (sharedUser != null) {
8110 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8111 reportSettingsProblem(Log.ERROR,
8112 "Package " + p.name + " was user "
8113 + p.sharedUser + " but is now " + sharedUser
8114 + "; I am not changing its files so it will probably fail!");
8115 p.sharedUser.packages.remove(p);
8116 } else if (p.userId != sharedUser.userId) {
8117 reportSettingsProblem(Log.ERROR,
8118 "Package " + p.name + " was user id " + p.userId
8119 + " but is now user " + sharedUser
8120 + " with id " + sharedUser.userId
8121 + "; I am not changing its files so it will probably fail!");
8122 }
8123
8124 sharedUser.packages.add(p);
8125 p.sharedUser = sharedUser;
8126 p.userId = sharedUser.userId;
8127 }
8128 }
8129
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008130 /*
8131 * Update the shared user setting when a package using
8132 * specifying the shared user id is removed. The gids
8133 * associated with each permission of the deleted package
8134 * are removed from the shared user's gid list only if its
8135 * not in use by other permissions of packages in the
8136 * shared user setting.
8137 */
8138 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008139 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008140 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 return;
8142 }
8143 // No sharedUserId
8144 if (deletedPs.sharedUser == null) {
8145 return;
8146 }
8147 SharedUserSetting sus = deletedPs.sharedUser;
8148 // Update permissions
8149 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8150 boolean used = false;
8151 if (!sus.grantedPermissions.contains (eachPerm)) {
8152 continue;
8153 }
8154 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008155 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008156 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008157 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008158 used = true;
8159 break;
8160 }
8161 }
8162 if (!used) {
8163 // can safely delete this permission from list
8164 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165 }
8166 }
8167 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008168 int newGids[] = globalGids;
8169 for (String eachPerm : sus.grantedPermissions) {
8170 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008171 if (bp != null) {
8172 newGids = appendInts(newGids, bp.gids);
8173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008174 }
8175 sus.gids = newGids;
8176 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008178 private int removePackageLP(String name) {
8179 PackageSetting p = mPackages.get(name);
8180 if (p != null) {
8181 mPackages.remove(name);
8182 if (p.sharedUser != null) {
8183 p.sharedUser.packages.remove(p);
8184 if (p.sharedUser.packages.size() == 0) {
8185 mSharedUsers.remove(p.sharedUser.name);
8186 removeUserIdLP(p.sharedUser.userId);
8187 return p.sharedUser.userId;
8188 }
8189 } else {
8190 removeUserIdLP(p.userId);
8191 return p.userId;
8192 }
8193 }
8194 return -1;
8195 }
8196
8197 private boolean addUserIdLP(int uid, Object obj, Object name) {
8198 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8199 return false;
8200 }
8201
8202 if (uid >= FIRST_APPLICATION_UID) {
8203 int N = mUserIds.size();
8204 final int index = uid - FIRST_APPLICATION_UID;
8205 while (index >= N) {
8206 mUserIds.add(null);
8207 N++;
8208 }
8209 if (mUserIds.get(index) != null) {
8210 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008211 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008212 + " name=" + name);
8213 return false;
8214 }
8215 mUserIds.set(index, obj);
8216 } else {
8217 if (mOtherUserIds.get(uid) != null) {
8218 reportSettingsProblem(Log.ERROR,
8219 "Adding duplicate shared id: " + uid
8220 + " name=" + name);
8221 return false;
8222 }
8223 mOtherUserIds.put(uid, obj);
8224 }
8225 return true;
8226 }
8227
8228 public Object getUserIdLP(int uid) {
8229 if (uid >= FIRST_APPLICATION_UID) {
8230 int N = mUserIds.size();
8231 final int index = uid - FIRST_APPLICATION_UID;
8232 return index < N ? mUserIds.get(index) : null;
8233 } else {
8234 return mOtherUserIds.get(uid);
8235 }
8236 }
8237
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008238 private Set<String> findPackagesWithFlag(int flag) {
8239 Set<String> ret = new HashSet<String>();
8240 for (PackageSetting ps : mPackages.values()) {
8241 // Has to match atleast all the flag bits set on flag
8242 if ((ps.pkgFlags & flag) == flag) {
8243 ret.add(ps.name);
8244 }
8245 }
8246 return ret;
8247 }
8248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008249 private void removeUserIdLP(int uid) {
8250 if (uid >= FIRST_APPLICATION_UID) {
8251 int N = mUserIds.size();
8252 final int index = uid - FIRST_APPLICATION_UID;
8253 if (index < N) mUserIds.set(index, null);
8254 } else {
8255 mOtherUserIds.remove(uid);
8256 }
8257 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259 void writeLP() {
8260 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8261
8262 // Keep the old settings around until we know the new ones have
8263 // been successfully written.
8264 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008265 // Presence of backup settings file indicates that we failed
8266 // to persist settings earlier. So preserve the older
8267 // backup for future reference since the current settings
8268 // might have been corrupted.
8269 if (!mBackupSettingsFilename.exists()) {
8270 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008271 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008272 return;
8273 }
8274 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008275 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008276 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008278 }
8279
8280 mPastSignatures.clear();
8281
8282 try {
8283 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8284
8285 //XmlSerializer serializer = XmlUtils.serializerInstance();
8286 XmlSerializer serializer = new FastXmlSerializer();
8287 serializer.setOutput(str, "utf-8");
8288 serializer.startDocument(null, true);
8289 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8290
8291 serializer.startTag(null, "packages");
8292
8293 serializer.startTag(null, "permission-trees");
8294 for (BasePermission bp : mPermissionTrees.values()) {
8295 writePermission(serializer, bp);
8296 }
8297 serializer.endTag(null, "permission-trees");
8298
8299 serializer.startTag(null, "permissions");
8300 for (BasePermission bp : mPermissions.values()) {
8301 writePermission(serializer, bp);
8302 }
8303 serializer.endTag(null, "permissions");
8304
8305 for (PackageSetting pkg : mPackages.values()) {
8306 writePackage(serializer, pkg);
8307 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008309 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8310 writeDisabledSysPackage(serializer, pkg);
8311 }
8312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008313 serializer.startTag(null, "preferred-activities");
8314 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8315 serializer.startTag(null, "item");
8316 pa.writeToXml(serializer);
8317 serializer.endTag(null, "item");
8318 }
8319 serializer.endTag(null, "preferred-activities");
8320
8321 for (SharedUserSetting usr : mSharedUsers.values()) {
8322 serializer.startTag(null, "shared-user");
8323 serializer.attribute(null, "name", usr.name);
8324 serializer.attribute(null, "userId",
8325 Integer.toString(usr.userId));
8326 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8327 serializer.startTag(null, "perms");
8328 for (String name : usr.grantedPermissions) {
8329 serializer.startTag(null, "item");
8330 serializer.attribute(null, "name", name);
8331 serializer.endTag(null, "item");
8332 }
8333 serializer.endTag(null, "perms");
8334 serializer.endTag(null, "shared-user");
8335 }
8336
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008337 if (mPackagesToBeCleaned.size() > 0) {
8338 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8339 serializer.startTag(null, "cleaning-package");
8340 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8341 serializer.endTag(null, "cleaning-package");
8342 }
8343 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008344
8345 if (mRenamedPackages.size() > 0) {
8346 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8347 serializer.startTag(null, "renamed-package");
8348 serializer.attribute(null, "new", e.getKey());
8349 serializer.attribute(null, "old", e.getValue());
8350 serializer.endTag(null, "renamed-package");
8351 }
8352 }
8353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008354 serializer.endTag(null, "packages");
8355
8356 serializer.endDocument();
8357
8358 str.flush();
8359 str.close();
8360
8361 // New settings successfully written, old ones are no longer
8362 // needed.
8363 mBackupSettingsFilename.delete();
8364 FileUtils.setPermissions(mSettingsFilename.toString(),
8365 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8366 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8367 |FileUtils.S_IROTH,
8368 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008369
8370 // Write package list file now, use a JournaledFile.
8371 //
8372 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8373 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8374
8375 str = new FileOutputStream(journal.chooseForWrite());
8376 try {
8377 StringBuilder sb = new StringBuilder();
8378 for (PackageSetting pkg : mPackages.values()) {
8379 ApplicationInfo ai = pkg.pkg.applicationInfo;
8380 String dataPath = ai.dataDir;
8381 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8382
8383 // Avoid any application that has a space in its path
8384 // or that is handled by the system.
8385 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8386 continue;
8387
8388 // we store on each line the following information for now:
8389 //
8390 // pkgName - package name
8391 // userId - application-specific user id
8392 // debugFlag - 0 or 1 if the package is debuggable.
8393 // dataPath - path to package's data path
8394 //
8395 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8396 //
8397 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8398 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8399 // system/core/run-as/run-as.c
8400 //
8401 sb.setLength(0);
8402 sb.append(ai.packageName);
8403 sb.append(" ");
8404 sb.append((int)ai.uid);
8405 sb.append(isDebug ? " 1 " : " 0 ");
8406 sb.append(dataPath);
8407 sb.append("\n");
8408 str.write(sb.toString().getBytes());
8409 }
8410 str.flush();
8411 str.close();
8412 journal.commit();
8413 }
8414 catch (Exception e) {
8415 journal.rollback();
8416 }
8417
8418 FileUtils.setPermissions(mPackageListFilename.toString(),
8419 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8420 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8421 |FileUtils.S_IROTH,
8422 -1, -1);
8423
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008424 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008425
8426 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008427 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 -08008428 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008429 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 -08008430 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008431 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008432 if (mSettingsFilename.exists()) {
8433 if (!mSettingsFilename.delete()) {
8434 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8435 }
8436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008437 //Debug.stopMethodTracing();
8438 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008439
8440 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008441 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008442 serializer.startTag(null, "updated-package");
8443 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008444 if (pkg.realName != null) {
8445 serializer.attribute(null, "realName", pkg.realName);
8446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008447 serializer.attribute(null, "codePath", pkg.codePathString);
8448 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008449 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008450 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8451 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8452 }
8453 if (pkg.sharedUser == null) {
8454 serializer.attribute(null, "userId",
8455 Integer.toString(pkg.userId));
8456 } else {
8457 serializer.attribute(null, "sharedUserId",
8458 Integer.toString(pkg.userId));
8459 }
8460 serializer.startTag(null, "perms");
8461 if (pkg.sharedUser == null) {
8462 // If this is a shared user, the permissions will
8463 // be written there. We still need to write an
8464 // empty permissions list so permissionsFixed will
8465 // be set.
8466 for (final String name : pkg.grantedPermissions) {
8467 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008468 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008469 // We only need to write signature or system permissions but this wont
8470 // match the semantics of grantedPermissions. So write all permissions.
8471 serializer.startTag(null, "item");
8472 serializer.attribute(null, "name", name);
8473 serializer.endTag(null, "item");
8474 }
8475 }
8476 }
8477 serializer.endTag(null, "perms");
8478 serializer.endTag(null, "updated-package");
8479 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008480
8481 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008482 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008483 serializer.startTag(null, "package");
8484 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008485 if (pkg.realName != null) {
8486 serializer.attribute(null, "realName", pkg.realName);
8487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008488 serializer.attribute(null, "codePath", pkg.codePathString);
8489 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8490 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8491 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008492 serializer.attribute(null, "flags",
8493 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008495 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008496 if (pkg.sharedUser == null) {
8497 serializer.attribute(null, "userId",
8498 Integer.toString(pkg.userId));
8499 } else {
8500 serializer.attribute(null, "sharedUserId",
8501 Integer.toString(pkg.userId));
8502 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008503 if (pkg.uidError) {
8504 serializer.attribute(null, "uidError", "true");
8505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8507 serializer.attribute(null, "enabled",
8508 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8509 ? "true" : "false");
8510 }
8511 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8512 serializer.attribute(null, "installStatus", "false");
8513 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008514 if (pkg.installerPackageName != null) {
8515 serializer.attribute(null, "installer", pkg.installerPackageName);
8516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8518 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8519 serializer.startTag(null, "perms");
8520 if (pkg.sharedUser == null) {
8521 // If this is a shared user, the permissions will
8522 // be written there. We still need to write an
8523 // empty permissions list so permissionsFixed will
8524 // be set.
8525 for (final String name : pkg.grantedPermissions) {
8526 serializer.startTag(null, "item");
8527 serializer.attribute(null, "name", name);
8528 serializer.endTag(null, "item");
8529 }
8530 }
8531 serializer.endTag(null, "perms");
8532 }
8533 if (pkg.disabledComponents.size() > 0) {
8534 serializer.startTag(null, "disabled-components");
8535 for (final String name : pkg.disabledComponents) {
8536 serializer.startTag(null, "item");
8537 serializer.attribute(null, "name", name);
8538 serializer.endTag(null, "item");
8539 }
8540 serializer.endTag(null, "disabled-components");
8541 }
8542 if (pkg.enabledComponents.size() > 0) {
8543 serializer.startTag(null, "enabled-components");
8544 for (final String name : pkg.enabledComponents) {
8545 serializer.startTag(null, "item");
8546 serializer.attribute(null, "name", name);
8547 serializer.endTag(null, "item");
8548 }
8549 serializer.endTag(null, "enabled-components");
8550 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008552 serializer.endTag(null, "package");
8553 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008555 void writePermission(XmlSerializer serializer, BasePermission bp)
8556 throws XmlPullParserException, java.io.IOException {
8557 if (bp.type != BasePermission.TYPE_BUILTIN
8558 && bp.sourcePackage != null) {
8559 serializer.startTag(null, "item");
8560 serializer.attribute(null, "name", bp.name);
8561 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008562 if (bp.protectionLevel !=
8563 PermissionInfo.PROTECTION_NORMAL) {
8564 serializer.attribute(null, "protection",
8565 Integer.toString(bp.protectionLevel));
8566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008567 if (DEBUG_SETTINGS) Log.v(TAG,
8568 "Writing perm: name=" + bp.name + " type=" + bp.type);
8569 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8570 PermissionInfo pi = bp.perm != null ? bp.perm.info
8571 : bp.pendingInfo;
8572 if (pi != null) {
8573 serializer.attribute(null, "type", "dynamic");
8574 if (pi.icon != 0) {
8575 serializer.attribute(null, "icon",
8576 Integer.toString(pi.icon));
8577 }
8578 if (pi.nonLocalizedLabel != null) {
8579 serializer.attribute(null, "label",
8580 pi.nonLocalizedLabel.toString());
8581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008582 }
8583 }
8584 serializer.endTag(null, "item");
8585 }
8586 }
8587
8588 String getReadMessagesLP() {
8589 return mReadMessages.toString();
8590 }
8591
Oscar Montemayora8529f62009-11-18 10:14:20 -08008592 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8594 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008595 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596 while(its.hasNext()) {
8597 String key = its.next();
8598 PackageSetting ps = mPackages.get(key);
8599 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008600 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 }
8602 }
8603 return ret;
8604 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008606 boolean readLP() {
8607 FileInputStream str = null;
8608 if (mBackupSettingsFilename.exists()) {
8609 try {
8610 str = new FileInputStream(mBackupSettingsFilename);
8611 mReadMessages.append("Reading from backup settings file\n");
8612 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008613 if (mSettingsFilename.exists()) {
8614 // If both the backup and settings file exist, we
8615 // ignore the settings since it might have been
8616 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008617 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008618 mSettingsFilename.delete();
8619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008620 } catch (java.io.IOException e) {
8621 // We'll try for the normal settings file.
8622 }
8623 }
8624
8625 mPastSignatures.clear();
8626
8627 try {
8628 if (str == null) {
8629 if (!mSettingsFilename.exists()) {
8630 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008631 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008632 return false;
8633 }
8634 str = new FileInputStream(mSettingsFilename);
8635 }
8636 XmlPullParser parser = Xml.newPullParser();
8637 parser.setInput(str, null);
8638
8639 int type;
8640 while ((type=parser.next()) != XmlPullParser.START_TAG
8641 && type != XmlPullParser.END_DOCUMENT) {
8642 ;
8643 }
8644
8645 if (type != XmlPullParser.START_TAG) {
8646 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008647 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008648 return false;
8649 }
8650
8651 int outerDepth = parser.getDepth();
8652 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8653 && (type != XmlPullParser.END_TAG
8654 || parser.getDepth() > outerDepth)) {
8655 if (type == XmlPullParser.END_TAG
8656 || type == XmlPullParser.TEXT) {
8657 continue;
8658 }
8659
8660 String tagName = parser.getName();
8661 if (tagName.equals("package")) {
8662 readPackageLP(parser);
8663 } else if (tagName.equals("permissions")) {
8664 readPermissionsLP(mPermissions, parser);
8665 } else if (tagName.equals("permission-trees")) {
8666 readPermissionsLP(mPermissionTrees, parser);
8667 } else if (tagName.equals("shared-user")) {
8668 readSharedUserLP(parser);
8669 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008670 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008671 } else if (tagName.equals("preferred-activities")) {
8672 readPreferredActivitiesLP(parser);
8673 } else if(tagName.equals("updated-package")) {
8674 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008675 } else if (tagName.equals("cleaning-package")) {
8676 String name = parser.getAttributeValue(null, "name");
8677 if (name != null) {
8678 mPackagesToBeCleaned.add(name);
8679 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008680 } else if (tagName.equals("renamed-package")) {
8681 String nname = parser.getAttributeValue(null, "new");
8682 String oname = parser.getAttributeValue(null, "old");
8683 if (nname != null && oname != null) {
8684 mRenamedPackages.put(nname, oname);
8685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008687 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 + parser.getName());
8689 XmlUtils.skipCurrentTag(parser);
8690 }
8691 }
8692
8693 str.close();
8694
8695 } catch(XmlPullParserException e) {
8696 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008697 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008698
8699 } catch(java.io.IOException e) {
8700 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008701 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008702
8703 }
8704
8705 int N = mPendingPackages.size();
8706 for (int i=0; i<N; i++) {
8707 final PendingPackage pp = mPendingPackages.get(i);
8708 Object idObj = getUserIdLP(pp.sharedId);
8709 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008710 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008711 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008712 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008713 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008714 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008715 + pp.name);
8716 continue;
8717 }
8718 p.copyFrom(pp);
8719 } else if (idObj != null) {
8720 String msg = "Bad package setting: package " + pp.name
8721 + " has shared uid " + pp.sharedId
8722 + " that is not a shared uid\n";
8723 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008724 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008725 } else {
8726 String msg = "Bad package setting: package " + pp.name
8727 + " has shared uid " + pp.sharedId
8728 + " that is not defined\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 }
8732 }
8733 mPendingPackages.clear();
8734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008735 mReadMessages.append("Read completed successfully: "
8736 + mPackages.size() + " packages, "
8737 + mSharedUsers.size() + " shared uids\n");
8738
8739 return true;
8740 }
8741
8742 private int readInt(XmlPullParser parser, String ns, String name,
8743 int defValue) {
8744 String v = parser.getAttributeValue(ns, name);
8745 try {
8746 if (v == null) {
8747 return defValue;
8748 }
8749 return Integer.parseInt(v);
8750 } catch (NumberFormatException e) {
8751 reportSettingsProblem(Log.WARN,
8752 "Error in package manager settings: attribute " +
8753 name + " has bad integer value " + v + " at "
8754 + parser.getPositionDescription());
8755 }
8756 return defValue;
8757 }
8758
8759 private void readPermissionsLP(HashMap<String, BasePermission> out,
8760 XmlPullParser parser)
8761 throws IOException, XmlPullParserException {
8762 int outerDepth = parser.getDepth();
8763 int type;
8764 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8765 && (type != XmlPullParser.END_TAG
8766 || parser.getDepth() > outerDepth)) {
8767 if (type == XmlPullParser.END_TAG
8768 || type == XmlPullParser.TEXT) {
8769 continue;
8770 }
8771
8772 String tagName = parser.getName();
8773 if (tagName.equals("item")) {
8774 String name = parser.getAttributeValue(null, "name");
8775 String sourcePackage = parser.getAttributeValue(null, "package");
8776 String ptype = parser.getAttributeValue(null, "type");
8777 if (name != null && sourcePackage != null) {
8778 boolean dynamic = "dynamic".equals(ptype);
8779 BasePermission bp = new BasePermission(name, sourcePackage,
8780 dynamic
8781 ? BasePermission.TYPE_DYNAMIC
8782 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008783 bp.protectionLevel = readInt(parser, null, "protection",
8784 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008785 if (dynamic) {
8786 PermissionInfo pi = new PermissionInfo();
8787 pi.packageName = sourcePackage.intern();
8788 pi.name = name.intern();
8789 pi.icon = readInt(parser, null, "icon", 0);
8790 pi.nonLocalizedLabel = parser.getAttributeValue(
8791 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008792 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008793 bp.pendingInfo = pi;
8794 }
8795 out.put(bp.name, bp);
8796 } else {
8797 reportSettingsProblem(Log.WARN,
8798 "Error in package manager settings: permissions has"
8799 + " no name at " + parser.getPositionDescription());
8800 }
8801 } else {
8802 reportSettingsProblem(Log.WARN,
8803 "Unknown element reading permissions: "
8804 + parser.getName() + " at "
8805 + parser.getPositionDescription());
8806 }
8807 XmlUtils.skipCurrentTag(parser);
8808 }
8809 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008811 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008812 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008813 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008814 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008815 String codePathStr = parser.getAttributeValue(null, "codePath");
8816 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008817 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008818 resourcePathStr = codePathStr;
8819 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008820 String version = parser.getAttributeValue(null, "version");
8821 int versionCode = 0;
8822 if (version != null) {
8823 try {
8824 versionCode = Integer.parseInt(version);
8825 } catch (NumberFormatException e) {
8826 }
8827 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008829 int pkgFlags = 0;
8830 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008831 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008832 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008833 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008834 String timeStampStr = parser.getAttributeValue(null, "ts");
8835 if (timeStampStr != null) {
8836 try {
8837 long timeStamp = Long.parseLong(timeStampStr);
8838 ps.setTimeStamp(timeStamp, timeStampStr);
8839 } catch (NumberFormatException e) {
8840 }
8841 }
8842 String idStr = parser.getAttributeValue(null, "userId");
8843 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8844 if(ps.userId <= 0) {
8845 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8846 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8847 }
8848 int outerDepth = parser.getDepth();
8849 int type;
8850 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8851 && (type != XmlPullParser.END_TAG
8852 || parser.getDepth() > outerDepth)) {
8853 if (type == XmlPullParser.END_TAG
8854 || type == XmlPullParser.TEXT) {
8855 continue;
8856 }
8857
8858 String tagName = parser.getName();
8859 if (tagName.equals("perms")) {
8860 readGrantedPermissionsLP(parser,
8861 ps.grantedPermissions);
8862 } else {
8863 reportSettingsProblem(Log.WARN,
8864 "Unknown element under <updated-package>: "
8865 + parser.getName());
8866 XmlUtils.skipCurrentTag(parser);
8867 }
8868 }
8869 mDisabledSysPackages.put(name, ps);
8870 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008872 private void readPackageLP(XmlPullParser parser)
8873 throws XmlPullParserException, IOException {
8874 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008875 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008876 String idStr = null;
8877 String sharedIdStr = null;
8878 String codePathStr = null;
8879 String resourcePathStr = null;
8880 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008881 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008882 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 int pkgFlags = 0;
8884 String timeStampStr;
8885 long timeStamp = 0;
8886 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008887 String version = null;
8888 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008889 try {
8890 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008891 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008893 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008894 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8895 codePathStr = parser.getAttributeValue(null, "codePath");
8896 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008897 version = parser.getAttributeValue(null, "version");
8898 if (version != null) {
8899 try {
8900 versionCode = Integer.parseInt(version);
8901 } catch (NumberFormatException e) {
8902 }
8903 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008904 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008905
8906 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008907 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008908 try {
8909 pkgFlags = Integer.parseInt(systemStr);
8910 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008911 }
8912 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008913 // For backward compatibility
8914 systemStr = parser.getAttributeValue(null, "system");
8915 if (systemStr != null) {
8916 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8917 } else {
8918 // Old settings that don't specify system... just treat
8919 // them as system, good enough.
8920 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8921 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008922 }
8923 timeStampStr = parser.getAttributeValue(null, "ts");
8924 if (timeStampStr != null) {
8925 try {
8926 timeStamp = Long.parseLong(timeStampStr);
8927 } catch (NumberFormatException e) {
8928 }
8929 }
8930 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8931 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8932 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8933 if (resourcePathStr == null) {
8934 resourcePathStr = codePathStr;
8935 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008936 if (realName != null) {
8937 realName = realName.intern();
8938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008939 if (name == null) {
8940 reportSettingsProblem(Log.WARN,
8941 "Error in package manager settings: <package> has no name at "
8942 + parser.getPositionDescription());
8943 } else if (codePathStr == null) {
8944 reportSettingsProblem(Log.WARN,
8945 "Error in package manager settings: <package> has no codePath at "
8946 + parser.getPositionDescription());
8947 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008948 packageSetting = addPackageLP(name.intern(), realName,
8949 new File(codePathStr), new File(resourcePathStr),
8950 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008951 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8952 + ": userId=" + userId + " pkg=" + packageSetting);
8953 if (packageSetting == null) {
8954 reportSettingsProblem(Log.ERROR,
8955 "Failure adding uid " + userId
8956 + " while parsing settings at "
8957 + parser.getPositionDescription());
8958 } else {
8959 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8960 }
8961 } else if (sharedIdStr != null) {
8962 userId = sharedIdStr != null
8963 ? Integer.parseInt(sharedIdStr) : 0;
8964 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008965 packageSetting = new PendingPackage(name.intern(), realName,
8966 new File(codePathStr), new File(resourcePathStr),
8967 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008968 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8969 mPendingPackages.add((PendingPackage) packageSetting);
8970 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8971 + ": sharedUserId=" + userId + " pkg="
8972 + packageSetting);
8973 } else {
8974 reportSettingsProblem(Log.WARN,
8975 "Error in package manager settings: package "
8976 + name + " has bad sharedId " + sharedIdStr
8977 + " at " + parser.getPositionDescription());
8978 }
8979 } else {
8980 reportSettingsProblem(Log.WARN,
8981 "Error in package manager settings: package "
8982 + name + " has bad userId " + idStr + " at "
8983 + parser.getPositionDescription());
8984 }
8985 } catch (NumberFormatException e) {
8986 reportSettingsProblem(Log.WARN,
8987 "Error in package manager settings: package "
8988 + name + " has bad userId " + idStr + " at "
8989 + parser.getPositionDescription());
8990 }
8991 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008992 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008993 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008994 final String enabledStr = parser.getAttributeValue(null, "enabled");
8995 if (enabledStr != null) {
8996 if (enabledStr.equalsIgnoreCase("true")) {
8997 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8998 } else if (enabledStr.equalsIgnoreCase("false")) {
8999 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9000 } else if (enabledStr.equalsIgnoreCase("default")) {
9001 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9002 } else {
9003 reportSettingsProblem(Log.WARN,
9004 "Error in package manager settings: package "
9005 + name + " has bad enabled value: " + idStr
9006 + " at " + parser.getPositionDescription());
9007 }
9008 } else {
9009 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9010 }
9011 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9012 if (installStatusStr != null) {
9013 if (installStatusStr.equalsIgnoreCase("false")) {
9014 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9015 } else {
9016 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9017 }
9018 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009020 int outerDepth = parser.getDepth();
9021 int type;
9022 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9023 && (type != XmlPullParser.END_TAG
9024 || parser.getDepth() > outerDepth)) {
9025 if (type == XmlPullParser.END_TAG
9026 || type == XmlPullParser.TEXT) {
9027 continue;
9028 }
9029
9030 String tagName = parser.getName();
9031 if (tagName.equals("disabled-components")) {
9032 readDisabledComponentsLP(packageSetting, parser);
9033 } else if (tagName.equals("enabled-components")) {
9034 readEnabledComponentsLP(packageSetting, parser);
9035 } else if (tagName.equals("sigs")) {
9036 packageSetting.signatures.readXml(parser, mPastSignatures);
9037 } else if (tagName.equals("perms")) {
9038 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009039 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009040 packageSetting.permissionsFixed = true;
9041 } else {
9042 reportSettingsProblem(Log.WARN,
9043 "Unknown element under <package>: "
9044 + parser.getName());
9045 XmlUtils.skipCurrentTag(parser);
9046 }
9047 }
9048 } else {
9049 XmlUtils.skipCurrentTag(parser);
9050 }
9051 }
9052
9053 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9054 XmlPullParser parser)
9055 throws IOException, XmlPullParserException {
9056 int outerDepth = parser.getDepth();
9057 int type;
9058 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9059 && (type != XmlPullParser.END_TAG
9060 || parser.getDepth() > outerDepth)) {
9061 if (type == XmlPullParser.END_TAG
9062 || type == XmlPullParser.TEXT) {
9063 continue;
9064 }
9065
9066 String tagName = parser.getName();
9067 if (tagName.equals("item")) {
9068 String name = parser.getAttributeValue(null, "name");
9069 if (name != null) {
9070 packageSetting.disabledComponents.add(name.intern());
9071 } else {
9072 reportSettingsProblem(Log.WARN,
9073 "Error in package manager settings: <disabled-components> has"
9074 + " no name at " + parser.getPositionDescription());
9075 }
9076 } else {
9077 reportSettingsProblem(Log.WARN,
9078 "Unknown element under <disabled-components>: "
9079 + parser.getName());
9080 }
9081 XmlUtils.skipCurrentTag(parser);
9082 }
9083 }
9084
9085 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9086 XmlPullParser parser)
9087 throws IOException, XmlPullParserException {
9088 int outerDepth = parser.getDepth();
9089 int type;
9090 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9091 && (type != XmlPullParser.END_TAG
9092 || parser.getDepth() > outerDepth)) {
9093 if (type == XmlPullParser.END_TAG
9094 || type == XmlPullParser.TEXT) {
9095 continue;
9096 }
9097
9098 String tagName = parser.getName();
9099 if (tagName.equals("item")) {
9100 String name = parser.getAttributeValue(null, "name");
9101 if (name != null) {
9102 packageSetting.enabledComponents.add(name.intern());
9103 } else {
9104 reportSettingsProblem(Log.WARN,
9105 "Error in package manager settings: <enabled-components> has"
9106 + " no name at " + parser.getPositionDescription());
9107 }
9108 } else {
9109 reportSettingsProblem(Log.WARN,
9110 "Unknown element under <enabled-components>: "
9111 + parser.getName());
9112 }
9113 XmlUtils.skipCurrentTag(parser);
9114 }
9115 }
9116
9117 private void readSharedUserLP(XmlPullParser parser)
9118 throws XmlPullParserException, IOException {
9119 String name = null;
9120 String idStr = null;
9121 int pkgFlags = 0;
9122 SharedUserSetting su = null;
9123 try {
9124 name = parser.getAttributeValue(null, "name");
9125 idStr = parser.getAttributeValue(null, "userId");
9126 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9127 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9128 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9129 }
9130 if (name == null) {
9131 reportSettingsProblem(Log.WARN,
9132 "Error in package manager settings: <shared-user> has no name at "
9133 + parser.getPositionDescription());
9134 } else if (userId == 0) {
9135 reportSettingsProblem(Log.WARN,
9136 "Error in package manager settings: shared-user "
9137 + name + " has bad userId " + idStr + " at "
9138 + parser.getPositionDescription());
9139 } else {
9140 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9141 reportSettingsProblem(Log.ERROR,
9142 "Occurred while parsing settings at "
9143 + parser.getPositionDescription());
9144 }
9145 }
9146 } catch (NumberFormatException e) {
9147 reportSettingsProblem(Log.WARN,
9148 "Error in package manager settings: package "
9149 + name + " has bad userId " + idStr + " at "
9150 + parser.getPositionDescription());
9151 };
9152
9153 if (su != null) {
9154 int outerDepth = parser.getDepth();
9155 int type;
9156 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9157 && (type != XmlPullParser.END_TAG
9158 || parser.getDepth() > outerDepth)) {
9159 if (type == XmlPullParser.END_TAG
9160 || type == XmlPullParser.TEXT) {
9161 continue;
9162 }
9163
9164 String tagName = parser.getName();
9165 if (tagName.equals("sigs")) {
9166 su.signatures.readXml(parser, mPastSignatures);
9167 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009168 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169 } else {
9170 reportSettingsProblem(Log.WARN,
9171 "Unknown element under <shared-user>: "
9172 + parser.getName());
9173 XmlUtils.skipCurrentTag(parser);
9174 }
9175 }
9176
9177 } else {
9178 XmlUtils.skipCurrentTag(parser);
9179 }
9180 }
9181
9182 private void readGrantedPermissionsLP(XmlPullParser parser,
9183 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9184 int outerDepth = parser.getDepth();
9185 int type;
9186 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9187 && (type != XmlPullParser.END_TAG
9188 || parser.getDepth() > outerDepth)) {
9189 if (type == XmlPullParser.END_TAG
9190 || type == XmlPullParser.TEXT) {
9191 continue;
9192 }
9193
9194 String tagName = parser.getName();
9195 if (tagName.equals("item")) {
9196 String name = parser.getAttributeValue(null, "name");
9197 if (name != null) {
9198 outPerms.add(name.intern());
9199 } else {
9200 reportSettingsProblem(Log.WARN,
9201 "Error in package manager settings: <perms> has"
9202 + " no name at " + parser.getPositionDescription());
9203 }
9204 } else {
9205 reportSettingsProblem(Log.WARN,
9206 "Unknown element under <perms>: "
9207 + parser.getName());
9208 }
9209 XmlUtils.skipCurrentTag(parser);
9210 }
9211 }
9212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009213 private void readPreferredActivitiesLP(XmlPullParser parser)
9214 throws XmlPullParserException, IOException {
9215 int outerDepth = parser.getDepth();
9216 int type;
9217 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9218 && (type != XmlPullParser.END_TAG
9219 || parser.getDepth() > outerDepth)) {
9220 if (type == XmlPullParser.END_TAG
9221 || type == XmlPullParser.TEXT) {
9222 continue;
9223 }
9224
9225 String tagName = parser.getName();
9226 if (tagName.equals("item")) {
9227 PreferredActivity pa = new PreferredActivity(parser);
9228 if (pa.mParseError == null) {
9229 mPreferredActivities.addFilter(pa);
9230 } else {
9231 reportSettingsProblem(Log.WARN,
9232 "Error in package manager settings: <preferred-activity> "
9233 + pa.mParseError + " at "
9234 + parser.getPositionDescription());
9235 }
9236 } else {
9237 reportSettingsProblem(Log.WARN,
9238 "Unknown element under <preferred-activities>: "
9239 + parser.getName());
9240 XmlUtils.skipCurrentTag(parser);
9241 }
9242 }
9243 }
9244
9245 // Returns -1 if we could not find an available UserId to assign
9246 private int newUserIdLP(Object obj) {
9247 // Let's be stupidly inefficient for now...
9248 final int N = mUserIds.size();
9249 for (int i=0; i<N; i++) {
9250 if (mUserIds.get(i) == null) {
9251 mUserIds.set(i, obj);
9252 return FIRST_APPLICATION_UID + i;
9253 }
9254 }
9255
9256 // None left?
9257 if (N >= MAX_APPLICATION_UIDS) {
9258 return -1;
9259 }
9260
9261 mUserIds.add(obj);
9262 return FIRST_APPLICATION_UID + N;
9263 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009265 public PackageSetting getDisabledSystemPkg(String name) {
9266 synchronized(mPackages) {
9267 PackageSetting ps = mDisabledSysPackages.get(name);
9268 return ps;
9269 }
9270 }
9271
9272 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9273 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9274 if (Config.LOGV) {
9275 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9276 + " componentName = " + componentInfo.name);
9277 Log.v(TAG, "enabledComponents: "
9278 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9279 Log.v(TAG, "disabledComponents: "
9280 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9281 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009282 if (packageSettings == null) {
9283 if (false) {
9284 Log.w(TAG, "WAITING FOR DEBUGGER");
9285 Debug.waitForDebugger();
9286 Log.i(TAG, "We will crash!");
9287 }
9288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009289 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9290 || ((componentInfo.enabled
9291 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9292 || (componentInfo.applicationInfo.enabled
9293 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9294 && !packageSettings.disabledComponents.contains(componentInfo.name))
9295 || packageSettings.enabledComponents.contains(componentInfo.name));
9296 }
9297 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009298
9299 // ------- apps on sdcard specific code -------
9300 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009301 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009302 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009303 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009304 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009305
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009306 private String getEncryptKey() {
9307 try {
9308 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9309 if (sdEncKey == null) {
9310 sdEncKey = SystemKeyStore.getInstance().
9311 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9312 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009313 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009314 return null;
9315 }
9316 }
9317 return sdEncKey;
9318 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009319 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009320 return null;
9321 }
9322 }
9323
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009324 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009325 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009326 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009327 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009328 if (list != null) {
9329 int idx = 0;
9330 int idList[] = new int[MAX_CONTAINERS];
9331 boolean neverFound = true;
9332 for (String name : list) {
9333 // Ignore null entries
9334 if (name == null) {
9335 continue;
9336 }
9337 int sidx = name.indexOf(prefix);
9338 if (sidx == -1) {
9339 // Not a temp file. just ignore
9340 continue;
9341 }
9342 String subStr = name.substring(sidx + prefix.length());
9343 idList[idx] = -1;
9344 if (subStr != null) {
9345 try {
9346 int cid = Integer.parseInt(subStr);
9347 idList[idx++] = cid;
9348 neverFound = false;
9349 } catch (NumberFormatException e) {
9350 }
9351 }
9352 }
9353 if (!neverFound) {
9354 // Sort idList
9355 Arrays.sort(idList);
9356 for (int j = 1; j <= idList.length; j++) {
9357 if (idList[j-1] != j) {
9358 tmpIdx = j;
9359 break;
9360 }
9361 }
9362 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009363 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009364 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009365 }
9366
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009367 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009368 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009369 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009370 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9371 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9372 throw new SecurityException("Media status can only be updated by the system");
9373 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009374 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009375 Log.i(TAG, "Updating external media status from " +
9376 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9377 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009378 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9379 mediaStatus+", mMediaMounted=" + mMediaMounted);
9380 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009381 if (reportStatus) {
9382 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9383 }
9384 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009385 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009386 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009387 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009388 // Queue up an async operation since the package installation may take a little while.
9389 mHandler.post(new Runnable() {
9390 public void run() {
9391 mHandler.removeCallbacks(this);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009392 try {
9393 updateExternalMediaStatusInner(mediaStatus);
9394 } finally {
9395 if (reportStatus) {
9396 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9397 }
9398 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009399 }
9400 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009401 }
9402
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009403 private void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009404 // If we are up here that means there are packages to be
9405 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009406 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009407 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009408 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009409 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009410 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009411
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009412 int uidList[] = new int[list.length];
9413 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009414 HashSet<String> removeCids = new HashSet<String>();
9415 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009416 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009417 for (String cid : list) {
9418 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009419 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9420 boolean failed = true;
9421 try {
9422 String pkgName = args.getPackageName();
9423 if (pkgName == null) {
9424 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009425 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009426 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9427 PackageSetting ps = mSettings.mPackages.get(pkgName);
9428 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009429 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009430 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9431 " corresponds to pkg : " + pkgName +
9432 " at code path: " + ps.codePathString);
9433 // We do have a valid package installed on sdcard
9434 processCids.put(args, ps.codePathString);
9435 failed = false;
9436 int uid = ps.userId;
9437 if (uid != -1) {
9438 uidList[num++] = uid;
9439 }
9440 }
9441 } finally {
9442 if (failed) {
9443 // Stale container on sdcard. Just delete
9444 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9445 removeCids.add(cid);
9446 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009447 }
9448 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009449 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009450 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009451 int uidArr[] = null;
9452 if (num > 0) {
9453 // Sort uid list
9454 Arrays.sort(uidList, 0, num);
9455 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009456 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009457 uidArr[0] = uidList[0];
9458 int di = 0;
9459 for (int i = 1; i < num; i++) {
9460 if (uidList[i-1] != uidList[i]) {
9461 uidArr[di++] = uidList[i];
9462 }
9463 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009464 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009465 // Process packages with valid entries.
9466 if (mediaStatus) {
9467 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009468 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009469 startCleaningPackages();
9470 } else {
9471 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009472 unloadMediaPackages(processCids, uidArr);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009473 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009474 }
9475
9476 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9477 ArrayList<String> pkgList, int uidArr[]) {
9478 int size = pkgList.size();
9479 if (size > 0) {
9480 // Send broadcasts here
9481 Bundle extras = new Bundle();
9482 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9483 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009484 if (uidArr != null) {
9485 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9486 }
9487 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9488 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009489 sendPackageBroadcast(action, null, extras);
9490 }
9491 }
9492
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009493 /*
9494 * Look at potentially valid container ids from processCids
9495 * If package information doesn't match the one on record
9496 * or package scanning fails, the cid is added to list of
9497 * removeCids and cleaned up. Since cleaning up containers
9498 * involves destroying them, we do not want any parse
9499 * references to such stale containers. So force gc's
9500 * to avoid unnecessary crashes.
9501 */
9502 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009503 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009504 ArrayList<String> pkgList = new ArrayList<String>();
9505 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009506 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009507 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009508 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009509 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9510 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009511 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009512 try {
9513 // Make sure there are no container errors first.
9514 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9515 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009516 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009517 " when installing from sdcard");
9518 continue;
9519 }
9520 // Check code path here.
9521 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009522 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009523 " does not match one in settings " + codePath);
9524 continue;
9525 }
9526 // Parse package
9527 int parseFlags = PackageParser.PARSE_CHATTY |
9528 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9529 PackageParser pp = new PackageParser(codePath);
9530 pp.setSeparateProcesses(mSeparateProcesses);
9531 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9532 codePath, mMetrics, parseFlags);
9533 pp = null;
9534 doGc = true;
9535 // Check for parse errors
9536 if (pkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009537 Slog.e(TAG, "Parse error when installing install pkg : "
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009538 + args.cid + " from " + args.cachePath);
9539 continue;
9540 }
9541 setApplicationInfoPaths(pkg, codePath, codePath);
9542 synchronized (mInstallLock) {
9543 // Scan the package
9544 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9545 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009546 retCode = PackageManager.INSTALL_SUCCEEDED;
9547 pkgList.add(pkg.packageName);
9548 // Post process args
9549 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9550 }
9551 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009552 Slog.i(TAG, "Failed to install pkg: " +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009553 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009554 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009555 }
9556
9557 } finally {
9558 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9559 // Don't destroy container here. Wait till gc clears things up.
9560 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009561 }
9562 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009563 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009564 synchronized (mPackages) {
9565 // Persist settings
9566 mSettings.writeLP();
9567 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009568 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009569 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009570 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9571 }
9572 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009573 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009574 }
9575 // Delete any stale containers if needed.
9576 if (removeCids != null) {
9577 for (String cid : removeCids) {
9578 Log.i(TAG, "Destroying stale container : " + cid);
9579 PackageHelper.destroySdDir(cid);
9580 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009581 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009582 }
9583
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009584 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009585 int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009586 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009587 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009588 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009589 Set<SdInstallArgs> keys = processCids.keySet();
9590 for (SdInstallArgs args : keys) {
9591 String cid = args.cid;
9592 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009593 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009594 // Delete package internally
9595 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9596 synchronized (mInstallLock) {
9597 boolean res = deletePackageLI(pkgName, false,
9598 PackageManager.DONT_DELETE_DATA, outInfo);
9599 if (res) {
9600 pkgList.add(pkgName);
9601 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009602 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009603 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009604 }
9605 }
9606 }
9607 // Send broadcasts
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009608 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009609 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009610 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009611 // Force gc
9612 Runtime.getRuntime().gc();
9613 // Just unmount all valid containers.
9614 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009615 synchronized (mInstallLock) {
9616 args.doPostDeleteLI(false);
9617 }
9618 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009619 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009620
9621 public void movePackage(final String packageName,
9622 final IPackageMoveObserver observer, final int flags) {
9623 if (packageName == null) {
9624 return;
9625 }
9626 mContext.enforceCallingOrSelfPermission(
9627 android.Manifest.permission.MOVE_PACKAGE, null);
9628 int returnCode = PackageManager.MOVE_SUCCEEDED;
9629 int currFlags = 0;
9630 int newFlags = 0;
9631 synchronized (mPackages) {
9632 PackageParser.Package pkg = mPackages.get(packageName);
9633 if (pkg == null) {
9634 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9635 }
9636 // Disable moving fwd locked apps and system packages
9637 if (pkg.applicationInfo != null &&
9638 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009639 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009640 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9641 } else if (pkg.applicationInfo != null &&
9642 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009643 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009644 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9645 } else {
9646 // Find install location first
9647 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9648 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009649 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009650 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9651 } else {
9652 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9653 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009654 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009655 PackageManager.INSTALL_EXTERNAL : 0;
9656 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009657 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009658 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9659 }
9660 }
9661 }
9662 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9663 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9664 } else {
9665 Message msg = mHandler.obtainMessage(INIT_COPY);
9666 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9667 pkg.applicationInfo.publicSourceDir);
9668 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9669 packageName);
9670 msg.obj = mp;
9671 mHandler.sendMessage(msg);
9672 }
9673 }
9674 }
9675
9676 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9677 // Queue up an async operation since the package deletion may take a little while.
9678 mHandler.post(new Runnable() {
9679 public void run() {
9680 mHandler.removeCallbacks(this);
9681 int returnCode = currentStatus;
9682 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9683 if (moveSucceeded) {
9684 int uid = -1;
9685 synchronized (mPackages) {
9686 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9687 }
9688 ArrayList<String> pkgList = new ArrayList<String>();
9689 pkgList.add(mp.packageName);
9690 int uidArr[] = new int[] { uid };
9691 // Send resources unavailable broadcast
9692 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9693
9694 // Update package code and resource paths
9695 synchronized (mPackages) {
9696 PackageParser.Package pkg = mPackages.get(mp.packageName);
9697 if (pkg != null) {
9698 String oldCodePath = pkg.mPath;
9699 String newCodePath = mp.targetArgs.getCodePath();
9700 String newResPath = mp.targetArgs.getResourcePath();
9701 pkg.mPath = newCodePath;
9702 // Move dex files around
9703 if (moveDexFiles(pkg)
9704 != PackageManager.INSTALL_SUCCEEDED) {
9705 // Moving of dex files failed. Set
9706 // error code and abort move.
9707 pkg.mPath = pkg.mScanPath;
9708 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9709 moveSucceeded = false;
9710 } else {
9711 pkg.mScanPath = newCodePath;
9712 pkg.applicationInfo.sourceDir = newCodePath;
9713 pkg.applicationInfo.publicSourceDir = newResPath;
9714 PackageSetting ps = (PackageSetting) pkg.mExtras;
9715 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9716 ps.codePathString = ps.codePath.getPath();
9717 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9718 ps.resourcePathString = ps.resourcePath.getPath();
9719 // Set the application info flag correctly.
9720 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009721 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009722 } else {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009723 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009724 }
9725 ps.setFlags(pkg.applicationInfo.flags);
9726 mAppDirs.remove(oldCodePath);
9727 mAppDirs.put(newCodePath, pkg);
9728 // Persist settings
9729 mSettings.writeLP();
9730 }
9731 }
9732 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009733 // Send resources available broadcast
9734 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009735 }
9736 if (!moveSucceeded){
9737 // Clean up failed installation
9738 if (mp.targetArgs != null) {
9739 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009740 returnCode);
9741 }
9742 } else {
9743 // Force a gc to clear things up.
9744 Runtime.getRuntime().gc();
9745 // Delete older code
9746 synchronized (mInstallLock) {
9747 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009748 }
9749 }
9750 IPackageMoveObserver observer = mp.observer;
9751 if (observer != null) {
9752 try {
9753 observer.packageMoved(mp.packageName, returnCode);
9754 } catch (RemoteException e) {
9755 Log.i(TAG, "Observer no longer exists.");
9756 }
9757 }
9758 }
9759 });
9760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009761}