blob: 48b3fbbb3a17fe5409623cefb5d5347079268e42 [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;
346
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700347 // Delay time in millisecs
348 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800349 final private DefaultContainerConnection mDefContainerConn =
350 new DefaultContainerConnection();
351 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800352 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800353 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800354 IMediaContainerService imcs =
355 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800356 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800357 }
358
359 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800360 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800361 }
362 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700363
Christopher Tate1bb69062010-02-19 17:02:12 -0800364 // Recordkeeping of restore-after-install operations that are currently in flight
365 // between the Package Manager and the Backup Manager
366 class PostInstallData {
367 public InstallArgs args;
368 public PackageInstalledInfo res;
369
370 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
371 args = _a;
372 res = _r;
373 }
374 };
375 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
376 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
377
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800379 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800380 final ArrayList<HandlerParams> mPendingInstalls =
381 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800382
383 private boolean connectToService() {
384 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
385 " DefaultContainerService");
386 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
387 if (mContext.bindService(service, mDefContainerConn,
388 Context.BIND_AUTO_CREATE)) {
389 mBound = true;
390 return true;
391 }
392 return false;
393 }
394
395 private void disconnectService() {
396 mContainerService = null;
397 mBound = false;
398 mContext.unbindService(mDefContainerConn);
399 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800400
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700401 PackageHandler(Looper looper) {
402 super(looper);
403 }
404 public void handleMessage(Message msg) {
405 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800406 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800407 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800408 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800409 int idx = mPendingInstalls.size();
410 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
411 // If a bind was already initiated we dont really
412 // need to do anything. The pending install
413 // will be processed later on.
414 if (!mBound) {
415 // If this is the only one pending we might
416 // have to bind to the service again.
417 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800418 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800419 params.serviceError();
420 return;
421 } else {
422 // Once we bind to the service, the first
423 // pending request will be processed.
424 mPendingInstalls.add(idx, params);
425 }
426 } else {
427 mPendingInstalls.add(idx, params);
428 // Already bound to the service. Just make
429 // sure we trigger off processing the first request.
430 if (idx == 0) {
431 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800432 }
433 }
434 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800435 }
436 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800437 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800438 if (msg.obj != null) {
439 mContainerService = (IMediaContainerService) msg.obj;
440 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800441 if (mContainerService == null) {
442 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800443 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800444 for (HandlerParams params : mPendingInstalls) {
445 mPendingInstalls.remove(0);
446 // Indicate service bind error
447 params.serviceError();
448 }
449 mPendingInstalls.clear();
450 } else if (mPendingInstalls.size() > 0) {
451 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800452 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800453 params.startCopy();
454 }
455 } else {
456 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800457 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800458 }
459 break;
460 }
461 case MCS_RECONNECT : {
462 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
463 if (mPendingInstalls.size() > 0) {
464 if (mBound) {
465 disconnectService();
466 }
467 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800468 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800469 for (HandlerParams params : mPendingInstalls) {
470 mPendingInstalls.remove(0);
471 // Indicate service bind error
472 params.serviceError();
473 }
474 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800475 }
476 }
477 break;
478 }
479 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800480 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
481 // Delete pending install
482 if (mPendingInstalls.size() > 0) {
483 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800484 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800485 if (mPendingInstalls.size() == 0) {
486 if (mBound) {
487 disconnectService();
488 }
489 } else {
490 // There are more pending requests in queue.
491 // Just post MCS_BOUND message to trigger processing
492 // of next pending install.
493 mHandler.sendEmptyMessage(MCS_BOUND);
494 }
495 break;
496 }
497 case MCS_GIVE_UP: {
498 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
499 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800500 break;
501 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700502 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800503 String packages[];
504 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700505 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700506 int uids[];
507 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800508 if (mPendingBroadcasts == null) {
509 return;
510 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700511 size = mPendingBroadcasts.size();
512 if (size <= 0) {
513 // Nothing to be done. Just return
514 return;
515 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800516 packages = new String[size];
517 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700518 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800519 Iterator<HashMap.Entry<String, ArrayList<String>>>
520 it = mPendingBroadcasts.entrySet().iterator();
521 int i = 0;
522 while (it.hasNext() && i < size) {
523 HashMap.Entry<String, ArrayList<String>> ent = it.next();
524 packages[i] = ent.getKey();
525 components[i] = ent.getValue();
526 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700527 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800528 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700529 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800530 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 mPendingBroadcasts.clear();
532 }
533 // Send broadcasts
534 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800535 sendPackageChangedBroadcast(packages[i], true,
536 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700537 }
538 break;
539 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800540 case START_CLEANING_PACKAGE: {
541 String packageName = (String)msg.obj;
542 synchronized (mPackages) {
543 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
544 mSettings.mPackagesToBeCleaned.add(packageName);
545 }
546 }
547 startCleaningPackages();
548 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800549 case POST_INSTALL: {
550 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
551 PostInstallData data = mRunningInstalls.get(msg.arg1);
552 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800553 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800554
555 if (data != null) {
556 InstallArgs args = data.args;
557 PackageInstalledInfo res = data.res;
558
559 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
560 res.removedInfo.sendBroadcast(false, true);
561 Bundle extras = new Bundle(1);
562 extras.putInt(Intent.EXTRA_UID, res.uid);
563 final boolean update = res.removedInfo.removedPackage != null;
564 if (update) {
565 extras.putBoolean(Intent.EXTRA_REPLACING, true);
566 }
567 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
568 res.pkg.applicationInfo.packageName,
569 extras);
570 if (update) {
571 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
572 res.pkg.applicationInfo.packageName,
573 extras);
574 }
575 if (res.removedInfo.args != null) {
576 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800577 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800578 }
579 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800580 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800581 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800582 // We delete after a gc for applications on sdcard.
583 if (deleteOld) {
584 synchronized (mInstallLock) {
585 res.removedInfo.args.doPostDeleteLI(true);
586 }
587 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800588 if (args.observer != null) {
589 try {
590 args.observer.packageInstalled(res.name, res.returnCode);
591 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800592 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800593 }
594 }
595 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800596 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800597 }
598 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700599 }
600 }
601 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800602
603 static boolean installOnSd(int flags) {
604 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700605 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800606 return false;
607 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700608 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
609 return true;
610 }
611 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800612 }
613
614 static boolean isFwdLocked(int flags) {
615 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
616 return true;
617 }
618 return false;
619 }
620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 public static final IPackageManager main(Context context, boolean factoryTest) {
622 PackageManagerService m = new PackageManagerService(context, factoryTest);
623 ServiceManager.addService("package", m);
624 return m;
625 }
626
627 static String[] splitString(String str, char sep) {
628 int count = 1;
629 int i = 0;
630 while ((i=str.indexOf(sep, i)) >= 0) {
631 count++;
632 i++;
633 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 String[] res = new String[count];
636 i=0;
637 count = 0;
638 int lastI=0;
639 while ((i=str.indexOf(sep, i)) >= 0) {
640 res[count] = str.substring(lastI, i);
641 count++;
642 i++;
643 lastI = i;
644 }
645 res[count] = str.substring(lastI, str.length());
646 return res;
647 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800650 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800654 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 mContext = context;
658 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700659 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 mMetrics = new DisplayMetrics();
661 mSettings = new Settings();
662 mSettings.addSharedUserLP("android.uid.system",
663 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
664 mSettings.addSharedUserLP("android.uid.phone",
665 MULTIPLE_APPLICATION_UIDS
666 ? RADIO_UID : FIRST_APPLICATION_UID,
667 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400668 mSettings.addSharedUserLP("android.uid.log",
669 MULTIPLE_APPLICATION_UIDS
670 ? LOG_UID : FIRST_APPLICATION_UID,
671 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672
673 String separateProcesses = SystemProperties.get("debug.separate_processes");
674 if (separateProcesses != null && separateProcesses.length() > 0) {
675 if ("*".equals(separateProcesses)) {
676 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
677 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800678 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 } else {
680 mDefParseFlags = 0;
681 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800682 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 + separateProcesses);
684 }
685 } else {
686 mDefParseFlags = 0;
687 mSeparateProcesses = null;
688 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 Installer installer = new Installer();
691 // Little hacky thing to check if installd is here, to determine
692 // whether we are running on the simulator and thus need to take
693 // care of building the /data file structure ourself.
694 // (apparently the sim now has a working installer)
695 if (installer.ping() && Process.supportsProcesses()) {
696 mInstaller = installer;
697 } else {
698 mInstaller = null;
699 }
700
701 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
702 Display d = wm.getDefaultDisplay();
703 d.getMetrics(mMetrics);
704
705 synchronized (mInstallLock) {
706 synchronized (mPackages) {
707 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700708 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 File dataDir = Environment.getDataDirectory();
711 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800712 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
714
715 if (mInstaller == null) {
716 // Make sure these dirs exist, when we are running in
717 // the simulator.
718 // Make a wide-open directory for random misc stuff.
719 File miscDir = new File(dataDir, "misc");
720 miscDir.mkdirs();
721 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800722 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 mDrmAppPrivateInstallDir.mkdirs();
724 }
725
726 readPermissions();
727
728 mRestoredSettings = mSettings.readLP();
729 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800730
731 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800733
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800734 // Set flag to monitor and not change apk file paths when
735 // scanning install directories.
736 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700737 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800738 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800739 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700745 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700748 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 /**
751 * Out of paranoia, ensure that everything in the boot class
752 * path has been dexed.
753 */
754 String bootClassPath = System.getProperty("java.boot.class.path");
755 if (bootClassPath != null) {
756 String[] paths = splitString(bootClassPath, ':');
757 for (int i=0; i<paths.length; i++) {
758 try {
759 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
760 libFiles.add(paths[i]);
761 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700762 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 }
764 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800765 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800767 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 }
769 }
770 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800771 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 /**
775 * Also ensure all external libraries have had dexopt run on them.
776 */
777 if (mSharedLibraries.size() > 0) {
778 Iterator<String> libs = mSharedLibraries.values().iterator();
779 while (libs.hasNext()) {
780 String lib = libs.next();
781 try {
782 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
783 libFiles.add(lib);
784 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700785 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 }
787 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800788 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800790 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 }
792 }
793 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 // Gross hack for now: we know this file doesn't contain any
796 // code, so don't dexopt it to avoid the resulting log spew.
797 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 /**
800 * And there are a number of commands implemented in Java, which
801 * we currently need to do the dexopt on so that they can be
802 * run from a non-root shell.
803 */
804 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700805 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 for (int i=0; i<frameworkFiles.length; i++) {
807 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
808 String path = libPath.getPath();
809 // Skip the file if we alrady did it.
810 if (libFiles.contains(path)) {
811 continue;
812 }
813 // Skip the file if it is not a type we want to dexopt.
814 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
815 continue;
816 }
817 try {
818 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
819 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700820 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 }
822 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800823 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800825 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 }
827 }
828 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800829
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700830 if (didDexOpt) {
831 // If we had to do a dexopt of one of the previous
832 // things, then something on the system has changed.
833 // Consider this significant, and wipe away all other
834 // existing dexopt files to ensure we don't leave any
835 // dangling around.
836 String[] files = mDalvikCacheDir.list();
837 if (files != null) {
838 for (int i=0; i<files.length; i++) {
839 String fn = files[i];
840 if (fn.startsWith("data@app@")
841 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800842 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700843 (new File(mDalvikCacheDir, fn)).delete();
844 }
845 }
846 }
847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800849
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800850 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 mFrameworkInstallObserver = new AppDirObserver(
852 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
853 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700854 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
855 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800856 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800857
858 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
860 mSystemInstallObserver = new AppDirObserver(
861 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
862 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700863 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
864 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800865
866 if (mInstaller != null) {
867 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
868 mInstaller.moveFiles();
869 }
870
871 // Prune any system packages that no longer exist.
872 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
873 while (psit.hasNext()) {
874 PackageSetting ps = psit.next();
875 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800876 && !mPackages.containsKey(ps.name)
877 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800878 psit.remove();
879 String msg = "System package " + ps.name
880 + " no longer exists; wiping its data";
881 reportSettingsProblem(Log.WARN, msg);
882 if (mInstaller != null) {
883 // XXX how to set useEncryptedFSDir for packages that
884 // are not encrypted?
885 mInstaller.remove(ps.name, true);
886 }
887 }
888 }
889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 mAppInstallDir = new File(dataDir, "app");
891 if (mInstaller == null) {
892 // Make sure these dirs exist, when we are running in
893 // the simulator.
894 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
895 }
896 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800897 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 //clean up list
899 for(int i = 0; i < deletePkgsList.size(); i++) {
900 //clean up here
901 cleanupInstallFailedPackage(deletePkgsList.get(i));
902 }
903 //delete tmp files
904 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800905
906 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 SystemClock.uptimeMillis());
908 mAppInstallObserver = new AppDirObserver(
909 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
910 mAppInstallObserver.startWatching();
911 scanDirLI(mAppInstallDir, 0, scanMode);
912
913 mDrmAppInstallObserver = new AppDirObserver(
914 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
915 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800916 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800918 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800920 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 + ((SystemClock.uptimeMillis()-startTime)/1000f)
922 + " seconds");
923
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700924 updatePermissionsLP(null, null, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925
926 mSettings.writeLP();
927
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800928 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 // Now after opening every single application zip, make sure they
932 // are all flushed. Not really needed, but keeps things nice and
933 // tidy.
934 Runtime.getRuntime().gc();
935 } // synchronized (mPackages)
936 } // synchronized (mInstallLock)
937 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 @Override
940 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
941 throws RemoteException {
942 try {
943 return super.onTransact(code, data, reply, flags);
944 } catch (RuntimeException e) {
945 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800946 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 }
948 throw e;
949 }
950 }
951
Dianne Hackborne6620b22010-01-22 14:46:21 -0800952 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800953 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800955 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
956 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800958 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800959 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 }
961 } else {
962 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800963 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 File dataDir = new File(pkg.applicationInfo.dataDir);
965 dataDir.delete();
966 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800967 if (ps.codePath != null) {
968 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800969 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800970 }
971 }
972 if (ps.resourcePath != null) {
973 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800974 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800975 }
976 }
977 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 }
979
980 void readPermissions() {
981 // Read permissions from .../etc/permission directory.
982 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
983 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800984 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 return;
986 }
987 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800988 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 return;
990 }
991
992 // Iterate over the files in the directory and scan .xml files
993 for (File f : libraryDir.listFiles()) {
994 // We'll read platform.xml last
995 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
996 continue;
997 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001000 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 continue;
1002 }
1003 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001004 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 continue;
1006 }
1007
1008 readPermissionsFromXml(f);
1009 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1012 final File permFile = new File(Environment.getRootDirectory(),
1013 "etc/permissions/platform.xml");
1014 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001015
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001016 StringBuilder sb = new StringBuilder(128);
1017 sb.append("Libs:");
1018 Iterator<String> it = mSharedLibraries.keySet().iterator();
1019 while (it.hasNext()) {
1020 sb.append(' ');
1021 String name = it.next();
1022 sb.append(name);
1023 sb.append(':');
1024 sb.append(mSharedLibraries.get(name));
1025 }
1026 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001027
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001028 sb.setLength(0);
1029 sb.append("Features:");
1030 it = mAvailableFeatures.keySet().iterator();
1031 while (it.hasNext()) {
1032 sb.append(' ');
1033 sb.append(it.next());
1034 }
1035 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001037
1038 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 FileReader permReader = null;
1040 try {
1041 permReader = new FileReader(permFile);
1042 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001043 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 return;
1045 }
1046
1047 try {
1048 XmlPullParser parser = Xml.newPullParser();
1049 parser.setInput(permReader);
1050
1051 XmlUtils.beginDocument(parser, "permissions");
1052
1053 while (true) {
1054 XmlUtils.nextElement(parser);
1055 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1056 break;
1057 }
1058
1059 String name = parser.getName();
1060 if ("group".equals(name)) {
1061 String gidStr = parser.getAttributeValue(null, "gid");
1062 if (gidStr != null) {
1063 int gid = Integer.parseInt(gidStr);
1064 mGlobalGids = appendInt(mGlobalGids, gid);
1065 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001066 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 + parser.getPositionDescription());
1068 }
1069
1070 XmlUtils.skipCurrentTag(parser);
1071 continue;
1072 } else if ("permission".equals(name)) {
1073 String perm = parser.getAttributeValue(null, "name");
1074 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001075 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 + parser.getPositionDescription());
1077 XmlUtils.skipCurrentTag(parser);
1078 continue;
1079 }
1080 perm = perm.intern();
1081 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 } else if ("assign-permission".equals(name)) {
1084 String perm = parser.getAttributeValue(null, "name");
1085 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001086 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 + parser.getPositionDescription());
1088 XmlUtils.skipCurrentTag(parser);
1089 continue;
1090 }
1091 String uidStr = parser.getAttributeValue(null, "uid");
1092 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001093 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 + parser.getPositionDescription());
1095 XmlUtils.skipCurrentTag(parser);
1096 continue;
1097 }
1098 int uid = Process.getUidForName(uidStr);
1099 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001100 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 + uidStr + "\" at "
1102 + parser.getPositionDescription());
1103 XmlUtils.skipCurrentTag(parser);
1104 continue;
1105 }
1106 perm = perm.intern();
1107 HashSet<String> perms = mSystemPermissions.get(uid);
1108 if (perms == null) {
1109 perms = new HashSet<String>();
1110 mSystemPermissions.put(uid, perms);
1111 }
1112 perms.add(perm);
1113 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 } else if ("library".equals(name)) {
1116 String lname = parser.getAttributeValue(null, "name");
1117 String lfile = parser.getAttributeValue(null, "file");
1118 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001119 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 + parser.getPositionDescription());
1121 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001122 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 + parser.getPositionDescription());
1124 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001125 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001126 mSharedLibraries.put(lname, lfile);
1127 }
1128 XmlUtils.skipCurrentTag(parser);
1129 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001130
Dianne Hackborn49237342009-08-27 20:08:01 -07001131 } else if ("feature".equals(name)) {
1132 String fname = parser.getAttributeValue(null, "name");
1133 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001134 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001135 + parser.getPositionDescription());
1136 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001137 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001138 FeatureInfo fi = new FeatureInfo();
1139 fi.name = fname;
1140 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 }
1142 XmlUtils.skipCurrentTag(parser);
1143 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 } else {
1146 XmlUtils.skipCurrentTag(parser);
1147 continue;
1148 }
1149
1150 }
1151 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001152 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001154 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
1156 }
1157
1158 void readPermission(XmlPullParser parser, String name)
1159 throws IOException, XmlPullParserException {
1160
1161 name = name.intern();
1162
1163 BasePermission bp = mSettings.mPermissions.get(name);
1164 if (bp == null) {
1165 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1166 mSettings.mPermissions.put(name, bp);
1167 }
1168 int outerDepth = parser.getDepth();
1169 int type;
1170 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1171 && (type != XmlPullParser.END_TAG
1172 || parser.getDepth() > outerDepth)) {
1173 if (type == XmlPullParser.END_TAG
1174 || type == XmlPullParser.TEXT) {
1175 continue;
1176 }
1177
1178 String tagName = parser.getName();
1179 if ("group".equals(tagName)) {
1180 String gidStr = parser.getAttributeValue(null, "gid");
1181 if (gidStr != null) {
1182 int gid = Process.getGidForName(gidStr);
1183 bp.gids = appendInt(bp.gids, gid);
1184 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001185 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 + parser.getPositionDescription());
1187 }
1188 }
1189 XmlUtils.skipCurrentTag(parser);
1190 }
1191 }
1192
1193 static int[] appendInt(int[] cur, int val) {
1194 if (cur == null) {
1195 return new int[] { val };
1196 }
1197 final int N = cur.length;
1198 for (int i=0; i<N; i++) {
1199 if (cur[i] == val) {
1200 return cur;
1201 }
1202 }
1203 int[] ret = new int[N+1];
1204 System.arraycopy(cur, 0, ret, 0, N);
1205 ret[N] = val;
1206 return ret;
1207 }
1208
1209 static int[] appendInts(int[] cur, int[] add) {
1210 if (add == null) return cur;
1211 if (cur == null) return add;
1212 final int N = add.length;
1213 for (int i=0; i<N; i++) {
1214 cur = appendInt(cur, add[i]);
1215 }
1216 return cur;
1217 }
1218
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001219 static int[] removeInt(int[] cur, int val) {
1220 if (cur == null) {
1221 return null;
1222 }
1223 final int N = cur.length;
1224 for (int i=0; i<N; i++) {
1225 if (cur[i] == val) {
1226 int[] ret = new int[N-1];
1227 if (i > 0) {
1228 System.arraycopy(cur, 0, ret, 0, i);
1229 }
1230 if (i < (N-1)) {
1231 System.arraycopy(cur, i, ret, i+1, N-i-1);
1232 }
1233 return ret;
1234 }
1235 }
1236 return cur;
1237 }
1238
1239 static int[] removeInts(int[] cur, int[] rem) {
1240 if (rem == null) return cur;
1241 if (cur == null) return cur;
1242 final int N = rem.length;
1243 for (int i=0; i<N; i++) {
1244 cur = removeInt(cur, rem[i]);
1245 }
1246 return cur;
1247 }
1248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001250 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1251 // The package has been uninstalled but has retained data and resources.
1252 return PackageParser.generatePackageInfo(p, null, flags);
1253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 final PackageSetting ps = (PackageSetting)p.mExtras;
1255 if (ps == null) {
1256 return null;
1257 }
1258 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1259 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1260 }
1261
1262 public PackageInfo getPackageInfo(String packageName, int flags) {
1263 synchronized (mPackages) {
1264 PackageParser.Package p = mPackages.get(packageName);
1265 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001266 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 + ": " + p);
1268 if (p != null) {
1269 return generatePackageInfo(p, flags);
1270 }
1271 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1272 return generatePackageInfoFromSettingsLP(packageName, flags);
1273 }
1274 }
1275 return null;
1276 }
1277
Dianne Hackborn47096932010-02-11 15:57:09 -08001278 public String[] currentToCanonicalPackageNames(String[] names) {
1279 String[] out = new String[names.length];
1280 synchronized (mPackages) {
1281 for (int i=names.length-1; i>=0; i--) {
1282 PackageSetting ps = mSettings.mPackages.get(names[i]);
1283 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1284 }
1285 }
1286 return out;
1287 }
1288
1289 public String[] canonicalToCurrentPackageNames(String[] names) {
1290 String[] out = new String[names.length];
1291 synchronized (mPackages) {
1292 for (int i=names.length-1; i>=0; i--) {
1293 String cur = mSettings.mRenamedPackages.get(names[i]);
1294 out[i] = cur != null ? cur : names[i];
1295 }
1296 }
1297 return out;
1298 }
1299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 public int getPackageUid(String packageName) {
1301 synchronized (mPackages) {
1302 PackageParser.Package p = mPackages.get(packageName);
1303 if(p != null) {
1304 return p.applicationInfo.uid;
1305 }
1306 PackageSetting ps = mSettings.mPackages.get(packageName);
1307 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1308 return -1;
1309 }
1310 p = ps.pkg;
1311 return p != null ? p.applicationInfo.uid : -1;
1312 }
1313 }
1314
1315 public int[] getPackageGids(String packageName) {
1316 synchronized (mPackages) {
1317 PackageParser.Package p = mPackages.get(packageName);
1318 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001319 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 + ": " + p);
1321 if (p != null) {
1322 final PackageSetting ps = (PackageSetting)p.mExtras;
1323 final SharedUserSetting suid = ps.sharedUser;
1324 return suid != null ? suid.gids : ps.gids;
1325 }
1326 }
1327 // stupid thing to indicate an error.
1328 return new int[0];
1329 }
1330
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001331 static final PermissionInfo generatePermissionInfo(
1332 BasePermission bp, int flags) {
1333 if (bp.perm != null) {
1334 return PackageParser.generatePermissionInfo(bp.perm, flags);
1335 }
1336 PermissionInfo pi = new PermissionInfo();
1337 pi.name = bp.name;
1338 pi.packageName = bp.sourcePackage;
1339 pi.nonLocalizedLabel = bp.name;
1340 pi.protectionLevel = bp.protectionLevel;
1341 return pi;
1342 }
1343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 public PermissionInfo getPermissionInfo(String name, int flags) {
1345 synchronized (mPackages) {
1346 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001347 if (p != null) {
1348 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 }
1350 return null;
1351 }
1352 }
1353
1354 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1355 synchronized (mPackages) {
1356 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1357 for (BasePermission p : mSettings.mPermissions.values()) {
1358 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001359 if (p.perm == null || p.perm.info.group == null) {
1360 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 }
1362 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001363 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1365 }
1366 }
1367 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 if (out.size() > 0) {
1370 return out;
1371 }
1372 return mPermissionGroups.containsKey(group) ? out : null;
1373 }
1374 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1377 synchronized (mPackages) {
1378 return PackageParser.generatePermissionGroupInfo(
1379 mPermissionGroups.get(name), flags);
1380 }
1381 }
1382
1383 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1384 synchronized (mPackages) {
1385 final int N = mPermissionGroups.size();
1386 ArrayList<PermissionGroupInfo> out
1387 = new ArrayList<PermissionGroupInfo>(N);
1388 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1389 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1390 }
1391 return out;
1392 }
1393 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1396 PackageSetting ps = mSettings.mPackages.get(packageName);
1397 if(ps != null) {
1398 if(ps.pkg == null) {
1399 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1400 if(pInfo != null) {
1401 return pInfo.applicationInfo;
1402 }
1403 return null;
1404 }
1405 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1406 }
1407 return null;
1408 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1411 PackageSetting ps = mSettings.mPackages.get(packageName);
1412 if(ps != null) {
1413 if(ps.pkg == null) {
1414 ps.pkg = new PackageParser.Package(packageName);
1415 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001416 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1417 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1418 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1419 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
1421 return generatePackageInfo(ps.pkg, flags);
1422 }
1423 return null;
1424 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1427 synchronized (mPackages) {
1428 PackageParser.Package p = mPackages.get(packageName);
1429 if (Config.LOGV) Log.v(
1430 TAG, "getApplicationInfo " + packageName
1431 + ": " + p);
1432 if (p != null) {
1433 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001434 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
1436 if ("android".equals(packageName)||"system".equals(packageName)) {
1437 return mAndroidApplication;
1438 }
1439 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1440 return generateApplicationInfoFromSettingsLP(packageName, flags);
1441 }
1442 }
1443 return null;
1444 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001445
1446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1448 mContext.enforceCallingOrSelfPermission(
1449 android.Manifest.permission.CLEAR_APP_CACHE, null);
1450 // Queue up an async operation since clearing cache may take a little while.
1451 mHandler.post(new Runnable() {
1452 public void run() {
1453 mHandler.removeCallbacks(this);
1454 int retCode = -1;
1455 if (mInstaller != null) {
1456 retCode = mInstaller.freeCache(freeStorageSize);
1457 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001458 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 }
1460 } //end if mInstaller
1461 if (observer != null) {
1462 try {
1463 observer.onRemoveCompleted(null, (retCode >= 0));
1464 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001465 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 }
1467 }
1468 }
1469 });
1470 }
1471
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001472 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001473 mContext.enforceCallingOrSelfPermission(
1474 android.Manifest.permission.CLEAR_APP_CACHE, null);
1475 // Queue up an async operation since clearing cache may take a little while.
1476 mHandler.post(new Runnable() {
1477 public void run() {
1478 mHandler.removeCallbacks(this);
1479 int retCode = -1;
1480 if (mInstaller != null) {
1481 retCode = mInstaller.freeCache(freeStorageSize);
1482 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001483 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001484 }
1485 }
1486 if(pi != null) {
1487 try {
1488 // Callback via pending intent
1489 int code = (retCode >= 0) ? 1 : 0;
1490 pi.sendIntent(null, code, null,
1491 null, null);
1492 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001493 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001494 }
1495 }
1496 }
1497 });
1498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1501 synchronized (mPackages) {
1502 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001503
1504 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001506 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 }
1508 if (mResolveComponentName.equals(component)) {
1509 return mResolveActivity;
1510 }
1511 }
1512 return null;
1513 }
1514
1515 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1516 synchronized (mPackages) {
1517 PackageParser.Activity a = mReceivers.mActivities.get(component);
1518 if (Config.LOGV) Log.v(
1519 TAG, "getReceiverInfo " + component + ": " + a);
1520 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1521 return PackageParser.generateActivityInfo(a, flags);
1522 }
1523 }
1524 return null;
1525 }
1526
1527 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1528 synchronized (mPackages) {
1529 PackageParser.Service s = mServices.mServices.get(component);
1530 if (Config.LOGV) Log.v(
1531 TAG, "getServiceInfo " + component + ": " + s);
1532 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1533 return PackageParser.generateServiceInfo(s, flags);
1534 }
1535 }
1536 return null;
1537 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 public String[] getSystemSharedLibraryNames() {
1540 Set<String> libSet;
1541 synchronized (mPackages) {
1542 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001543 int size = libSet.size();
1544 if (size > 0) {
1545 String[] libs = new String[size];
1546 libSet.toArray(libs);
1547 return libs;
1548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001550 return null;
1551 }
1552
1553 public FeatureInfo[] getSystemAvailableFeatures() {
1554 Collection<FeatureInfo> featSet;
1555 synchronized (mPackages) {
1556 featSet = mAvailableFeatures.values();
1557 int size = featSet.size();
1558 if (size > 0) {
1559 FeatureInfo[] features = new FeatureInfo[size+1];
1560 featSet.toArray(features);
1561 FeatureInfo fi = new FeatureInfo();
1562 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1563 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1564 features[size] = fi;
1565 return features;
1566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 }
1568 return null;
1569 }
1570
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001571 public boolean hasSystemFeature(String name) {
1572 synchronized (mPackages) {
1573 return mAvailableFeatures.containsKey(name);
1574 }
1575 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 public int checkPermission(String permName, String pkgName) {
1578 synchronized (mPackages) {
1579 PackageParser.Package p = mPackages.get(pkgName);
1580 if (p != null && p.mExtras != null) {
1581 PackageSetting ps = (PackageSetting)p.mExtras;
1582 if (ps.sharedUser != null) {
1583 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1584 return PackageManager.PERMISSION_GRANTED;
1585 }
1586 } else if (ps.grantedPermissions.contains(permName)) {
1587 return PackageManager.PERMISSION_GRANTED;
1588 }
1589 }
1590 }
1591 return PackageManager.PERMISSION_DENIED;
1592 }
1593
1594 public int checkUidPermission(String permName, int uid) {
1595 synchronized (mPackages) {
1596 Object obj = mSettings.getUserIdLP(uid);
1597 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001598 GrantedPermissions gp = (GrantedPermissions)obj;
1599 if (gp.grantedPermissions.contains(permName)) {
1600 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 }
1602 } else {
1603 HashSet<String> perms = mSystemPermissions.get(uid);
1604 if (perms != null && perms.contains(permName)) {
1605 return PackageManager.PERMISSION_GRANTED;
1606 }
1607 }
1608 }
1609 return PackageManager.PERMISSION_DENIED;
1610 }
1611
1612 private BasePermission findPermissionTreeLP(String permName) {
1613 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1614 if (permName.startsWith(bp.name) &&
1615 permName.length() > bp.name.length() &&
1616 permName.charAt(bp.name.length()) == '.') {
1617 return bp;
1618 }
1619 }
1620 return null;
1621 }
1622
1623 private BasePermission checkPermissionTreeLP(String permName) {
1624 if (permName != null) {
1625 BasePermission bp = findPermissionTreeLP(permName);
1626 if (bp != null) {
1627 if (bp.uid == Binder.getCallingUid()) {
1628 return bp;
1629 }
1630 throw new SecurityException("Calling uid "
1631 + Binder.getCallingUid()
1632 + " is not allowed to add to permission tree "
1633 + bp.name + " owned by uid " + bp.uid);
1634 }
1635 }
1636 throw new SecurityException("No permission tree found for " + permName);
1637 }
1638
1639 public boolean addPermission(PermissionInfo info) {
1640 synchronized (mPackages) {
1641 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1642 throw new SecurityException("Label must be specified in permission");
1643 }
1644 BasePermission tree = checkPermissionTreeLP(info.name);
1645 BasePermission bp = mSettings.mPermissions.get(info.name);
1646 boolean added = bp == null;
1647 if (added) {
1648 bp = new BasePermission(info.name, tree.sourcePackage,
1649 BasePermission.TYPE_DYNAMIC);
1650 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1651 throw new SecurityException(
1652 "Not allowed to modify non-dynamic permission "
1653 + info.name);
1654 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001655 bp.protectionLevel = info.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 bp.perm = new PackageParser.Permission(tree.perm.owner,
1657 new PermissionInfo(info));
1658 bp.perm.info.packageName = tree.perm.info.packageName;
1659 bp.uid = tree.uid;
1660 if (added) {
1661 mSettings.mPermissions.put(info.name, bp);
1662 }
1663 mSettings.writeLP();
1664 return added;
1665 }
1666 }
1667
1668 public void removePermission(String name) {
1669 synchronized (mPackages) {
1670 checkPermissionTreeLP(name);
1671 BasePermission bp = mSettings.mPermissions.get(name);
1672 if (bp != null) {
1673 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1674 throw new SecurityException(
1675 "Not allowed to modify non-dynamic permission "
1676 + name);
1677 }
1678 mSettings.mPermissions.remove(name);
1679 mSettings.writeLP();
1680 }
1681 }
1682 }
1683
Dianne Hackborn854060af2009-07-09 18:14:31 -07001684 public boolean isProtectedBroadcast(String actionName) {
1685 synchronized (mPackages) {
1686 return mProtectedBroadcasts.contains(actionName);
1687 }
1688 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 public int checkSignatures(String pkg1, String pkg2) {
1691 synchronized (mPackages) {
1692 PackageParser.Package p1 = mPackages.get(pkg1);
1693 PackageParser.Package p2 = mPackages.get(pkg2);
1694 if (p1 == null || p1.mExtras == null
1695 || p2 == null || p2.mExtras == null) {
1696 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1697 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001698 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 }
1700 }
1701
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001702 public int checkUidSignatures(int uid1, int uid2) {
1703 synchronized (mPackages) {
1704 Signature[] s1;
1705 Signature[] s2;
1706 Object obj = mSettings.getUserIdLP(uid1);
1707 if (obj != null) {
1708 if (obj instanceof SharedUserSetting) {
1709 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1710 } else if (obj instanceof PackageSetting) {
1711 s1 = ((PackageSetting)obj).signatures.mSignatures;
1712 } else {
1713 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1714 }
1715 } else {
1716 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1717 }
1718 obj = mSettings.getUserIdLP(uid2);
1719 if (obj != null) {
1720 if (obj instanceof SharedUserSetting) {
1721 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1722 } else if (obj instanceof PackageSetting) {
1723 s2 = ((PackageSetting)obj).signatures.mSignatures;
1724 } else {
1725 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1726 }
1727 } else {
1728 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1729 }
1730 return checkSignaturesLP(s1, s2);
1731 }
1732 }
1733
1734 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1735 if (s1 == null) {
1736 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1738 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1739 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001740 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1742 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001743 final int N1 = s1.length;
1744 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 for (int i=0; i<N1; i++) {
1746 boolean match = false;
1747 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001748 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 match = true;
1750 break;
1751 }
1752 }
1753 if (!match) {
1754 return PackageManager.SIGNATURE_NO_MATCH;
1755 }
1756 }
1757 return PackageManager.SIGNATURE_MATCH;
1758 }
1759
1760 public String[] getPackagesForUid(int uid) {
1761 synchronized (mPackages) {
1762 Object obj = mSettings.getUserIdLP(uid);
1763 if (obj instanceof SharedUserSetting) {
1764 SharedUserSetting sus = (SharedUserSetting)obj;
1765 final int N = sus.packages.size();
1766 String[] res = new String[N];
1767 Iterator<PackageSetting> it = sus.packages.iterator();
1768 int i=0;
1769 while (it.hasNext()) {
1770 res[i++] = it.next().name;
1771 }
1772 return res;
1773 } else if (obj instanceof PackageSetting) {
1774 PackageSetting ps = (PackageSetting)obj;
1775 return new String[] { ps.name };
1776 }
1777 }
1778 return null;
1779 }
1780
1781 public String getNameForUid(int uid) {
1782 synchronized (mPackages) {
1783 Object obj = mSettings.getUserIdLP(uid);
1784 if (obj instanceof SharedUserSetting) {
1785 SharedUserSetting sus = (SharedUserSetting)obj;
1786 return sus.name + ":" + sus.userId;
1787 } else if (obj instanceof PackageSetting) {
1788 PackageSetting ps = (PackageSetting)obj;
1789 return ps.name;
1790 }
1791 }
1792 return null;
1793 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 public int getUidForSharedUser(String sharedUserName) {
1796 if(sharedUserName == null) {
1797 return -1;
1798 }
1799 synchronized (mPackages) {
1800 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1801 if(suid == null) {
1802 return -1;
1803 }
1804 return suid.userId;
1805 }
1806 }
1807
1808 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1809 int flags) {
1810 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001811 return chooseBestActivity(intent, resolvedType, flags, query);
1812 }
1813
Mihai Predaeae850c2009-05-13 10:13:48 +02001814 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1815 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 if (query != null) {
1817 final int N = query.size();
1818 if (N == 1) {
1819 return query.get(0);
1820 } else if (N > 1) {
1821 // If there is more than one activity with the same priority,
1822 // then let the user decide between them.
1823 ResolveInfo r0 = query.get(0);
1824 ResolveInfo r1 = query.get(1);
1825 if (false) {
1826 System.out.println(r0.activityInfo.name +
1827 "=" + r0.priority + " vs " +
1828 r1.activityInfo.name +
1829 "=" + r1.priority);
1830 }
1831 // If the first activity has a higher priority, or a different
1832 // default, then it is always desireable to pick it.
1833 if (r0.priority != r1.priority
1834 || r0.preferredOrder != r1.preferredOrder
1835 || r0.isDefault != r1.isDefault) {
1836 return query.get(0);
1837 }
1838 // If we have saved a preference for a preferred activity for
1839 // this Intent, use that.
1840 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1841 flags, query, r0.priority);
1842 if (ri != null) {
1843 return ri;
1844 }
1845 return mResolveInfo;
1846 }
1847 }
1848 return null;
1849 }
1850
1851 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1852 int flags, List<ResolveInfo> query, int priority) {
1853 synchronized (mPackages) {
1854 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1855 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001856 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1858 if (prefs != null && prefs.size() > 0) {
1859 // First figure out how good the original match set is.
1860 // We will only allow preferred activities that came
1861 // from the same match quality.
1862 int match = 0;
1863 final int N = query.size();
1864 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1865 for (int j=0; j<N; j++) {
1866 ResolveInfo ri = query.get(j);
1867 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1868 + ": 0x" + Integer.toHexString(match));
1869 if (ri.match > match) match = ri.match;
1870 }
1871 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1872 + Integer.toHexString(match));
1873 match &= IntentFilter.MATCH_CATEGORY_MASK;
1874 final int M = prefs.size();
1875 for (int i=0; i<M; i++) {
1876 PreferredActivity pa = prefs.get(i);
1877 if (pa.mMatch != match) {
1878 continue;
1879 }
1880 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1881 if (DEBUG_PREFERRED) {
1882 Log.v(TAG, "Got preferred activity:");
1883 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1884 }
1885 if (ai != null) {
1886 for (int j=0; j<N; j++) {
1887 ResolveInfo ri = query.get(j);
1888 if (!ri.activityInfo.applicationInfo.packageName
1889 .equals(ai.applicationInfo.packageName)) {
1890 continue;
1891 }
1892 if (!ri.activityInfo.name.equals(ai.name)) {
1893 continue;
1894 }
1895
1896 // Okay we found a previously set preferred app.
1897 // If the result set is different from when this
1898 // was created, we need to clear it and re-ask the
1899 // user their preference.
1900 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001901 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 + intent + " type " + resolvedType);
1903 mSettings.mPreferredActivities.removeFilter(pa);
1904 return null;
1905 }
1906
1907 // Yay!
1908 return ri;
1909 }
1910 }
1911 }
1912 }
1913 }
1914 return null;
1915 }
1916
1917 public List<ResolveInfo> queryIntentActivities(Intent intent,
1918 String resolvedType, int flags) {
1919 ComponentName comp = intent.getComponent();
1920 if (comp != null) {
1921 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1922 ActivityInfo ai = getActivityInfo(comp, flags);
1923 if (ai != null) {
1924 ResolveInfo ri = new ResolveInfo();
1925 ri.activityInfo = ai;
1926 list.add(ri);
1927 }
1928 return list;
1929 }
1930
1931 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001932 String pkgName = intent.getPackage();
1933 if (pkgName == null) {
1934 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1935 resolvedType, flags);
1936 }
1937 PackageParser.Package pkg = mPackages.get(pkgName);
1938 if (pkg != null) {
1939 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1940 resolvedType, flags, pkg.activities);
1941 }
1942 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 }
1944 }
1945
1946 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1947 Intent[] specifics, String[] specificTypes, Intent intent,
1948 String resolvedType, int flags) {
1949 final String resultsAction = intent.getAction();
1950
1951 List<ResolveInfo> results = queryIntentActivities(
1952 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1953 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1954
1955 int specificsPos = 0;
1956 int N;
1957
1958 // todo: note that the algorithm used here is O(N^2). This
1959 // isn't a problem in our current environment, but if we start running
1960 // into situations where we have more than 5 or 10 matches then this
1961 // should probably be changed to something smarter...
1962
1963 // First we go through and resolve each of the specific items
1964 // that were supplied, taking care of removing any corresponding
1965 // duplicate items in the generic resolve list.
1966 if (specifics != null) {
1967 for (int i=0; i<specifics.length; i++) {
1968 final Intent sintent = specifics[i];
1969 if (sintent == null) {
1970 continue;
1971 }
1972
1973 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1974 String action = sintent.getAction();
1975 if (resultsAction != null && resultsAction.equals(action)) {
1976 // If this action was explicitly requested, then don't
1977 // remove things that have it.
1978 action = null;
1979 }
1980 ComponentName comp = sintent.getComponent();
1981 ResolveInfo ri = null;
1982 ActivityInfo ai = null;
1983 if (comp == null) {
1984 ri = resolveIntent(
1985 sintent,
1986 specificTypes != null ? specificTypes[i] : null,
1987 flags);
1988 if (ri == null) {
1989 continue;
1990 }
1991 if (ri == mResolveInfo) {
1992 // ACK! Must do something better with this.
1993 }
1994 ai = ri.activityInfo;
1995 comp = new ComponentName(ai.applicationInfo.packageName,
1996 ai.name);
1997 } else {
1998 ai = getActivityInfo(comp, flags);
1999 if (ai == null) {
2000 continue;
2001 }
2002 }
2003
2004 // Look for any generic query activities that are duplicates
2005 // of this specific one, and remove them from the results.
2006 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2007 N = results.size();
2008 int j;
2009 for (j=specificsPos; j<N; j++) {
2010 ResolveInfo sri = results.get(j);
2011 if ((sri.activityInfo.name.equals(comp.getClassName())
2012 && sri.activityInfo.applicationInfo.packageName.equals(
2013 comp.getPackageName()))
2014 || (action != null && sri.filter.matchAction(action))) {
2015 results.remove(j);
2016 if (Config.LOGV) Log.v(
2017 TAG, "Removing duplicate item from " + j
2018 + " due to specific " + specificsPos);
2019 if (ri == null) {
2020 ri = sri;
2021 }
2022 j--;
2023 N--;
2024 }
2025 }
2026
2027 // Add this specific item to its proper place.
2028 if (ri == null) {
2029 ri = new ResolveInfo();
2030 ri.activityInfo = ai;
2031 }
2032 results.add(specificsPos, ri);
2033 ri.specificIndex = i;
2034 specificsPos++;
2035 }
2036 }
2037
2038 // Now we go through the remaining generic results and remove any
2039 // duplicate actions that are found here.
2040 N = results.size();
2041 for (int i=specificsPos; i<N-1; i++) {
2042 final ResolveInfo rii = results.get(i);
2043 if (rii.filter == null) {
2044 continue;
2045 }
2046
2047 // Iterate over all of the actions of this result's intent
2048 // filter... typically this should be just one.
2049 final Iterator<String> it = rii.filter.actionsIterator();
2050 if (it == null) {
2051 continue;
2052 }
2053 while (it.hasNext()) {
2054 final String action = it.next();
2055 if (resultsAction != null && resultsAction.equals(action)) {
2056 // If this action was explicitly requested, then don't
2057 // remove things that have it.
2058 continue;
2059 }
2060 for (int j=i+1; j<N; j++) {
2061 final ResolveInfo rij = results.get(j);
2062 if (rij.filter != null && rij.filter.hasAction(action)) {
2063 results.remove(j);
2064 if (Config.LOGV) Log.v(
2065 TAG, "Removing duplicate item from " + j
2066 + " due to action " + action + " at " + i);
2067 j--;
2068 N--;
2069 }
2070 }
2071 }
2072
2073 // If the caller didn't request filter information, drop it now
2074 // so we don't have to marshall/unmarshall it.
2075 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2076 rii.filter = null;
2077 }
2078 }
2079
2080 // Filter out the caller activity if so requested.
2081 if (caller != null) {
2082 N = results.size();
2083 for (int i=0; i<N; i++) {
2084 ActivityInfo ainfo = results.get(i).activityInfo;
2085 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2086 && caller.getClassName().equals(ainfo.name)) {
2087 results.remove(i);
2088 break;
2089 }
2090 }
2091 }
2092
2093 // If the caller didn't request filter information,
2094 // drop them now so we don't have to
2095 // marshall/unmarshall it.
2096 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2097 N = results.size();
2098 for (int i=0; i<N; i++) {
2099 results.get(i).filter = null;
2100 }
2101 }
2102
2103 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2104 return results;
2105 }
2106
2107 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2108 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002109 ComponentName comp = intent.getComponent();
2110 if (comp != null) {
2111 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2112 ActivityInfo ai = getReceiverInfo(comp, flags);
2113 if (ai != null) {
2114 ResolveInfo ri = new ResolveInfo();
2115 ri.activityInfo = ai;
2116 list.add(ri);
2117 }
2118 return list;
2119 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002122 String pkgName = intent.getPackage();
2123 if (pkgName == null) {
2124 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2125 resolvedType, flags);
2126 }
2127 PackageParser.Package pkg = mPackages.get(pkgName);
2128 if (pkg != null) {
2129 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2130 resolvedType, flags, pkg.receivers);
2131 }
2132 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 }
2134 }
2135
2136 public ResolveInfo resolveService(Intent intent, String resolvedType,
2137 int flags) {
2138 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2139 flags);
2140 if (query != null) {
2141 if (query.size() >= 1) {
2142 // If there is more than one service with the same priority,
2143 // just arbitrarily pick the first one.
2144 return query.get(0);
2145 }
2146 }
2147 return null;
2148 }
2149
2150 public List<ResolveInfo> queryIntentServices(Intent intent,
2151 String resolvedType, int flags) {
2152 ComponentName comp = intent.getComponent();
2153 if (comp != null) {
2154 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2155 ServiceInfo si = getServiceInfo(comp, flags);
2156 if (si != null) {
2157 ResolveInfo ri = new ResolveInfo();
2158 ri.serviceInfo = si;
2159 list.add(ri);
2160 }
2161 return list;
2162 }
2163
2164 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002165 String pkgName = intent.getPackage();
2166 if (pkgName == null) {
2167 return (List<ResolveInfo>)mServices.queryIntent(intent,
2168 resolvedType, flags);
2169 }
2170 PackageParser.Package pkg = mPackages.get(pkgName);
2171 if (pkg != null) {
2172 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2173 resolvedType, flags, pkg.services);
2174 }
2175 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 }
2177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 public List<PackageInfo> getInstalledPackages(int flags) {
2180 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2181
2182 synchronized (mPackages) {
2183 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2184 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2185 while (i.hasNext()) {
2186 final PackageSetting ps = i.next();
2187 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2188 if(psPkg != null) {
2189 finalList.add(psPkg);
2190 }
2191 }
2192 }
2193 else {
2194 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2195 while (i.hasNext()) {
2196 final PackageParser.Package p = i.next();
2197 if (p.applicationInfo != null) {
2198 PackageInfo pi = generatePackageInfo(p, flags);
2199 if(pi != null) {
2200 finalList.add(pi);
2201 }
2202 }
2203 }
2204 }
2205 }
2206 return finalList;
2207 }
2208
2209 public List<ApplicationInfo> getInstalledApplications(int flags) {
2210 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2211 synchronized(mPackages) {
2212 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2213 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2214 while (i.hasNext()) {
2215 final PackageSetting ps = i.next();
2216 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2217 if(ai != null) {
2218 finalList.add(ai);
2219 }
2220 }
2221 }
2222 else {
2223 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2224 while (i.hasNext()) {
2225 final PackageParser.Package p = i.next();
2226 if (p.applicationInfo != null) {
2227 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2228 if(ai != null) {
2229 finalList.add(ai);
2230 }
2231 }
2232 }
2233 }
2234 }
2235 return finalList;
2236 }
2237
2238 public List<ApplicationInfo> getPersistentApplications(int flags) {
2239 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2240
2241 synchronized (mPackages) {
2242 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2243 while (i.hasNext()) {
2244 PackageParser.Package p = i.next();
2245 if (p.applicationInfo != null
2246 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2247 && (!mSafeMode || (p.applicationInfo.flags
2248 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2249 finalList.add(p.applicationInfo);
2250 }
2251 }
2252 }
2253
2254 return finalList;
2255 }
2256
2257 public ProviderInfo resolveContentProvider(String name, int flags) {
2258 synchronized (mPackages) {
2259 final PackageParser.Provider provider = mProviders.get(name);
2260 return provider != null
2261 && mSettings.isEnabledLP(provider.info, flags)
2262 && (!mSafeMode || (provider.info.applicationInfo.flags
2263 &ApplicationInfo.FLAG_SYSTEM) != 0)
2264 ? PackageParser.generateProviderInfo(provider, flags)
2265 : null;
2266 }
2267 }
2268
Fred Quintana718d8a22009-04-29 17:53:20 -07002269 /**
2270 * @deprecated
2271 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 public void querySyncProviders(List outNames, List outInfo) {
2273 synchronized (mPackages) {
2274 Iterator<Map.Entry<String, PackageParser.Provider>> i
2275 = mProviders.entrySet().iterator();
2276
2277 while (i.hasNext()) {
2278 Map.Entry<String, PackageParser.Provider> entry = i.next();
2279 PackageParser.Provider p = entry.getValue();
2280
2281 if (p.syncable
2282 && (!mSafeMode || (p.info.applicationInfo.flags
2283 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2284 outNames.add(entry.getKey());
2285 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2286 }
2287 }
2288 }
2289 }
2290
2291 public List<ProviderInfo> queryContentProviders(String processName,
2292 int uid, int flags) {
2293 ArrayList<ProviderInfo> finalList = null;
2294
2295 synchronized (mPackages) {
2296 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2297 while (i.hasNext()) {
2298 PackageParser.Provider p = i.next();
2299 if (p.info.authority != null
2300 && (processName == null ||
2301 (p.info.processName.equals(processName)
2302 && p.info.applicationInfo.uid == uid))
2303 && mSettings.isEnabledLP(p.info, flags)
2304 && (!mSafeMode || (p.info.applicationInfo.flags
2305 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2306 if (finalList == null) {
2307 finalList = new ArrayList<ProviderInfo>(3);
2308 }
2309 finalList.add(PackageParser.generateProviderInfo(p,
2310 flags));
2311 }
2312 }
2313 }
2314
2315 if (finalList != null) {
2316 Collections.sort(finalList, mProviderInitOrderSorter);
2317 }
2318
2319 return finalList;
2320 }
2321
2322 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2323 int flags) {
2324 synchronized (mPackages) {
2325 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2326 return PackageParser.generateInstrumentationInfo(i, flags);
2327 }
2328 }
2329
2330 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2331 int flags) {
2332 ArrayList<InstrumentationInfo> finalList =
2333 new ArrayList<InstrumentationInfo>();
2334
2335 synchronized (mPackages) {
2336 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2337 while (i.hasNext()) {
2338 PackageParser.Instrumentation p = i.next();
2339 if (targetPackage == null
2340 || targetPackage.equals(p.info.targetPackage)) {
2341 finalList.add(PackageParser.generateInstrumentationInfo(p,
2342 flags));
2343 }
2344 }
2345 }
2346
2347 return finalList;
2348 }
2349
2350 private void scanDirLI(File dir, int flags, int scanMode) {
2351 Log.d(TAG, "Scanning app dir " + dir);
2352
2353 String[] files = dir.list();
2354
2355 int i;
2356 for (i=0; i<files.length; i++) {
2357 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002358 if (!isPackageFilename(files[i])) {
2359 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002360 continue;
2361 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002362 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002364 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002365 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2366 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002367 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002368 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002369 file.delete();
2370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 }
2372 }
2373
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002374 private static File getSettingsProblemFile() {
2375 File dataDir = Environment.getDataDirectory();
2376 File systemDir = new File(dataDir, "system");
2377 File fname = new File(systemDir, "uiderrors.txt");
2378 return fname;
2379 }
2380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 private static void reportSettingsProblem(int priority, String msg) {
2382 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002383 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 FileOutputStream out = new FileOutputStream(fname, true);
2385 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002386 SimpleDateFormat formatter = new SimpleDateFormat();
2387 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2388 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 pw.close();
2390 FileUtils.setPermissions(
2391 fname.toString(),
2392 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2393 -1, -1);
2394 } catch (java.io.IOException e) {
2395 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002396 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 }
2398
2399 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2400 PackageParser.Package pkg, File srcFile, int parseFlags) {
2401 if (GET_CERTIFICATES) {
2402 if (ps == null || !ps.codePath.equals(srcFile)
2403 || ps.getTimeStamp() != srcFile.lastModified()) {
2404 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2405 if (!pp.collectCertificates(pkg, parseFlags)) {
2406 mLastScanError = pp.getParseError();
2407 return false;
2408 }
2409 }
2410 }
2411 return true;
2412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 /*
2415 * Scan a package and return the newly parsed package.
2416 * Returns null in case of errors and the error code is stored in mLastScanError
2417 */
2418 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002419 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002421 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002423 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002426 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427 if (pkg == null) {
2428 mLastScanError = pp.getParseError();
2429 return null;
2430 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002431 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 PackageSetting updatedPkg;
2433 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002434 // Look to see if we already know about this package.
2435 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002436 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002437 // This package has been renamed to its original name. Let's
2438 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002439 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002440 }
2441 // If there was no original package, see one for the real package name.
2442 if (ps == null) {
2443 ps = mSettings.peekPackageLP(pkg.packageName);
2444 }
2445 // Check to see if this package could be hiding/updating a system
2446 // package. Must look for it either under the original or real
2447 // package name depending on our state.
2448 updatedPkg = mSettings.mDisabledSysPackages.get(
2449 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002451 // First check if this is a system package that may involve an update
2452 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2453 if (!ps.codePath.equals(scanFile)) {
2454 // The path has changed from what was last scanned... check the
2455 // version of the new path against what we have stored to determine
2456 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002457 if (pkg.mVersionCode < ps.versionCode) {
2458 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002459 // Ignore entry. Skip it.
2460 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2461 + "ignored: updated version " + ps.versionCode
2462 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002463 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2464 return null;
2465 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002466 // The current app on the system partion is better than
2467 // what we have updated to on the data partition; switch
2468 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002469 // At this point, its safely assumed that package installation for
2470 // apps in system partition will go through. If not there won't be a working
2471 // version of the app
2472 synchronized (mPackages) {
2473 // Just remove the loaded entries from package lists.
2474 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002475 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002476 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002477 + "reverting from " + ps.codePathString
2478 + ": new version " + pkg.mVersionCode
2479 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002480 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2481 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002482 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 }
2485 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002486 if (updatedPkg != null) {
2487 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2488 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2489 }
2490 // Verify certificates against what was last scanned
2491 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002492 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002493 return null;
2494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 // The apk is forward locked (not public) if its code and resources
2496 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002497 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002499 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002500 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002501
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002502 String codePath = null;
2503 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002504 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2505 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002506 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002507 } else {
2508 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002509 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002510 }
2511 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002512 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002513 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002514 codePath = pkg.mScanPath;
2515 // Set application objects path explicitly.
2516 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002518 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 }
2520
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002521 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2522 String destCodePath, String destResPath) {
2523 pkg.mPath = pkg.mScanPath = destCodePath;
2524 pkg.applicationInfo.sourceDir = destCodePath;
2525 pkg.applicationInfo.publicSourceDir = destResPath;
2526 }
2527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 private static String fixProcessName(String defProcessName,
2529 String processName, int uid) {
2530 if (processName == null) {
2531 return defProcessName;
2532 }
2533 return processName;
2534 }
2535
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002536 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2538 if (pkg.mSignatures != null) {
2539 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2540 updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002541 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 + " signatures do not match the previously installed version; ignoring!");
2543 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2544 return false;
2545 }
2546
2547 if (pkgSetting.sharedUser != null) {
2548 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2549 pkg.mSignatures, updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002550 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 + " has no signatures that match those in shared user "
2552 + pkgSetting.sharedUser.name + "; ignoring!");
2553 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2554 return false;
2555 }
2556 }
2557 } else {
2558 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2559 }
2560 return true;
2561 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002562
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002563 public boolean performDexOpt(String packageName) {
2564 if (!mNoDexOpt) {
2565 return false;
2566 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002567
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002568 PackageParser.Package p;
2569 synchronized (mPackages) {
2570 p = mPackages.get(packageName);
2571 if (p == null || p.mDidDexOpt) {
2572 return false;
2573 }
2574 }
2575 synchronized (mInstallLock) {
2576 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2577 }
2578 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002579
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002580 static final int DEX_OPT_SKIPPED = 0;
2581 static final int DEX_OPT_PERFORMED = 1;
2582 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002583
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002584 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2585 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002586 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002587 String path = pkg.mScanPath;
2588 int ret = 0;
2589 try {
2590 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002591 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002592 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002593 pkg.mDidDexOpt = true;
2594 performed = true;
2595 }
2596 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002597 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002598 ret = -1;
2599 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002600 Slog.w(TAG, "Exception reading apk: " + path, e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002601 ret = -1;
2602 }
2603 if (ret < 0) {
2604 //error from installer
2605 return DEX_OPT_FAILED;
2606 }
2607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002608
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002609 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2610 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002611
2612 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2613 return Environment.isEncryptedFilesystemEnabled() &&
2614 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2615 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002616
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002617 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2618 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002619 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002620 + " to " + newPkg.packageName
2621 + ": old package not in system partition");
2622 return false;
2623 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002624 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002625 + " to " + newPkg.packageName
2626 + ": old package still exists");
2627 return false;
2628 }
2629 return true;
2630 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002631
2632 private File getDataPathForPackage(PackageParser.Package pkg) {
2633 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2634 File dataPath;
2635 if (useEncryptedFSDir) {
2636 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2637 } else {
2638 dataPath = new File(mAppDataDir, pkg.packageName);
2639 }
2640 return dataPath;
2641 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002642
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002643 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2644 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002645 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002646 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2647 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002648 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002649 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002650 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2651 return null;
2652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 mScanningPath = scanFile;
2654 if (pkg == null) {
2655 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2656 return null;
2657 }
2658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2660 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2661 }
2662
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002663 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 synchronized (mPackages) {
2665 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002666 Slog.w(TAG, "*************************************************");
2667 Slog.w(TAG, "Core android package being redefined. Skipping.");
2668 Slog.w(TAG, " file=" + mScanningPath);
2669 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2671 return null;
2672 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 // Set up information for our fall-back user intent resolution
2675 // activity.
2676 mPlatformPackage = pkg;
2677 pkg.mVersionCode = mSdkVersion;
2678 mAndroidApplication = pkg.applicationInfo;
2679 mResolveActivity.applicationInfo = mAndroidApplication;
2680 mResolveActivity.name = ResolverActivity.class.getName();
2681 mResolveActivity.packageName = mAndroidApplication.packageName;
2682 mResolveActivity.processName = mAndroidApplication.processName;
2683 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2684 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2685 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2686 mResolveActivity.exported = true;
2687 mResolveActivity.enabled = true;
2688 mResolveInfo.activityInfo = mResolveActivity;
2689 mResolveInfo.priority = 0;
2690 mResolveInfo.preferredOrder = 0;
2691 mResolveInfo.match = 0;
2692 mResolveComponentName = new ComponentName(
2693 mAndroidApplication.packageName, mResolveActivity.name);
2694 }
2695 }
2696
2697 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002698 TAG, "Scanning package " + pkg.packageName);
2699 if (mPackages.containsKey(pkg.packageName)
2700 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002701 Slog.w(TAG, "*************************************************");
2702 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002704 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2706 return null;
2707 }
2708
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002709 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002710 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2711 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 SharedUserSetting suid = null;
2714 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002715
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002716 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2717 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002718 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002719 pkg.mRealPackage = null;
2720 pkg.mAdoptPermissions = null;
2721 }
2722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 synchronized (mPackages) {
2724 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002725 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2726 if (mTmpSharedLibraries == null ||
2727 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2728 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2729 }
2730 int num = 0;
2731 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2732 for (int i=0; i<N; i++) {
2733 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002735 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002737 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2739 return null;
2740 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002741 mTmpSharedLibraries[num] = file;
2742 num++;
2743 }
2744 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2745 for (int i=0; i<N; i++) {
2746 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2747 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002748 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002749 + " desires unavailable shared library "
2750 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2751 } else {
2752 mTmpSharedLibraries[num] = file;
2753 num++;
2754 }
2755 }
2756 if (num > 0) {
2757 pkg.usesLibraryFiles = new String[num];
2758 System.arraycopy(mTmpSharedLibraries, 0,
2759 pkg.usesLibraryFiles, 0, num);
2760 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002761
Dianne Hackborn49237342009-08-27 20:08:01 -07002762 if (pkg.reqFeatures != null) {
2763 N = pkg.reqFeatures.size();
2764 for (int i=0; i<N; i++) {
2765 FeatureInfo fi = pkg.reqFeatures.get(i);
2766 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2767 // Don't care.
2768 continue;
2769 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002770
Dianne Hackborn49237342009-08-27 20:08:01 -07002771 if (fi.name != null) {
2772 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002773 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002774 + " requires unavailable feature "
2775 + fi.name + "; failing!");
2776 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2777 return null;
2778 }
2779 }
2780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 }
2782 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 if (pkg.mSharedUserId != null) {
2785 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2786 pkg.applicationInfo.flags, true);
2787 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002788 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 + " for shared user failed");
2790 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2791 return null;
2792 }
2793 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2794 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2795 + suid.userId + "): packages=" + suid.packages);
2796 }
2797 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002798
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002799 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002800 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002801 Log.w(TAG, "WAITING FOR DEBUGGER");
2802 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002803 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2804 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002805 }
2806 }
2807
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002808 // Check if we are renaming from an original package name.
2809 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002810 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002811 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002812 // This package may need to be renamed to a previously
2813 // installed name. Let's check on that...
2814 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002815 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002816 // This package had originally been installed as the
2817 // original name, and we have already taken care of
2818 // transitioning to the new one. Just update the new
2819 // one to continue using the old name.
2820 realName = pkg.mRealPackage;
2821 if (!pkg.packageName.equals(renamed)) {
2822 // Callers into this function may have already taken
2823 // care of renaming the package; only do it here if
2824 // it is not already done.
2825 pkg.setPackageName(renamed);
2826 }
2827
Dianne Hackbornc1552392010-03-03 16:19:01 -08002828 } else {
2829 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2830 if ((origPackage=mSettings.peekPackageLP(
2831 pkg.mOriginalPackages.get(i))) != null) {
2832 // We do have the package already installed under its
2833 // original name... should we use it?
2834 if (!verifyPackageUpdate(origPackage, pkg)) {
2835 // New package is not compatible with original.
2836 origPackage = null;
2837 continue;
2838 } else if (origPackage.sharedUser != null) {
2839 // Make sure uid is compatible between packages.
2840 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002841 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002842 + " to " + pkg.packageName + ": old uid "
2843 + origPackage.sharedUser.name
2844 + " differs from " + pkg.mSharedUserId);
2845 origPackage = null;
2846 continue;
2847 }
2848 } else {
2849 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2850 + pkg.packageName + " to old name " + origPackage.name);
2851 }
2852 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002853 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002854 }
2855 }
2856 }
2857
2858 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002859 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002860 + " was transferred to another, but its .apk remains");
2861 }
2862
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002863 // Just create the setting, don't add it yet. For already existing packages
2864 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002865 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 destResourceFile, pkg.applicationInfo.flags, true, false);
2867 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002868 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2870 return null;
2871 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002872
2873 if (pkgSetting.origPackage != null) {
2874 // If we are first transitioning from an original package,
2875 // fix up the new package's name now. We need to do this after
2876 // looking up the package under its new name, so getPackageLP
2877 // can take care of fiddling things correctly.
2878 pkg.setPackageName(origPackage.name);
2879
2880 // File a report about this.
2881 String msg = "New package " + pkgSetting.realName
2882 + " renamed to replace old package " + pkgSetting.name;
2883 reportSettingsProblem(Log.WARN, msg);
2884
2885 // Make a note of it.
2886 mTransferedPackages.add(origPackage.name);
2887
2888 // No longer need to retain this.
2889 pkgSetting.origPackage = null;
2890 }
2891
2892 if (realName != null) {
2893 // Make a note of it.
2894 mTransferedPackages.add(pkg.packageName);
2895 }
2896
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002897 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2899 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 pkg.applicationInfo.uid = pkgSetting.userId;
2902 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002903
2904 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002906 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2908 return null;
2909 }
2910 // The signature has changed, but this package is in the system
2911 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002912 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 // However... if this package is part of a shared user, but it
2914 // doesn't match the signature of the shared user, let's fail.
2915 // What this means is that you can't change the signatures
2916 // associated with an overall shared user, which doesn't seem all
2917 // that unreasonable.
2918 if (pkgSetting.sharedUser != null) {
2919 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2920 pkg.mSignatures, false)) {
2921 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2922 return null;
2923 }
2924 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002925 // File a report about this.
2926 String msg = "System package " + pkg.packageName
2927 + " signature changed; retaining data.";
2928 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002930
The Android Open Source Project10592532009-03-18 17:39:46 -07002931 // Verify that this new package doesn't have any content providers
2932 // that conflict with existing packages. Only do this if the
2933 // package isn't already installed, since we don't want to break
2934 // things that are installed.
2935 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2936 int N = pkg.providers.size();
2937 int i;
2938 for (i=0; i<N; i++) {
2939 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002940 if (p.info.authority != null) {
2941 String names[] = p.info.authority.split(";");
2942 for (int j = 0; j < names.length; j++) {
2943 if (mProviders.containsKey(names[j])) {
2944 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002945 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002946 " (in package " + pkg.applicationInfo.packageName +
2947 ") is already used by "
2948 + ((other != null && other.getComponentName() != null)
2949 ? other.getComponentName().getPackageName() : "?"));
2950 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2951 return null;
2952 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002953 }
2954 }
2955 }
2956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 }
2958
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002959 final String pkgName = pkg.packageName;
2960
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002961 if (pkg.mAdoptPermissions != null) {
2962 // This package wants to adopt ownership of permissions from
2963 // another package.
2964 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2965 String origName = pkg.mAdoptPermissions.get(i);
2966 PackageSetting orig = mSettings.peekPackageLP(origName);
2967 if (orig != null) {
2968 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002969 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002970 + origName + " to " + pkg.packageName);
2971 mSettings.transferPermissions(origName, pkg.packageName);
2972 }
2973 }
2974 }
2975 }
2976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 long scanFileTime = scanFile.lastModified();
2978 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2979 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2980 pkg.applicationInfo.processName = fixProcessName(
2981 pkg.applicationInfo.packageName,
2982 pkg.applicationInfo.processName,
2983 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984
2985 File dataPath;
2986 if (mPlatformPackage == pkg) {
2987 // The system package is special.
2988 dataPath = new File (Environment.getDataDirectory(), "system");
2989 pkg.applicationInfo.dataDir = dataPath.getPath();
2990 } else {
2991 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002992 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002993 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002994
2995 boolean uidError = false;
2996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 if (dataPath.exists()) {
2998 mOutPermissions[1] = 0;
2999 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3000 if (mOutPermissions[1] == pkg.applicationInfo.uid
3001 || !Process.supportsProcesses()) {
3002 pkg.applicationInfo.dataDir = dataPath.getPath();
3003 } else {
3004 boolean recovered = false;
3005 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3006 // If this is a system app, we can at least delete its
3007 // current data so the application will still work.
3008 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003009 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003010 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 // Old data gone!
3012 String msg = "System package " + pkg.packageName
3013 + " has changed from uid: "
3014 + mOutPermissions[1] + " to "
3015 + pkg.applicationInfo.uid + "; old data erased";
3016 reportSettingsProblem(Log.WARN, msg);
3017 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003020 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 pkg.applicationInfo.uid);
3022 if (ret == -1) {
3023 // Ack should not happen!
3024 msg = "System package " + pkg.packageName
3025 + " could not have data directory re-created after delete.";
3026 reportSettingsProblem(Log.WARN, msg);
3027 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3028 return null;
3029 }
3030 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 if (!recovered) {
3033 mHasSystemUidErrors = true;
3034 }
3035 }
3036 if (!recovered) {
3037 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3038 + pkg.applicationInfo.uid + "/fs_"
3039 + mOutPermissions[1];
3040 String msg = "Package " + pkg.packageName
3041 + " has mismatched uid: "
3042 + mOutPermissions[1] + " on disk, "
3043 + pkg.applicationInfo.uid + " in settings";
3044 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003045 mSettings.mReadMessages.append(msg);
3046 mSettings.mReadMessages.append('\n');
3047 uidError = true;
3048 if (!pkgSetting.uidError) {
3049 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 }
3052 }
3053 }
3054 pkg.applicationInfo.dataDir = dataPath.getPath();
3055 } else {
3056 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3057 Log.v(TAG, "Want this data dir: " + dataPath);
3058 //invoke installer to do the actual installation
3059 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003060 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 pkg.applicationInfo.uid);
3062 if(ret < 0) {
3063 // Error from installer
3064 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3065 return null;
3066 }
3067 } else {
3068 dataPath.mkdirs();
3069 if (dataPath.exists()) {
3070 FileUtils.setPermissions(
3071 dataPath.toString(),
3072 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3073 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3074 }
3075 }
3076 if (dataPath.exists()) {
3077 pkg.applicationInfo.dataDir = dataPath.getPath();
3078 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003079 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 pkg.applicationInfo.dataDir = null;
3081 }
3082 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003083
3084 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 }
3086
3087 // Perform shared library installation and dex validation and
3088 // optimization, if this is not a system app.
3089 if (mInstaller != null) {
3090 String path = scanFile.getPath();
3091 if (scanFileNewer) {
3092 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003093 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3094 if (err != PackageManager.INSTALL_SUCCEEDED) {
3095 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 return null;
3097 }
3098 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003099 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003100
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003101 if ((scanMode&SCAN_NO_DEX) == 0) {
3102 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003103 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3104 return null;
3105 }
3106 }
3107 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109 if (mFactoryTest && pkg.requestedPermissions.contains(
3110 android.Manifest.permission.FACTORY_TEST)) {
3111 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3112 }
3113
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003114 // Request the ActivityManager to kill the process(only for existing packages)
3115 // so that we do not end up in a confused state while the user is still using the older
3116 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003117 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003118 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003119 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003120 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003123 // We don't expect installation to fail beyond this point,
3124 if ((scanMode&SCAN_MONITOR) != 0) {
3125 mAppDirs.put(pkg.mPath, pkg);
3126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003128 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003130 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003131 // Make sure we don't accidentally delete its data.
3132 mSettings.mPackagesToBeCleaned.remove(pkgName);
3133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003134 int N = pkg.providers.size();
3135 StringBuilder r = null;
3136 int i;
3137 for (i=0; i<N; i++) {
3138 PackageParser.Provider p = pkg.providers.get(i);
3139 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3140 p.info.processName, pkg.applicationInfo.uid);
3141 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3142 p.info.name), p);
3143 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003144 if (p.info.authority != null) {
3145 String names[] = p.info.authority.split(";");
3146 p.info.authority = null;
3147 for (int j = 0; j < names.length; j++) {
3148 if (j == 1 && p.syncable) {
3149 // We only want the first authority for a provider to possibly be
3150 // syncable, so if we already added this provider using a different
3151 // authority clear the syncable flag. We copy the provider before
3152 // changing it because the mProviders object contains a reference
3153 // to a provider that we don't want to change.
3154 // Only do this for the second authority since the resulting provider
3155 // object can be the same for all future authorities for this provider.
3156 p = new PackageParser.Provider(p);
3157 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003159 if (!mProviders.containsKey(names[j])) {
3160 mProviders.put(names[j], p);
3161 if (p.info.authority == null) {
3162 p.info.authority = names[j];
3163 } else {
3164 p.info.authority = p.info.authority + ";" + names[j];
3165 }
3166 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3167 Log.d(TAG, "Registered content provider: " + names[j] +
3168 ", className = " + p.info.name +
3169 ", isSyncable = " + p.info.isSyncable);
3170 } else {
3171 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003172 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003173 " (in package " + pkg.applicationInfo.packageName +
3174 "): name already used by "
3175 + ((other != null && other.getComponentName() != null)
3176 ? other.getComponentName().getPackageName() : "?"));
3177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 }
3179 }
3180 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3181 if (r == null) {
3182 r = new StringBuilder(256);
3183 } else {
3184 r.append(' ');
3185 }
3186 r.append(p.info.name);
3187 }
3188 }
3189 if (r != null) {
3190 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3191 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 N = pkg.services.size();
3194 r = null;
3195 for (i=0; i<N; i++) {
3196 PackageParser.Service s = pkg.services.get(i);
3197 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3198 s.info.processName, pkg.applicationInfo.uid);
3199 mServices.addService(s);
3200 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3201 if (r == null) {
3202 r = new StringBuilder(256);
3203 } else {
3204 r.append(' ');
3205 }
3206 r.append(s.info.name);
3207 }
3208 }
3209 if (r != null) {
3210 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3211 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 N = pkg.receivers.size();
3214 r = null;
3215 for (i=0; i<N; i++) {
3216 PackageParser.Activity a = pkg.receivers.get(i);
3217 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3218 a.info.processName, pkg.applicationInfo.uid);
3219 mReceivers.addActivity(a, "receiver");
3220 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3221 if (r == null) {
3222 r = new StringBuilder(256);
3223 } else {
3224 r.append(' ');
3225 }
3226 r.append(a.info.name);
3227 }
3228 }
3229 if (r != null) {
3230 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3231 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 N = pkg.activities.size();
3234 r = null;
3235 for (i=0; i<N; i++) {
3236 PackageParser.Activity a = pkg.activities.get(i);
3237 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3238 a.info.processName, pkg.applicationInfo.uid);
3239 mActivities.addActivity(a, "activity");
3240 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3241 if (r == null) {
3242 r = new StringBuilder(256);
3243 } else {
3244 r.append(' ');
3245 }
3246 r.append(a.info.name);
3247 }
3248 }
3249 if (r != null) {
3250 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3251 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 N = pkg.permissionGroups.size();
3254 r = null;
3255 for (i=0; i<N; i++) {
3256 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3257 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3258 if (cur == null) {
3259 mPermissionGroups.put(pg.info.name, pg);
3260 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3261 if (r == null) {
3262 r = new StringBuilder(256);
3263 } else {
3264 r.append(' ');
3265 }
3266 r.append(pg.info.name);
3267 }
3268 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003269 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 + pg.info.packageName + " ignored: original from "
3271 + cur.info.packageName);
3272 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3273 if (r == null) {
3274 r = new StringBuilder(256);
3275 } else {
3276 r.append(' ');
3277 }
3278 r.append("DUP:");
3279 r.append(pg.info.name);
3280 }
3281 }
3282 }
3283 if (r != null) {
3284 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3285 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 N = pkg.permissions.size();
3288 r = null;
3289 for (i=0; i<N; i++) {
3290 PackageParser.Permission p = pkg.permissions.get(i);
3291 HashMap<String, BasePermission> permissionMap =
3292 p.tree ? mSettings.mPermissionTrees
3293 : mSettings.mPermissions;
3294 p.group = mPermissionGroups.get(p.info.group);
3295 if (p.info.group == null || p.group != null) {
3296 BasePermission bp = permissionMap.get(p.info.name);
3297 if (bp == null) {
3298 bp = new BasePermission(p.info.name, p.info.packageName,
3299 BasePermission.TYPE_NORMAL);
3300 permissionMap.put(p.info.name, bp);
3301 }
3302 if (bp.perm == null) {
3303 if (bp.sourcePackage == null
3304 || bp.sourcePackage.equals(p.info.packageName)) {
3305 BasePermission tree = findPermissionTreeLP(p.info.name);
3306 if (tree == null
3307 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003308 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 bp.perm = p;
3310 bp.uid = pkg.applicationInfo.uid;
3311 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3312 if (r == null) {
3313 r = new StringBuilder(256);
3314 } else {
3315 r.append(' ');
3316 }
3317 r.append(p.info.name);
3318 }
3319 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003320 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 + p.info.packageName + " ignored: base tree "
3322 + tree.name + " is from package "
3323 + tree.sourcePackage);
3324 }
3325 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003326 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 + p.info.packageName + " ignored: original from "
3328 + bp.sourcePackage);
3329 }
3330 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3331 if (r == null) {
3332 r = new StringBuilder(256);
3333 } else {
3334 r.append(' ');
3335 }
3336 r.append("DUP:");
3337 r.append(p.info.name);
3338 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003339 if (bp.perm == p) {
3340 bp.protectionLevel = p.info.protectionLevel;
3341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003342 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003343 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 + p.info.packageName + " ignored: no group "
3345 + p.group);
3346 }
3347 }
3348 if (r != null) {
3349 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3350 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 N = pkg.instrumentation.size();
3353 r = null;
3354 for (i=0; i<N; i++) {
3355 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3356 a.info.packageName = pkg.applicationInfo.packageName;
3357 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3358 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3359 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003360 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3362 if (r == null) {
3363 r = new StringBuilder(256);
3364 } else {
3365 r.append(' ');
3366 }
3367 r.append(a.info.name);
3368 }
3369 }
3370 if (r != null) {
3371 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3372 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003373
Dianne Hackborn854060af2009-07-09 18:14:31 -07003374 if (pkg.protectedBroadcasts != null) {
3375 N = pkg.protectedBroadcasts.size();
3376 for (i=0; i<N; i++) {
3377 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3378 }
3379 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 pkgSetting.setTimeStamp(scanFileTime);
3382 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 return pkg;
3385 }
3386
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003387 private void killApplication(String pkgName, int uid) {
3388 // Request the ActivityManager to kill the process(only for existing packages)
3389 // so that we do not end up in a confused state while the user is still using the older
3390 // version of the application while the new one gets installed.
3391 IActivityManager am = ActivityManagerNative.getDefault();
3392 if (am != null) {
3393 try {
3394 am.killApplicationWithUid(pkgName, uid);
3395 } catch (RemoteException e) {
3396 }
3397 }
3398 }
3399
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003400 // The following constants are returned by cachePackageSharedLibsForAbiLI
3401 // to indicate if native shared libraries were found in the package.
3402 // Values are:
3403 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3404 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3405 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3406 // in package (and not installed)
3407 //
3408 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3409 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3410 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003412 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3413 // and automatically copy them to /data/data/<appname>/lib if present.
3414 //
3415 // NOTE: this method may throw an IOException if the library cannot
3416 // be copied to its final destination, e.g. if there isn't enough
3417 // room left on the data partition, or a ZipException if the package
3418 // file is malformed.
3419 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003420 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3421 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003422 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3423 final String apkLib = "lib/";
3424 final int apkLibLen = apkLib.length();
3425 final int cpuAbiLen = cpuAbi.length();
3426 final String libPrefix = "lib";
3427 final int libPrefixLen = libPrefix.length();
3428 final String libSuffix = ".so";
3429 final int libSuffixLen = libSuffix.length();
3430 boolean hasNativeLibraries = false;
3431 boolean installedNativeLibraries = false;
3432
3433 // the minimum length of a valid native shared library of the form
3434 // lib/<something>/lib<name>.so.
3435 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3436
3437 ZipFile zipFile = new ZipFile(scanFile);
3438 Enumeration<ZipEntry> entries =
3439 (Enumeration<ZipEntry>) zipFile.entries();
3440
3441 while (entries.hasMoreElements()) {
3442 ZipEntry entry = entries.nextElement();
3443 // skip directories
3444 if (entry.isDirectory()) {
3445 continue;
3446 }
3447 String entryName = entry.getName();
3448
3449 // check that the entry looks like lib/<something>/lib<name>.so
3450 // here, but don't check the ABI just yet.
3451 //
3452 // - must be sufficiently long
3453 // - must end with libSuffix, i.e. ".so"
3454 // - must start with apkLib, i.e. "lib/"
3455 if (entryName.length() < minEntryLen ||
3456 !entryName.endsWith(libSuffix) ||
3457 !entryName.startsWith(apkLib) ) {
3458 continue;
3459 }
3460
3461 // file name must start with libPrefix, i.e. "lib"
3462 int lastSlash = entryName.lastIndexOf('/');
3463
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003464 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003465 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3466 continue;
3467 }
3468
3469 hasNativeLibraries = true;
3470
3471 // check the cpuAbi now, between lib/ and /lib<name>.so
3472 //
3473 if (lastSlash != apkLibLen + cpuAbiLen ||
3474 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3475 continue;
3476
3477 // extract the library file name, ensure it doesn't contain
3478 // weird characters. we're guaranteed here that it doesn't contain
3479 // a directory separator though.
3480 String libFileName = entryName.substring(lastSlash+1);
3481 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3482 continue;
3483 }
3484
3485 installedNativeLibraries = true;
3486
3487 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3488 File.separator + libFileName;
3489 File sharedLibraryFile = new File(sharedLibraryFilePath);
3490 if (! sharedLibraryFile.exists() ||
3491 sharedLibraryFile.length() != entry.getSize() ||
3492 sharedLibraryFile.lastModified() != entry.getTime()) {
3493 if (Config.LOGD) {
3494 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003496 if (mInstaller == null) {
3497 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003498 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003499 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003500 sharedLibraryFile);
3501 }
3502 }
3503 if (!hasNativeLibraries)
3504 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3505
3506 if (!installedNativeLibraries)
3507 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3508
3509 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3510 }
3511
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003512 // Find the gdbserver executable program in a package at
3513 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3514 //
3515 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3516 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3517 //
3518 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3519 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3520 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3521 final String GDBSERVER = "gdbserver";
3522 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3523
3524 ZipFile zipFile = new ZipFile(scanFile);
3525 Enumeration<ZipEntry> entries =
3526 (Enumeration<ZipEntry>) zipFile.entries();
3527
3528 while (entries.hasMoreElements()) {
3529 ZipEntry entry = entries.nextElement();
3530 // skip directories
3531 if (entry.isDirectory()) {
3532 continue;
3533 }
3534 String entryName = entry.getName();
3535
3536 if (!entryName.equals(apkGdbServerPath)) {
3537 continue;
3538 }
3539
3540 String installGdbServerPath = installGdbServerDir.getPath() +
3541 "/" + GDBSERVER;
3542 File installGdbServerFile = new File(installGdbServerPath);
3543 if (! installGdbServerFile.exists() ||
3544 installGdbServerFile.length() != entry.getSize() ||
3545 installGdbServerFile.lastModified() != entry.getTime()) {
3546 if (Config.LOGD) {
3547 Log.d(TAG, "Caching gdbserver " + entry.getName());
3548 }
3549 if (mInstaller == null) {
3550 installGdbServerDir.mkdir();
3551 }
3552 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3553 installGdbServerFile);
3554 }
3555 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3556 }
3557 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3558 }
3559
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003560 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3561 // and copy them to /data/data/<appname>/lib.
3562 //
3563 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3564 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3565 // one if ro.product.cpu.abi2 is defined.
3566 //
3567 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3568 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003569 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003570 try {
3571 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3572
3573 // some architectures are capable of supporting several CPU ABIs
3574 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3575 // this is indicated by the definition of the ro.product.cpu.abi2
3576 // system property.
3577 //
3578 // only scan the package twice in case of ABI mismatch
3579 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003580 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003581 if (cpuAbi2 != null) {
3582 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003583 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003584
3585 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003586 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003587 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003589
3590 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3591 cpuAbi = cpuAbi2;
3592 }
3593 }
3594
3595 // for debuggable packages, also extract gdbserver from lib/<abi>
3596 // into /data/data/<appname>/lib too.
3597 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3598 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3599 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3600 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3601 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003603 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003604 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003605 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003606 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003608 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003609 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003611 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 }
3613
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003614 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003616 File binaryDir,
3617 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 InputStream inputStream = zipFile.getInputStream(entry);
3619 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003620 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003622 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 // now need to be left as world readable and owned by the system.
3624 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3625 ! tempFile.setLastModified(entry.getTime()) ||
3626 FileUtils.setPermissions(tempFilePath,
3627 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003628 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003630 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 // Failed to properly write file.
3632 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003633 throw new IOException("Couldn't create cached binary "
3634 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 }
3636 } finally {
3637 inputStream.close();
3638 }
3639 }
3640
3641 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3642 if (chatty && Config.LOGD) Log.d(
3643 TAG, "Removing package " + pkg.applicationInfo.packageName );
3644
3645 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003646 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 mPackages.remove(pkg.applicationInfo.packageName);
3649 if (pkg.mPath != null) {
3650 mAppDirs.remove(pkg.mPath);
3651 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 PackageSetting ps = (PackageSetting)pkg.mExtras;
3654 if (ps != null && ps.sharedUser != null) {
3655 // XXX don't do this until the data is removed.
3656 if (false) {
3657 ps.sharedUser.packages.remove(ps);
3658 if (ps.sharedUser.packages.size() == 0) {
3659 // Remove.
3660 }
3661 }
3662 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 int N = pkg.providers.size();
3665 StringBuilder r = null;
3666 int i;
3667 for (i=0; i<N; i++) {
3668 PackageParser.Provider p = pkg.providers.get(i);
3669 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3670 p.info.name));
3671 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 /* The is another ContentProvider with this authority when
3674 * this app was installed so this authority is null,
3675 * Ignore it as we don't have to unregister the provider.
3676 */
3677 continue;
3678 }
3679 String names[] = p.info.authority.split(";");
3680 for (int j = 0; j < names.length; j++) {
3681 if (mProviders.get(names[j]) == p) {
3682 mProviders.remove(names[j]);
3683 if (chatty && Config.LOGD) Log.d(
3684 TAG, "Unregistered content provider: " + names[j] +
3685 ", className = " + p.info.name +
3686 ", isSyncable = " + p.info.isSyncable);
3687 }
3688 }
3689 if (chatty) {
3690 if (r == null) {
3691 r = new StringBuilder(256);
3692 } else {
3693 r.append(' ');
3694 }
3695 r.append(p.info.name);
3696 }
3697 }
3698 if (r != null) {
3699 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3700 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702 N = pkg.services.size();
3703 r = null;
3704 for (i=0; i<N; i++) {
3705 PackageParser.Service s = pkg.services.get(i);
3706 mServices.removeService(s);
3707 if (chatty) {
3708 if (r == null) {
3709 r = new StringBuilder(256);
3710 } else {
3711 r.append(' ');
3712 }
3713 r.append(s.info.name);
3714 }
3715 }
3716 if (r != null) {
3717 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 N = pkg.receivers.size();
3721 r = null;
3722 for (i=0; i<N; i++) {
3723 PackageParser.Activity a = pkg.receivers.get(i);
3724 mReceivers.removeActivity(a, "receiver");
3725 if (chatty) {
3726 if (r == null) {
3727 r = new StringBuilder(256);
3728 } else {
3729 r.append(' ');
3730 }
3731 r.append(a.info.name);
3732 }
3733 }
3734 if (r != null) {
3735 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3736 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 N = pkg.activities.size();
3739 r = null;
3740 for (i=0; i<N; i++) {
3741 PackageParser.Activity a = pkg.activities.get(i);
3742 mActivities.removeActivity(a, "activity");
3743 if (chatty) {
3744 if (r == null) {
3745 r = new StringBuilder(256);
3746 } else {
3747 r.append(' ');
3748 }
3749 r.append(a.info.name);
3750 }
3751 }
3752 if (r != null) {
3753 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3754 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 N = pkg.permissions.size();
3757 r = null;
3758 for (i=0; i<N; i++) {
3759 PackageParser.Permission p = pkg.permissions.get(i);
3760 boolean tree = false;
3761 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3762 if (bp == null) {
3763 tree = true;
3764 bp = mSettings.mPermissionTrees.get(p.info.name);
3765 }
3766 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003767 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003768 if (chatty) {
3769 if (r == null) {
3770 r = new StringBuilder(256);
3771 } else {
3772 r.append(' ');
3773 }
3774 r.append(p.info.name);
3775 }
3776 }
3777 }
3778 if (r != null) {
3779 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3780 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 N = pkg.instrumentation.size();
3783 r = null;
3784 for (i=0; i<N; i++) {
3785 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003786 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003787 if (chatty) {
3788 if (r == null) {
3789 r = new StringBuilder(256);
3790 } else {
3791 r.append(' ');
3792 }
3793 r.append(a.info.name);
3794 }
3795 }
3796 if (r != null) {
3797 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3798 }
3799 }
3800 }
3801
3802 private static final boolean isPackageFilename(String name) {
3803 return name != null && name.endsWith(".apk");
3804 }
3805
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003806 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3807 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3808 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3809 return true;
3810 }
3811 }
3812 return false;
3813 }
3814
3815 private void updatePermissionsLP(String changingPkg,
3816 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 // Make sure there are no dangling permission trees.
3818 Iterator<BasePermission> it = mSettings.mPermissionTrees
3819 .values().iterator();
3820 while (it.hasNext()) {
3821 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003822 if (bp.packageSetting == null) {
3823 // We may not yet have parsed the package, so just see if
3824 // we still know about its settings.
3825 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3826 }
3827 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003828 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 + " from package " + bp.sourcePackage);
3830 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003831 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3832 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3833 Slog.i(TAG, "Removing old permission tree: " + bp.name
3834 + " from package " + bp.sourcePackage);
3835 grantPermissions = true;
3836 it.remove();
3837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 }
3839 }
3840
3841 // Make sure all dynamic permissions have been assigned to a package,
3842 // and make sure there are no dangling permissions.
3843 it = mSettings.mPermissions.values().iterator();
3844 while (it.hasNext()) {
3845 BasePermission bp = it.next();
3846 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3847 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3848 + bp.name + " pkg=" + bp.sourcePackage
3849 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003850 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 BasePermission tree = findPermissionTreeLP(bp.name);
3852 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003853 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 bp.perm = new PackageParser.Permission(tree.perm.owner,
3855 new PermissionInfo(bp.pendingInfo));
3856 bp.perm.info.packageName = tree.perm.info.packageName;
3857 bp.perm.info.name = bp.name;
3858 bp.uid = tree.uid;
3859 }
3860 }
3861 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003862 if (bp.packageSetting == null) {
3863 // We may not yet have parsed the package, so just see if
3864 // we still know about its settings.
3865 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3866 }
3867 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003868 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 + " from package " + bp.sourcePackage);
3870 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003871 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3872 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3873 Slog.i(TAG, "Removing old permission: " + bp.name
3874 + " from package " + bp.sourcePackage);
3875 grantPermissions = true;
3876 it.remove();
3877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 }
3879 }
3880
3881 // Now update the permissions for all packages, in particular
3882 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003883 if (grantPermissions) {
3884 for (PackageParser.Package pkg : mPackages.values()) {
3885 if (pkg != pkgInfo) {
3886 grantPermissionsLP(pkg, false);
3887 }
3888 }
3889 }
3890
3891 if (pkgInfo != null) {
3892 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 }
3894 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3897 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3898 if (ps == null) {
3899 return;
3900 }
3901 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003902 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 if (replace) {
3905 ps.permissionsFixed = false;
3906 if (gp == ps) {
3907 gp.grantedPermissions.clear();
3908 gp.gids = mGlobalGids;
3909 }
3910 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 if (gp.gids == null) {
3913 gp.gids = mGlobalGids;
3914 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 final int N = pkg.requestedPermissions.size();
3917 for (int i=0; i<N; i++) {
3918 String name = pkg.requestedPermissions.get(i);
3919 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 if (false) {
3921 if (gp != ps) {
3922 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003923 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 }
3925 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003926 if (bp != null && bp.packageSetting != null) {
3927 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003929 boolean allowedSig = false;
3930 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3931 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 allowed = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003933 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3934 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3935 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003937 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003939 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3941 // For updated system applications, the signatureOrSystem permission
3942 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003943 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3945 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3946 if(sysPs.grantedPermissions.contains(perm)) {
3947 allowed = true;
3948 } else {
3949 allowed = false;
3950 }
3951 } else {
3952 allowed = true;
3953 }
3954 }
3955 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003956 if (allowed) {
3957 allowedSig = true;
3958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 } else {
3960 allowed = false;
3961 }
3962 if (false) {
3963 if (gp != ps) {
3964 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3965 }
3966 }
3967 if (allowed) {
3968 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3969 && ps.permissionsFixed) {
3970 // If this is an existing, non-system package, then
3971 // we can't add any new permissions to it.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003972 if (!allowedSig && !gp.loadedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003974 // Except... if this is a permission that was added
3975 // to the platform (note: need to only do this when
3976 // updating the platform).
3977 final int NP = PackageParser.NEW_PERMISSIONS.length;
3978 for (int ip=0; ip<NP; ip++) {
3979 final PackageParser.NewPermissionInfo npi
3980 = PackageParser.NEW_PERMISSIONS[ip];
3981 if (npi.name.equals(perm)
3982 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3983 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003984 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003985 + pkg.packageName);
3986 break;
3987 }
3988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 }
3990 }
3991 if (allowed) {
3992 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003993 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994 gp.grantedPermissions.add(perm);
3995 gp.gids = appendInts(gp.gids, bp.gids);
3996 }
3997 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003998 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 + " to package " + pkg.packageName
4000 + " because it was previously installed without");
4001 }
4002 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004003 if (gp.grantedPermissions.remove(perm)) {
4004 changedPermission = true;
4005 gp.gids = removeInts(gp.gids, bp.gids);
4006 Slog.i(TAG, "Un-granting permission " + perm
4007 + " from package " + pkg.packageName
4008 + " (protectionLevel=" + bp.protectionLevel
4009 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4010 + ")");
4011 } else {
4012 Slog.w(TAG, "Not granting permission " + perm
4013 + " to package " + pkg.packageName
4014 + " (protectionLevel=" + bp.protectionLevel
4015 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4016 + ")");
4017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 }
4019 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004020 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 + " in package " + pkg.packageName);
4022 }
4023 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004024
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004025 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004026 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4027 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 // This is the first that we have heard about this package, so the
4029 // permissions we have now selected are fixed until explicitly
4030 // changed.
4031 ps.permissionsFixed = true;
4032 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
4033 }
4034 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 private final class ActivityIntentResolver
4037 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004038 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004040 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 }
4042
Mihai Preda074edef2009-05-18 17:13:31 +02004043 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004045 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4047 }
4048
Mihai Predaeae850c2009-05-13 10:13:48 +02004049 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4050 ArrayList<PackageParser.Activity> packageActivities) {
4051 if (packageActivities == null) {
4052 return null;
4053 }
4054 mFlags = flags;
4055 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4056 int N = packageActivities.size();
4057 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4058 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004059
4060 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004061 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004062 intentFilters = packageActivities.get(i).intents;
4063 if (intentFilters != null && intentFilters.size() > 0) {
4064 listCut.add(intentFilters);
4065 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004066 }
4067 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4068 }
4069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004071 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 if (SHOW_INFO || Config.LOGV) Log.v(
4073 TAG, " " + type + " " +
4074 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4075 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4076 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004077 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4079 if (SHOW_INFO || Config.LOGV) {
4080 Log.v(TAG, " IntentFilter:");
4081 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4082 }
4083 if (!intent.debugCheck()) {
4084 Log.w(TAG, "==> For Activity " + a.info.name);
4085 }
4086 addFilter(intent);
4087 }
4088 }
4089
4090 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004091 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 if (SHOW_INFO || Config.LOGV) Log.v(
4093 TAG, " " + type + " " +
4094 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4095 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4096 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004097 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4099 if (SHOW_INFO || Config.LOGV) {
4100 Log.v(TAG, " IntentFilter:");
4101 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4102 }
4103 removeFilter(intent);
4104 }
4105 }
4106
4107 @Override
4108 protected boolean allowFilterResult(
4109 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4110 ActivityInfo filterAi = filter.activity.info;
4111 for (int i=dest.size()-1; i>=0; i--) {
4112 ActivityInfo destAi = dest.get(i).activityInfo;
4113 if (destAi.name == filterAi.name
4114 && destAi.packageName == filterAi.packageName) {
4115 return false;
4116 }
4117 }
4118 return true;
4119 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004122 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4123 return info.activity.owner.packageName;
4124 }
4125
4126 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4128 int match) {
4129 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4130 return null;
4131 }
4132 final PackageParser.Activity activity = info.activity;
4133 if (mSafeMode && (activity.info.applicationInfo.flags
4134 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4135 return null;
4136 }
4137 final ResolveInfo res = new ResolveInfo();
4138 res.activityInfo = PackageParser.generateActivityInfo(activity,
4139 mFlags);
4140 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4141 res.filter = info;
4142 }
4143 res.priority = info.getPriority();
4144 res.preferredOrder = activity.owner.mPreferredOrder;
4145 //System.out.println("Result: " + res.activityInfo.className +
4146 // " = " + res.priority);
4147 res.match = match;
4148 res.isDefault = info.hasDefault;
4149 res.labelRes = info.labelRes;
4150 res.nonLocalizedLabel = info.nonLocalizedLabel;
4151 res.icon = info.icon;
4152 return res;
4153 }
4154
4155 @Override
4156 protected void sortResults(List<ResolveInfo> results) {
4157 Collections.sort(results, mResolvePrioritySorter);
4158 }
4159
4160 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004161 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004163 out.print(prefix); out.print(
4164 Integer.toHexString(System.identityHashCode(filter.activity)));
4165 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004166 out.print(filter.activity.getComponentShortName());
4167 out.print(" filter ");
4168 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 }
4170
4171// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4172// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4173// final List<ResolveInfo> retList = Lists.newArrayList();
4174// while (i.hasNext()) {
4175// final ResolveInfo resolveInfo = i.next();
4176// if (isEnabledLP(resolveInfo.activityInfo)) {
4177// retList.add(resolveInfo);
4178// }
4179// }
4180// return retList;
4181// }
4182
4183 // Keys are String (activity class name), values are Activity.
4184 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4185 = new HashMap<ComponentName, PackageParser.Activity>();
4186 private int mFlags;
4187 }
4188
4189 private final class ServiceIntentResolver
4190 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004191 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004193 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 }
4195
Mihai Preda074edef2009-05-18 17:13:31 +02004196 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004197 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004198 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4200 }
4201
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004202 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4203 ArrayList<PackageParser.Service> packageServices) {
4204 if (packageServices == null) {
4205 return null;
4206 }
4207 mFlags = flags;
4208 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4209 int N = packageServices.size();
4210 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4211 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4212
4213 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4214 for (int i = 0; i < N; ++i) {
4215 intentFilters = packageServices.get(i).intents;
4216 if (intentFilters != null && intentFilters.size() > 0) {
4217 listCut.add(intentFilters);
4218 }
4219 }
4220 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4221 }
4222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004224 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 if (SHOW_INFO || Config.LOGV) Log.v(
4226 TAG, " " + (s.info.nonLocalizedLabel != null
4227 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4228 if (SHOW_INFO || Config.LOGV) Log.v(
4229 TAG, " Class=" + s.info.name);
4230 int NI = s.intents.size();
4231 int j;
4232 for (j=0; j<NI; j++) {
4233 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4234 if (SHOW_INFO || Config.LOGV) {
4235 Log.v(TAG, " IntentFilter:");
4236 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4237 }
4238 if (!intent.debugCheck()) {
4239 Log.w(TAG, "==> For Service " + s.info.name);
4240 }
4241 addFilter(intent);
4242 }
4243 }
4244
4245 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004246 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 if (SHOW_INFO || Config.LOGV) Log.v(
4248 TAG, " " + (s.info.nonLocalizedLabel != null
4249 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4250 if (SHOW_INFO || Config.LOGV) Log.v(
4251 TAG, " Class=" + s.info.name);
4252 int NI = s.intents.size();
4253 int j;
4254 for (j=0; j<NI; j++) {
4255 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4256 if (SHOW_INFO || Config.LOGV) {
4257 Log.v(TAG, " IntentFilter:");
4258 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4259 }
4260 removeFilter(intent);
4261 }
4262 }
4263
4264 @Override
4265 protected boolean allowFilterResult(
4266 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4267 ServiceInfo filterSi = filter.service.info;
4268 for (int i=dest.size()-1; i>=0; i--) {
4269 ServiceInfo destAi = dest.get(i).serviceInfo;
4270 if (destAi.name == filterSi.name
4271 && destAi.packageName == filterSi.packageName) {
4272 return false;
4273 }
4274 }
4275 return true;
4276 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004279 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4280 return info.service.owner.packageName;
4281 }
4282
4283 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4285 int match) {
4286 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4287 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4288 return null;
4289 }
4290 final PackageParser.Service service = info.service;
4291 if (mSafeMode && (service.info.applicationInfo.flags
4292 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4293 return null;
4294 }
4295 final ResolveInfo res = new ResolveInfo();
4296 res.serviceInfo = PackageParser.generateServiceInfo(service,
4297 mFlags);
4298 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4299 res.filter = filter;
4300 }
4301 res.priority = info.getPriority();
4302 res.preferredOrder = service.owner.mPreferredOrder;
4303 //System.out.println("Result: " + res.activityInfo.className +
4304 // " = " + res.priority);
4305 res.match = match;
4306 res.isDefault = info.hasDefault;
4307 res.labelRes = info.labelRes;
4308 res.nonLocalizedLabel = info.nonLocalizedLabel;
4309 res.icon = info.icon;
4310 return res;
4311 }
4312
4313 @Override
4314 protected void sortResults(List<ResolveInfo> results) {
4315 Collections.sort(results, mResolvePrioritySorter);
4316 }
4317
4318 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004319 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004320 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004321 out.print(prefix); out.print(
4322 Integer.toHexString(System.identityHashCode(filter.service)));
4323 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004324 out.print(filter.service.getComponentShortName());
4325 out.print(" filter ");
4326 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 }
4328
4329// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4330// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4331// final List<ResolveInfo> retList = Lists.newArrayList();
4332// while (i.hasNext()) {
4333// final ResolveInfo resolveInfo = (ResolveInfo) i;
4334// if (isEnabledLP(resolveInfo.serviceInfo)) {
4335// retList.add(resolveInfo);
4336// }
4337// }
4338// return retList;
4339// }
4340
4341 // Keys are String (activity class name), values are Activity.
4342 private final HashMap<ComponentName, PackageParser.Service> mServices
4343 = new HashMap<ComponentName, PackageParser.Service>();
4344 private int mFlags;
4345 };
4346
4347 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4348 new Comparator<ResolveInfo>() {
4349 public int compare(ResolveInfo r1, ResolveInfo r2) {
4350 int v1 = r1.priority;
4351 int v2 = r2.priority;
4352 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4353 if (v1 != v2) {
4354 return (v1 > v2) ? -1 : 1;
4355 }
4356 v1 = r1.preferredOrder;
4357 v2 = r2.preferredOrder;
4358 if (v1 != v2) {
4359 return (v1 > v2) ? -1 : 1;
4360 }
4361 if (r1.isDefault != r2.isDefault) {
4362 return r1.isDefault ? -1 : 1;
4363 }
4364 v1 = r1.match;
4365 v2 = r2.match;
4366 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4367 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4368 }
4369 };
4370
4371 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4372 new Comparator<ProviderInfo>() {
4373 public int compare(ProviderInfo p1, ProviderInfo p2) {
4374 final int v1 = p1.initOrder;
4375 final int v2 = p2.initOrder;
4376 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4377 }
4378 };
4379
4380 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4381 IActivityManager am = ActivityManagerNative.getDefault();
4382 if (am != null) {
4383 try {
4384 final Intent intent = new Intent(action,
4385 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4386 if (extras != null) {
4387 intent.putExtras(extras);
4388 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004389 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 am.broadcastIntent(
4391 null, intent,
4392 null, null, 0, null, null, null, false, false);
4393 } catch (RemoteException ex) {
4394 }
4395 }
4396 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004397
4398 public String nextPackageToClean(String lastPackage) {
4399 synchronized (mPackages) {
4400 if (!mMediaMounted) {
4401 // If the external storage is no longer mounted at this point,
4402 // the caller may not have been able to delete all of this
4403 // packages files and can not delete any more. Bail.
4404 return null;
4405 }
4406 if (lastPackage != null) {
4407 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4408 }
4409 return mSettings.mPackagesToBeCleaned.size() > 0
4410 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4411 }
4412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004413
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004414 void schedulePackageCleaning(String packageName) {
4415 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4416 }
4417
4418 void startCleaningPackages() {
4419 synchronized (mPackages) {
4420 if (!mMediaMounted) {
4421 return;
4422 }
4423 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4424 return;
4425 }
4426 }
4427 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4428 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4429 IActivityManager am = ActivityManagerNative.getDefault();
4430 if (am != null) {
4431 try {
4432 am.startService(null, intent, null);
4433 } catch (RemoteException e) {
4434 }
4435 }
4436 }
4437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004438 private final class AppDirObserver extends FileObserver {
4439 public AppDirObserver(String path, int mask, boolean isrom) {
4440 super(path, mask);
4441 mRootDir = path;
4442 mIsRom = isrom;
4443 }
4444
4445 public void onEvent(int event, String path) {
4446 String removedPackage = null;
4447 int removedUid = -1;
4448 String addedPackage = null;
4449 int addedUid = -1;
4450
4451 synchronized (mInstallLock) {
4452 String fullPathStr = null;
4453 File fullPath = null;
4454 if (path != null) {
4455 fullPath = new File(mRootDir, path);
4456 fullPathStr = fullPath.getPath();
4457 }
4458
4459 if (Config.LOGV) Log.v(
4460 TAG, "File " + fullPathStr + " changed: "
4461 + Integer.toHexString(event));
4462
4463 if (!isPackageFilename(path)) {
4464 if (Config.LOGV) Log.v(
4465 TAG, "Ignoring change of non-package file: " + fullPathStr);
4466 return;
4467 }
4468
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004469 // Ignore packages that are being installed or
4470 // have just been installed.
4471 if (ignoreCodePath(fullPathStr)) {
4472 return;
4473 }
4474 PackageParser.Package p = null;
4475 synchronized (mPackages) {
4476 p = mAppDirs.get(fullPathStr);
4477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004478 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004479 if (p != null) {
4480 removePackageLI(p, true);
4481 removedPackage = p.applicationInfo.packageName;
4482 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004483 }
4484 }
4485
4486 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004488 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004489 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4490 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 PackageParser.PARSE_CHATTY |
4492 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004493 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004494 if (p != null) {
4495 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004496 updatePermissionsLP(p.packageName, p,
4497 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 }
4499 addedPackage = p.applicationInfo.packageName;
4500 addedUid = p.applicationInfo.uid;
4501 }
4502 }
4503 }
4504
4505 synchronized (mPackages) {
4506 mSettings.writeLP();
4507 }
4508 }
4509
4510 if (removedPackage != null) {
4511 Bundle extras = new Bundle(1);
4512 extras.putInt(Intent.EXTRA_UID, removedUid);
4513 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4514 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4515 }
4516 if (addedPackage != null) {
4517 Bundle extras = new Bundle(1);
4518 extras.putInt(Intent.EXTRA_UID, addedUid);
4519 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4520 }
4521 }
4522
4523 private final String mRootDir;
4524 private final boolean mIsRom;
4525 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 /* Called when a downloaded package installation has been confirmed by the user */
4528 public void installPackage(
4529 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004530 installPackage(packageURI, observer, flags, null);
4531 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004532
Jacek Surazski65e13172009-04-28 15:26:38 +02004533 /* Called when a downloaded package installation has been confirmed by the user */
4534 public void installPackage(
4535 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4536 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 mContext.enforceCallingOrSelfPermission(
4538 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004539
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004540 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004541 msg.obj = new InstallParams(packageURI, observer, flags,
4542 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004543 mHandler.sendMessage(msg);
4544 }
4545
Christopher Tate1bb69062010-02-19 17:02:12 -08004546 public void finishPackageInstall(int token) {
4547 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4548 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4549 mHandler.sendMessage(msg);
4550 }
4551
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004552 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004553 // Queue up an async operation since the package installation may take a little while.
4554 mHandler.post(new Runnable() {
4555 public void run() {
4556 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004557 // Result object to be returned
4558 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004559 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004560 res.uid = -1;
4561 res.pkg = null;
4562 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004563 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004564 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004565 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004566 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004567 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004568 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004569 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004570
4571 // A restore should be performed at this point if (a) the install
4572 // succeeded, (b) the operation is not an update, and (c) the new
4573 // package has a backupAgent defined.
4574 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004575 boolean doRestore = (!update
4576 && res.pkg != null
4577 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004578
4579 // Set up the post-install work request bookkeeping. This will be used
4580 // and cleaned up by the post-install event handling regardless of whether
4581 // there's a restore pass performed. Token values are >= 1.
4582 int token;
4583 if (mNextInstallToken < 0) mNextInstallToken = 1;
4584 token = mNextInstallToken++;
4585
4586 PostInstallData data = new PostInstallData(args, res);
4587 mRunningInstalls.put(token, data);
4588 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4589
4590 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4591 // Pass responsibility to the Backup Manager. It will perform a
4592 // restore if appropriate, then pass responsibility back to the
4593 // Package Manager to run the post-install observer callbacks
4594 // and broadcasts.
4595 IBackupManager bm = IBackupManager.Stub.asInterface(
4596 ServiceManager.getService(Context.BACKUP_SERVICE));
4597 if (bm != null) {
4598 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4599 + " to BM for possible restore");
4600 try {
4601 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4602 } catch (RemoteException e) {
4603 // can't happen; the backup manager is local
4604 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004605 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004606 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004607 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004608 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004609 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004610 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004613
4614 if (!doRestore) {
4615 // No restore possible, or the Backup Manager was mysteriously not
4616 // available -- just fire the post-install work request directly.
4617 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4618 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4619 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 }
4622 });
4623 }
4624
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004625 abstract class HandlerParams {
4626 final static int MAX_RETRIES = 4;
4627 int retry = 0;
4628 final void startCopy() {
4629 try {
4630 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4631 retry++;
4632 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004633 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004634 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4635 handleServiceError();
4636 return;
4637 } else {
4638 handleStartCopy();
4639 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4640 mHandler.sendEmptyMessage(MCS_UNBIND);
4641 }
4642 } catch (RemoteException e) {
4643 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4644 mHandler.sendEmptyMessage(MCS_RECONNECT);
4645 }
4646 handleReturnCode();
4647 }
4648
4649 final void serviceError() {
4650 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4651 handleServiceError();
4652 handleReturnCode();
4653 }
4654 abstract void handleStartCopy() throws RemoteException;
4655 abstract void handleServiceError();
4656 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004657 }
4658
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004659 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004660 final IPackageInstallObserver observer;
4661 int flags;
4662 final Uri packageURI;
4663 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004664 private InstallArgs mArgs;
4665 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004666 InstallParams(Uri packageURI,
4667 IPackageInstallObserver observer, int flags,
4668 String installerPackageName) {
4669 this.packageURI = packageURI;
4670 this.flags = flags;
4671 this.observer = observer;
4672 this.installerPackageName = installerPackageName;
4673 }
4674
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004675 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4676 String packageName = pkgLite.packageName;
4677 int installLocation = pkgLite.installLocation;
4678 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4679 synchronized (mPackages) {
4680 PackageParser.Package pkg = mPackages.get(packageName);
4681 if (pkg != null) {
4682 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4683 // Check for updated system application.
4684 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4685 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004686 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004687 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4688 }
4689 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4690 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004691 if (onSd) {
4692 // Install flag overrides everything.
4693 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4694 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004695 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004696 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4697 // Application explicitly specified internal.
4698 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4699 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4700 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004701 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004702 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004703 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4704 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4705 }
4706 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004707 }
4708 }
4709 } else {
4710 // Invalid install. Return error code
4711 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4712 }
4713 }
4714 }
4715 // All the special cases have been taken care of.
4716 // Return result based on recommended install location.
4717 if (onSd) {
4718 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4719 }
4720 return pkgLite.recommendedInstallLocation;
4721 }
4722
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004723 /*
4724 * Invoke remote method to get package information and install
4725 * location values. Override install location based on default
4726 * policy if needed and then create install arguments based
4727 * on the install location.
4728 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004729 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004730 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004731 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4732 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004733 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4734 if (onInt && onSd) {
4735 // Check if both bits are set.
4736 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4737 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4738 } else if (fwdLocked && onSd) {
4739 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004740 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004741 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004742 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004743 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004744 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004745 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004746 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4747 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4748 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4749 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4750 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004751 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4752 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4753 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004754 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4755 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004756 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004757 // Override with defaults if needed.
4758 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004759 if (!onSd && !onInt) {
4760 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004761 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4762 // Set the flag to install on external media.
4763 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004764 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004765 } else {
4766 // Make sure the flag for installing on external
4767 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004768 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004769 flags &= ~PackageManager.INSTALL_EXTERNAL;
4770 }
4771 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004772 }
4773 }
4774 // Create the file args now.
4775 mArgs = createInstallArgs(this);
4776 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4777 // Create copy only if we are not in an erroneous state.
4778 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004779 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004780 }
4781 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004782 }
4783
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004784 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004785 void handleReturnCode() {
4786 processPendingInstall(mArgs, mRet);
4787 }
4788
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004789 @Override
4790 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004791 mArgs = createInstallArgs(this);
4792 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004793 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004794 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004795
4796 /*
4797 * Utility class used in movePackage api.
4798 * srcArgs and targetArgs are not set for invalid flags and make
4799 * sure to do null checks when invoking methods on them.
4800 * We probably want to return ErrorPrams for both failed installs
4801 * and moves.
4802 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004803 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004804 final IPackageMoveObserver observer;
4805 final int flags;
4806 final String packageName;
4807 final InstallArgs srcArgs;
4808 final InstallArgs targetArgs;
4809 int mRet;
4810 MoveParams(InstallArgs srcArgs,
4811 IPackageMoveObserver observer,
4812 int flags, String packageName) {
4813 this.srcArgs = srcArgs;
4814 this.observer = observer;
4815 this.flags = flags;
4816 this.packageName = packageName;
4817 if (srcArgs != null) {
4818 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4819 targetArgs = createInstallArgs(packageUri, flags, packageName);
4820 } else {
4821 targetArgs = null;
4822 }
4823 }
4824
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004825 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004826 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4827 // Check for storage space on target medium
4828 if (!targetArgs.checkFreeStorage(mContainerService)) {
4829 Log.w(TAG, "Insufficient storage to install");
4830 return;
4831 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004832 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004833 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004834 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004835 if (DEBUG_SD_INSTALL) {
4836 StringBuilder builder = new StringBuilder();
4837 if (srcArgs != null) {
4838 builder.append("src: ");
4839 builder.append(srcArgs.getCodePath());
4840 }
4841 if (targetArgs != null) {
4842 builder.append(" target : ");
4843 builder.append(targetArgs.getCodePath());
4844 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004845 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004846 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004847 }
4848
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004849 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004850 void handleReturnCode() {
4851 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004852 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4853 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4854 currentStatus = PackageManager.MOVE_SUCCEEDED;
4855 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4856 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4857 }
4858 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004859 }
4860
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004861 @Override
4862 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004863 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004864 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004865 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004866
4867 private InstallArgs createInstallArgs(InstallParams params) {
4868 if (installOnSd(params.flags)) {
4869 return new SdInstallArgs(params);
4870 } else {
4871 return new FileInstallArgs(params);
4872 }
4873 }
4874
4875 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4876 if (installOnSd(flags)) {
4877 return new SdInstallArgs(fullCodePath, fullResourcePath);
4878 } else {
4879 return new FileInstallArgs(fullCodePath, fullResourcePath);
4880 }
4881 }
4882
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004883 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4884 if (installOnSd(flags)) {
4885 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4886 return new SdInstallArgs(packageURI, cid);
4887 } else {
4888 return new FileInstallArgs(packageURI, pkgName);
4889 }
4890 }
4891
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004892 static abstract class InstallArgs {
4893 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004894 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004895 final int flags;
4896 final Uri packageURI;
4897 final String installerPackageName;
4898
4899 InstallArgs(Uri packageURI,
4900 IPackageInstallObserver observer, int flags,
4901 String installerPackageName) {
4902 this.packageURI = packageURI;
4903 this.flags = flags;
4904 this.observer = observer;
4905 this.installerPackageName = installerPackageName;
4906 }
4907
4908 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004909 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004910 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004911 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004912 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004913 abstract String getCodePath();
4914 abstract String getResourcePath();
4915 // Need installer lock especially for dex file removal.
4916 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004917 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004918 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004919 }
4920
4921 class FileInstallArgs extends InstallArgs {
4922 File installDir;
4923 String codeFileName;
4924 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004925 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004926
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004927 FileInstallArgs(InstallParams params) {
4928 super(params.packageURI, params.observer,
4929 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004930 }
4931
4932 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4933 super(null, null, 0, null);
4934 File codeFile = new File(fullCodePath);
4935 installDir = codeFile.getParentFile();
4936 codeFileName = fullCodePath;
4937 resourceFileName = fullResourcePath;
4938 }
4939
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004940 FileInstallArgs(Uri packageURI, String pkgName) {
4941 super(packageURI, null, 0, null);
4942 boolean fwdLocked = isFwdLocked(flags);
4943 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4944 String apkName = getNextCodePath(null, pkgName, ".apk");
4945 codeFileName = new File(installDir, apkName + ".apk").getPath();
4946 resourceFileName = getResourcePathFromCodePath();
4947 }
4948
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004949 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4950 return imcs.checkFreeStorage(false, packageURI);
4951 }
4952
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004953 String getCodePath() {
4954 return codeFileName;
4955 }
4956
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004957 void createCopyFile() {
4958 boolean fwdLocked = isFwdLocked(flags);
4959 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4960 codeFileName = createTempPackageFile(installDir).getPath();
4961 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004962 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004963 }
4964
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004965 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004966 if (temp) {
4967 // Generate temp file name
4968 createCopyFile();
4969 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004970 // Get a ParcelFileDescriptor to write to the output file
4971 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004972 if (!created) {
4973 try {
4974 codeFile.createNewFile();
4975 // Set permissions
4976 if (!setPermissions()) {
4977 // Failed setting permissions.
4978 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4979 }
4980 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004981 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004982 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4983 }
4984 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004985 ParcelFileDescriptor out = null;
4986 try {
4987 out = ParcelFileDescriptor.open(codeFile,
4988 ParcelFileDescriptor.MODE_READ_WRITE);
4989 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004990 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004991 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4992 }
4993 // Copy the resource now
4994 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4995 try {
4996 if (imcs.copyResource(packageURI, out)) {
4997 ret = PackageManager.INSTALL_SUCCEEDED;
4998 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004999 } finally {
5000 try { if (out != null) out.close(); } catch (IOException e) {}
5001 }
5002 return ret;
5003 }
5004
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005005 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005006 if (status != PackageManager.INSTALL_SUCCEEDED) {
5007 cleanUp();
5008 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005009 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005010 }
5011
5012 boolean doRename(int status, final String pkgName, String oldCodePath) {
5013 if (status != PackageManager.INSTALL_SUCCEEDED) {
5014 cleanUp();
5015 return false;
5016 } else {
5017 // Rename based on packageName
5018 File codeFile = new File(getCodePath());
5019 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5020 File desFile = new File(installDir, apkName + ".apk");
5021 if (!codeFile.renameTo(desFile)) {
5022 return false;
5023 }
5024 // Reset paths since the file has been renamed.
5025 codeFileName = desFile.getPath();
5026 resourceFileName = getResourcePathFromCodePath();
5027 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005028 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005029 // Failed setting permissions.
5030 return false;
5031 }
5032 return true;
5033 }
5034 }
5035
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005036 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005037 if (status != PackageManager.INSTALL_SUCCEEDED) {
5038 cleanUp();
5039 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005040 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005041 }
5042
5043 String getResourcePath() {
5044 return resourceFileName;
5045 }
5046
5047 String getResourcePathFromCodePath() {
5048 String codePath = getCodePath();
5049 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5050 String apkNameOnly = getApkName(codePath);
5051 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5052 } else {
5053 return codePath;
5054 }
5055 }
5056
5057 private boolean cleanUp() {
5058 boolean ret = true;
5059 String sourceDir = getCodePath();
5060 String publicSourceDir = getResourcePath();
5061 if (sourceDir != null) {
5062 File sourceFile = new File(sourceDir);
5063 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005064 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005065 ret = false;
5066 }
5067 // Delete application's code and resources
5068 sourceFile.delete();
5069 }
5070 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5071 final File publicSourceFile = new File(publicSourceDir);
5072 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005073 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005074 }
5075 if (publicSourceFile.exists()) {
5076 publicSourceFile.delete();
5077 }
5078 }
5079 return ret;
5080 }
5081
5082 void cleanUpResourcesLI() {
5083 String sourceDir = getCodePath();
5084 if (cleanUp() && mInstaller != null) {
5085 int retCode = mInstaller.rmdex(sourceDir);
5086 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005087 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005088 + " at location "
5089 + sourceDir + ", retcode=" + retCode);
5090 // we don't consider this to be a failure of the core package deletion
5091 }
5092 }
5093 }
5094
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005095 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005096 // TODO Do this in a more elegant way later on. for now just a hack
5097 if (!isFwdLocked(flags)) {
5098 final int filePermissions =
5099 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5100 |FileUtils.S_IROTH;
5101 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5102 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005103 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005104 getCodePath()
5105 + ". The return code was: " + retCode);
5106 // TODO Define new internal error
5107 return false;
5108 }
5109 return true;
5110 }
5111 return true;
5112 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005113
5114 boolean doPostDeleteLI(boolean delete) {
5115 cleanUpResourcesLI();
5116 return true;
5117 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005118 }
5119
5120 class SdInstallArgs extends InstallArgs {
5121 String cid;
5122 String cachePath;
5123 static final String RES_FILE_NAME = "pkg.apk";
5124
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005125 SdInstallArgs(InstallParams params) {
5126 super(params.packageURI, params.observer,
5127 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005128 }
5129
5130 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005131 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005132 // Extract cid from fullCodePath
5133 int eidx = fullCodePath.lastIndexOf("/");
5134 String subStr1 = fullCodePath.substring(0, eidx);
5135 int sidx = subStr1.lastIndexOf("/");
5136 cid = subStr1.substring(sidx+1, eidx);
5137 cachePath = subStr1;
5138 }
5139
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005140 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005141 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5142 this.cid = cid;
5143 }
5144
5145 SdInstallArgs(Uri packageURI, String cid) {
5146 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005147 this.cid = cid;
5148 }
5149
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005150 void createCopyFile() {
5151 cid = getTempContainerId();
5152 }
5153
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005154 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5155 return imcs.checkFreeStorage(true, packageURI);
5156 }
5157
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005158 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005159 if (temp) {
5160 createCopyFile();
5161 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005162 cachePath = imcs.copyResourceToContainer(
5163 packageURI, cid,
5164 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005165 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5166 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005167 }
5168
5169 @Override
5170 String getCodePath() {
5171 return cachePath + "/" + RES_FILE_NAME;
5172 }
5173
5174 @Override
5175 String getResourcePath() {
5176 return cachePath + "/" + RES_FILE_NAME;
5177 }
5178
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005179 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005180 if (status != PackageManager.INSTALL_SUCCEEDED) {
5181 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005182 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005183 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005184 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005185 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005186 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005187 if (cachePath == null) {
5188 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5189 }
5190 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005191 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005192 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005193 }
5194
5195 boolean doRename(int status, final String pkgName,
5196 String oldCodePath) {
5197 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005198 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005199 if (PackageHelper.isContainerMounted(cid)) {
5200 // Unmount the container
5201 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005202 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005203 return false;
5204 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005205 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005206 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005207 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005208 return false;
5209 }
5210 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005211 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005212 newCachePath = PackageHelper.mountSdDir(newCacheId,
5213 getEncryptKey(), Process.SYSTEM_UID);
5214 } else {
5215 newCachePath = PackageHelper.getSdDir(newCacheId);
5216 }
5217 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005218 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005219 return false;
5220 }
5221 Log.i(TAG, "Succesfully renamed " + cid +
5222 " at path: " + cachePath + " to " + newCacheId +
5223 " at new path: " + newCachePath);
5224 cid = newCacheId;
5225 cachePath = newCachePath;
5226 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005227 }
5228
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005229 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005230 if (status != PackageManager.INSTALL_SUCCEEDED) {
5231 cleanUp();
5232 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005233 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005234 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005235 PackageHelper.mountSdDir(cid,
5236 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005237 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005238 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005239 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005240 }
5241
5242 private void cleanUp() {
5243 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005244 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005245 }
5246
5247 void cleanUpResourcesLI() {
5248 String sourceFile = getCodePath();
5249 // Remove dex file
5250 if (mInstaller != null) {
5251 int retCode = mInstaller.rmdex(sourceFile.toString());
5252 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005253 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005254 + " at location "
5255 + sourceFile.toString() + ", retcode=" + retCode);
5256 // we don't consider this to be a failure of the core package deletion
5257 }
5258 }
5259 cleanUp();
5260 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005261
5262 boolean matchContainer(String app) {
5263 if (cid.startsWith(app)) {
5264 return true;
5265 }
5266 return false;
5267 }
5268
5269 String getPackageName() {
5270 int idx = cid.lastIndexOf("-");
5271 if (idx == -1) {
5272 return cid;
5273 }
5274 return cid.substring(0, idx);
5275 }
5276
5277 boolean doPostDeleteLI(boolean delete) {
5278 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005279 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005280 if (mounted) {
5281 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005282 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005283 }
5284 if (ret && delete) {
5285 cleanUpResourcesLI();
5286 }
5287 return ret;
5288 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005289 };
5290
5291 // Utility method used to create code paths based on package name and available index.
5292 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5293 String idxStr = "";
5294 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005295 // Fall back to default value of idx=1 if prefix is not
5296 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005297 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005298 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005299 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005300 if (subStr.endsWith(suffix)) {
5301 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005302 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005303 // If oldCodePath already contains prefix find out the
5304 // ending index to either increment or decrement.
5305 int sidx = subStr.lastIndexOf(prefix);
5306 if (sidx != -1) {
5307 subStr = subStr.substring(sidx + prefix.length());
5308 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005309 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5310 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005311 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005312 try {
5313 idx = Integer.parseInt(subStr);
5314 if (idx <= 1) {
5315 idx++;
5316 } else {
5317 idx--;
5318 }
5319 } catch(NumberFormatException e) {
5320 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005321 }
5322 }
5323 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005324 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005325 return prefix + idxStr;
5326 }
5327
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005328 // Utility method used to ignore ADD/REMOVE events
5329 // by directory observer.
5330 private static boolean ignoreCodePath(String fullPathStr) {
5331 String apkName = getApkName(fullPathStr);
5332 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5333 if (idx != -1 && ((idx+1) < apkName.length())) {
5334 // Make sure the package ends with a numeral
5335 String version = apkName.substring(idx+1);
5336 try {
5337 Integer.parseInt(version);
5338 return true;
5339 } catch (NumberFormatException e) {}
5340 }
5341 return false;
5342 }
5343
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005344 // Utility method that returns the relative package path with respect
5345 // to the installation directory. Like say for /data/data/com.test-1.apk
5346 // string com.test-1 is returned.
5347 static String getApkName(String codePath) {
5348 if (codePath == null) {
5349 return null;
5350 }
5351 int sidx = codePath.lastIndexOf("/");
5352 int eidx = codePath.lastIndexOf(".");
5353 if (eidx == -1) {
5354 eidx = codePath.length();
5355 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005356 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005357 return null;
5358 }
5359 return codePath.substring(sidx+1, eidx);
5360 }
5361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 class PackageInstalledInfo {
5363 String name;
5364 int uid;
5365 PackageParser.Package pkg;
5366 int returnCode;
5367 PackageRemovedInfo removedInfo;
5368 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005370 /*
5371 * Install a non-existing package.
5372 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005373 private void installNewPackageLI(PackageParser.Package pkg,
5374 int parseFlags,
5375 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005376 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005377 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005378 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005379
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005380 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005381 res.name = pkgName;
5382 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005383 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005385 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 + " without first uninstalling.");
5387 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5388 return;
5389 }
5390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005391 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005392 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005393 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005394 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5396 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5397 }
5398 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005399 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005400 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005401 res);
5402 // delete the partially installed application. the data directory will have to be
5403 // restored if it was already existing
5404 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5405 // remove package from internal structures. Note that we want deletePackageX to
5406 // delete the package data and cache directories that it created in
5407 // scanPackageLocked, unless those directories existed before we even tried to
5408 // install.
5409 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005410 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005411 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5412 res.removedInfo);
5413 }
5414 }
5415 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005416
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005417 private void replacePackageLI(PackageParser.Package pkg,
5418 int parseFlags,
5419 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005420 String installerPackageName, PackageInstalledInfo res) {
5421
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005422 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005423 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424 // First find the old package info and check signatures
5425 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005426 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005427 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005428 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5430 return;
5431 }
5432 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005433 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005434 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005435 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005437 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438 }
5439 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005442 PackageParser.Package pkg,
5443 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005444 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 PackageParser.Package newPackage = null;
5446 String pkgName = deletedPackage.packageName;
5447 boolean deletedPkg = true;
5448 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005449
Jacek Surazski65e13172009-04-28 15:26:38 +02005450 String oldInstallerPackageName = null;
5451 synchronized (mPackages) {
5452 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005454
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005455 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005457 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005458 res.removedInfo)) {
5459 // If the existing package was'nt successfully deleted
5460 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5461 deletedPkg = false;
5462 } else {
5463 // Successfully deleted the old package. Now proceed with re-installation
5464 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005465 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005467 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5469 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005470 }
5471 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005472 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005473 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 res);
5475 updatedSettings = true;
5476 }
5477 }
5478
5479 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5480 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005481 // were keeping around in case we needed them (see below) can now be deleted.
5482 // This info will be set on the res.removedInfo to clean up later on as post
5483 // install action.
5484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005485 //update signature on the new package setting
5486 //this should always succeed, since we checked the
5487 //signature earlier.
5488 synchronized(mPackages) {
5489 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5490 parseFlags, true);
5491 }
5492 } else {
5493 // remove package from internal structures. Note that we want deletePackageX to
5494 // delete the package data and cache directories that it created in
5495 // scanPackageLocked, unless those directories existed before we even tried to
5496 // install.
5497 if(updatedSettings) {
5498 deletePackageLI(
5499 pkgName, true,
5500 PackageManager.DONT_DELETE_DATA,
5501 res.removedInfo);
5502 }
5503 // Since we failed to install the new package we need to restore the old
5504 // package that we deleted.
5505 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005506 File restoreFile = new File(deletedPackage.mPath);
5507 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005508 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005509 return;
5510 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005511 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5512 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005513 // Parse old package
5514 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5515 scanPackageLI(restoreFile, parseFlags, scanMode);
5516 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005517 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5518 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005519 mSettings.writeLP();
5520 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005521 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005522 Slog.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 }
5525 }
5526 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005529 PackageParser.Package pkg,
5530 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005531 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 PackageParser.Package newPackage = null;
5533 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005534 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 PackageParser.PARSE_IS_SYSTEM;
5536 String packageName = deletedPackage.packageName;
5537 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5538 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005539 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 return;
5541 }
5542 PackageParser.Package oldPkg;
5543 PackageSetting oldPkgSetting;
5544 synchronized (mPackages) {
5545 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005546 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005547 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5548 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005549 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550 return;
5551 }
5552 }
5553 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5554 res.removedInfo.removedPackage = packageName;
5555 // Remove existing system package
5556 removePackageLI(oldPkg, true);
5557 synchronized (mPackages) {
5558 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5559 }
5560
5561 // Successfully disabled the old package. Now proceed with re-installation
5562 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5563 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005564 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005566 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5568 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5569 }
5570 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005571 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572 updatedSettings = true;
5573 }
5574
5575 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5576 //update signature on the new package setting
5577 //this should always succeed, since we checked the
5578 //signature earlier.
5579 synchronized(mPackages) {
5580 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5581 parseFlags, true);
5582 }
5583 } else {
5584 // Re installation failed. Restore old information
5585 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005586 if (newPackage != null) {
5587 removePackageLI(newPackage, true);
5588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005590 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005591 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005592 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005593 // Restore the old system information in Settings
5594 synchronized(mPackages) {
5595 if(updatedSettings) {
5596 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005597 mSettings.setInstallerPackageName(packageName,
5598 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 }
5600 mSettings.writeLP();
5601 }
5602 }
5603 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005604
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005605 // Utility method used to move dex files during install.
5606 private int moveDexFiles(PackageParser.Package newPackage) {
5607 int retCode;
5608 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5609 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5610 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005611 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005612 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5613 }
5614 }
5615 return PackageManager.INSTALL_SUCCEEDED;
5616 }
5617
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005618 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005619 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005620 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 synchronized (mPackages) {
5622 //write settings. the installStatus will be incomplete at this stage.
5623 //note that the new package setting would have already been
5624 //added to mPackages. It hasn't been persisted yet.
5625 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5626 mSettings.writeLP();
5627 }
5628
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005629 if ((res.returnCode = moveDexFiles(newPackage))
5630 != PackageManager.INSTALL_SUCCEEDED) {
5631 // Discontinue if moving dex files failed.
5632 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005634 if((res.returnCode = setPermissionsLI(newPackage))
5635 != PackageManager.INSTALL_SUCCEEDED) {
5636 if (mInstaller != null) {
5637 mInstaller.rmdex(newPackage.mScanPath);
5638 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005639 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005641 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005644 updatePermissionsLP(newPackage.packageName, newPackage,
5645 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 res.name = pkgName;
5647 res.uid = newPackage.applicationInfo.uid;
5648 res.pkg = newPackage;
5649 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005650 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5652 //to update install status
5653 mSettings.writeLP();
5654 }
5655 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005656
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005657 private void installPackageLI(InstallArgs args,
5658 boolean newInstall, PackageInstalledInfo res) {
5659 int pFlags = args.flags;
5660 String installerPackageName = args.installerPackageName;
5661 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005662 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005663 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005664 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005665 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5666 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005667 // Result object to be returned
5668 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5669
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005670 // Retrieve PackageSettings and parse package
5671 int parseFlags = PackageParser.PARSE_CHATTY |
5672 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5673 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5674 parseFlags |= mDefParseFlags;
5675 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5676 pp.setSeparateProcesses(mSeparateProcesses);
5677 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5678 null, mMetrics, parseFlags);
5679 if (pkg == null) {
5680 res.returnCode = pp.getParseError();
5681 return;
5682 }
5683 String pkgName = res.name = pkg.packageName;
5684 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5685 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5686 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5687 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005689 }
5690 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5691 res.returnCode = pp.getParseError();
5692 return;
5693 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005694 // Get rid of all references to package scan path via parser.
5695 pp = null;
5696 String oldCodePath = null;
5697 boolean systemApp = false;
5698 synchronized (mPackages) {
5699 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005700 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5701 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005702 if (pkg.mOriginalPackages != null
5703 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005704 && mPackages.containsKey(oldName)) {
5705 // This package is derived from an original package,
5706 // and this device has been updating from that original
5707 // name. We must continue using the original name, so
5708 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005709 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005710 pkgName = pkg.packageName;
5711 replace = true;
5712 } else if (mPackages.containsKey(pkgName)) {
5713 // This package, under its official name, already exists
5714 // on the device; we should replace it.
5715 replace = true;
5716 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005717 }
5718 PackageSetting ps = mSettings.mPackages.get(pkgName);
5719 if (ps != null) {
5720 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5721 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5722 systemApp = (ps.pkg.applicationInfo.flags &
5723 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005724 }
5725 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005727
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005728 if (systemApp && onSd) {
5729 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005730 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005731 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5732 return;
5733 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005734
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005735 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5736 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5737 return;
5738 }
5739 // Set application objects path explicitly after the rename
5740 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005741 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005742 replacePackageLI(pkg, parseFlags, scanMode,
5743 installerPackageName, res);
5744 } else {
5745 installNewPackageLI(pkg, parseFlags, scanMode,
5746 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005747 }
5748 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005749
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005750 private int setPermissionsLI(PackageParser.Package newPackage) {
5751 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005752 int retCode = 0;
5753 // TODO Gross hack but fix later. Ideally move this to be a post installation
5754 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005755 if ((newPackage.applicationInfo.flags
5756 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5757 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758 try {
5759 extractPublicFiles(newPackage, destResourceFile);
5760 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005761 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 -08005762 " forward-locked app.");
5763 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5764 } finally {
5765 //TODO clean up the extracted public files
5766 }
5767 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005768 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 newPackage.applicationInfo.uid);
5770 } else {
5771 final int filePermissions =
5772 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005773 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005774 newPackage.applicationInfo.uid);
5775 }
5776 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005777 // The permissions on the resource file was set when it was copied for
5778 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005781 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005782 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005783 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005785 // TODO Define new internal error
5786 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 }
5788 return PackageManager.INSTALL_SUCCEEDED;
5789 }
5790
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005791 private boolean isForwardLocked(PackageParser.Package pkg) {
5792 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005793 }
5794
5795 private void extractPublicFiles(PackageParser.Package newPackage,
5796 File publicZipFile) throws IOException {
5797 final ZipOutputStream publicZipOutStream =
5798 new ZipOutputStream(new FileOutputStream(publicZipFile));
5799 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5800
5801 // Copy manifest, resources.arsc and res directory to public zip
5802
5803 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5804 while (privateZipEntries.hasMoreElements()) {
5805 final ZipEntry zipEntry = privateZipEntries.nextElement();
5806 final String zipEntryName = zipEntry.getName();
5807 if ("AndroidManifest.xml".equals(zipEntryName)
5808 || "resources.arsc".equals(zipEntryName)
5809 || zipEntryName.startsWith("res/")) {
5810 try {
5811 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5812 } catch (IOException e) {
5813 try {
5814 publicZipOutStream.close();
5815 throw e;
5816 } finally {
5817 publicZipFile.delete();
5818 }
5819 }
5820 }
5821 }
5822
5823 publicZipOutStream.close();
5824 FileUtils.setPermissions(
5825 publicZipFile.getAbsolutePath(),
5826 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5827 -1, -1);
5828 }
5829
5830 private static void copyZipEntry(ZipEntry zipEntry,
5831 ZipFile inZipFile,
5832 ZipOutputStream outZipStream) throws IOException {
5833 byte[] buffer = new byte[4096];
5834 int num;
5835
5836 ZipEntry newEntry;
5837 if (zipEntry.getMethod() == ZipEntry.STORED) {
5838 // Preserve the STORED method of the input entry.
5839 newEntry = new ZipEntry(zipEntry);
5840 } else {
5841 // Create a new entry so that the compressed len is recomputed.
5842 newEntry = new ZipEntry(zipEntry.getName());
5843 }
5844 outZipStream.putNextEntry(newEntry);
5845
5846 InputStream data = inZipFile.getInputStream(zipEntry);
5847 while ((num = data.read(buffer)) > 0) {
5848 outZipStream.write(buffer, 0, num);
5849 }
5850 outZipStream.flush();
5851 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 private void deleteTempPackageFiles() {
5854 FilenameFilter filter = new FilenameFilter() {
5855 public boolean accept(File dir, String name) {
5856 return name.startsWith("vmdl") && name.endsWith(".tmp");
5857 }
5858 };
5859 String tmpFilesList[] = mAppInstallDir.list(filter);
5860 if(tmpFilesList == null) {
5861 return;
5862 }
5863 for(int i = 0; i < tmpFilesList.length; i++) {
5864 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5865 tmpFile.delete();
5866 }
5867 }
5868
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005869 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005870 File tmpPackageFile;
5871 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005872 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005874 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 return null;
5876 }
5877 try {
5878 FileUtils.setPermissions(
5879 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5880 -1, -1);
5881 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005882 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883 return null;
5884 }
5885 return tmpPackageFile;
5886 }
5887
5888 public void deletePackage(final String packageName,
5889 final IPackageDeleteObserver observer,
5890 final int flags) {
5891 mContext.enforceCallingOrSelfPermission(
5892 android.Manifest.permission.DELETE_PACKAGES, null);
5893 // Queue up an async operation since the package deletion may take a little while.
5894 mHandler.post(new Runnable() {
5895 public void run() {
5896 mHandler.removeCallbacks(this);
5897 final boolean succeded = deletePackageX(packageName, true, true, flags);
5898 if (observer != null) {
5899 try {
5900 observer.packageDeleted(succeded);
5901 } catch (RemoteException e) {
5902 Log.i(TAG, "Observer no longer exists.");
5903 } //end catch
5904 } //end if
5905 } //end run
5906 });
5907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005909 /**
5910 * This method is an internal method that could be get invoked either
5911 * to delete an installed package or to clean up a failed installation.
5912 * After deleting an installed package, a broadcast is sent to notify any
5913 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005914 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005915 * installation wouldn't have sent the initial broadcast either
5916 * The key steps in deleting a package are
5917 * deleting the package information in internal structures like mPackages,
5918 * deleting the packages base directories through installd
5919 * updating mSettings to reflect current status
5920 * persisting settings for later use
5921 * sending a broadcast if necessary
5922 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5924 boolean deleteCodeAndResources, int flags) {
5925 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005926 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005927
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005928 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5929 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5930 try {
5931 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005932 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005933 return false;
5934 }
5935 } catch (RemoteException e) {
5936 }
5937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005938 synchronized (mInstallLock) {
5939 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5940 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005943 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5944 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5945
5946 // If the removed package was a system update, the old system packaged
5947 // was re-enabled; we need to broadcast this information
5948 if (systemUpdate) {
5949 Bundle extras = new Bundle(1);
5950 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5951 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5952
5953 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5954 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005956 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005957 // Force a gc here.
5958 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005959 // Delete the resources here after sending the broadcast to let
5960 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005961 if (info.args != null) {
5962 synchronized (mInstallLock) {
5963 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005964 }
5965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 return res;
5967 }
5968
5969 static class PackageRemovedInfo {
5970 String removedPackage;
5971 int uid = -1;
5972 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005973 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005974 // Clean up resources deleted packages.
5975 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005977 void sendBroadcast(boolean fullRemove, boolean replacing) {
5978 Bundle extras = new Bundle(1);
5979 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5980 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5981 if (replacing) {
5982 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5983 }
5984 if (removedPackage != null) {
5985 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5986 }
5987 if (removedUid >= 0) {
5988 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5989 }
5990 }
5991 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 /*
5994 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5995 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005996 * 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 -08005997 * delete a partially installed application.
5998 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005999 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006000 int flags) {
6001 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006002 if (outInfo != null) {
6003 outInfo.removedPackage = packageName;
6004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006005 removePackageLI(p, true);
6006 // Retrieve object to delete permissions for shared user later on
6007 PackageSetting deletedPs;
6008 synchronized (mPackages) {
6009 deletedPs = mSettings.mPackages.get(packageName);
6010 }
6011 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006012 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006014 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006016 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006017 + packageName + ", retcode=" + retCode);
6018 // we don't consider this to be a failure of the core package deletion
6019 }
6020 } else {
6021 //for emulator
6022 PackageParser.Package pkg = mPackages.get(packageName);
6023 File dataDir = new File(pkg.applicationInfo.dataDir);
6024 dataDir.delete();
6025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 }
6027 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006028 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006029 schedulePackageCleaning(packageName);
6030
6031 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6032 if (outInfo != null) {
6033 outInfo.removedUid = mSettings.removePackageLP(packageName);
6034 }
6035 if (deletedPs != null) {
6036 updatePermissionsLP(deletedPs.name, null, false, false);
6037 if (deletedPs.sharedUser != null) {
6038 // remove permissions associated with package
6039 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6040 }
6041 }
6042 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006043 // remove from preferred activities.
6044 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6045 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6046 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6047 removed.add(pa);
6048 }
6049 }
6050 for (PreferredActivity pa : removed) {
6051 mSettings.mPreferredActivities.removeFilter(pa);
6052 }
6053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006054 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006055 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 }
6057 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 /*
6060 * Tries to delete system package.
6061 */
6062 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006063 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 ApplicationInfo applicationInfo = p.applicationInfo;
6065 //applicable for non-partially installed applications only
6066 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006067 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006068 return false;
6069 }
6070 PackageSetting ps = null;
6071 // Confirm if the system package has been updated
6072 // An updated system app can be deleted. This will also have to restore
6073 // the system pkg from system partition
6074 synchronized (mPackages) {
6075 ps = mSettings.getDisabledSystemPkg(p.packageName);
6076 }
6077 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006078 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 return false;
6080 } else {
6081 Log.i(TAG, "Deleting system pkg from data partition");
6082 }
6083 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006084 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006085 boolean deleteCodeAndResources = false;
6086 if (ps.versionCode < p.mVersionCode) {
6087 // Delete code and resources for downgrades
6088 deleteCodeAndResources = true;
6089 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6090 flags &= ~PackageManager.DONT_DELETE_DATA;
6091 }
6092 } else {
6093 // Preserve data by setting flag
6094 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6095 flags |= PackageManager.DONT_DELETE_DATA;
6096 }
6097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006098 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6099 if (!ret) {
6100 return false;
6101 }
6102 synchronized (mPackages) {
6103 // Reinstate the old system package
6104 mSettings.enableSystemPackageLP(p.packageName);
6105 }
6106 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006107 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006108 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006109 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006112 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 return false;
6114 }
6115 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006116 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 mSettings.writeLP();
6118 }
6119 return true;
6120 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6123 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6124 ApplicationInfo applicationInfo = p.applicationInfo;
6125 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006126 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 return false;
6128 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006129 if (outInfo != null) {
6130 outInfo.uid = applicationInfo.uid;
6131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132
6133 // Delete package data from internal structures and also remove data if flag is set
6134 removePackageDataLI(p, outInfo, flags);
6135
6136 // Delete application code and resources
6137 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006138 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006139 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006140 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006141 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6142 PackageManager.INSTALL_FORWARD_LOCK : 0;
6143 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006144 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 }
6146 return true;
6147 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 /*
6150 * This method handles package deletion in general
6151 */
6152 private boolean deletePackageLI(String packageName,
6153 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6154 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006155 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 return false;
6157 }
6158 PackageParser.Package p;
6159 boolean dataOnly = false;
6160 synchronized (mPackages) {
6161 p = mPackages.get(packageName);
6162 if (p == null) {
6163 //this retrieves partially installed apps
6164 dataOnly = true;
6165 PackageSetting ps = mSettings.mPackages.get(packageName);
6166 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006167 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006168 return false;
6169 }
6170 p = ps.pkg;
6171 }
6172 }
6173 if (p == 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 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 if (dataOnly) {
6179 // Delete application data first
6180 removePackageDataLI(p, outInfo, flags);
6181 return true;
6182 }
6183 // At this point the package should have ApplicationInfo associated with it
6184 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006185 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 return false;
6187 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006188 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6190 Log.i(TAG, "Removing system package:"+p.packageName);
6191 // When an updated system application is deleted we delete the existing resources as well and
6192 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006193 ret = deleteSystemPackageLI(p, flags, outInfo);
6194 } else {
6195 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006196 // Kill application pre-emptively especially for apps on sd.
6197 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006198 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006200 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 public void clearApplicationUserData(final String packageName,
6204 final IPackageDataObserver observer) {
6205 mContext.enforceCallingOrSelfPermission(
6206 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6207 // Queue up an async operation since the package deletion may take a little while.
6208 mHandler.post(new Runnable() {
6209 public void run() {
6210 mHandler.removeCallbacks(this);
6211 final boolean succeeded;
6212 synchronized (mInstallLock) {
6213 succeeded = clearApplicationUserDataLI(packageName);
6214 }
6215 if (succeeded) {
6216 // invoke DeviceStorageMonitor's update method to clear any notifications
6217 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6218 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6219 if (dsm != null) {
6220 dsm.updateMemory();
6221 }
6222 }
6223 if(observer != null) {
6224 try {
6225 observer.onRemoveCompleted(packageName, succeeded);
6226 } catch (RemoteException e) {
6227 Log.i(TAG, "Observer no longer exists.");
6228 }
6229 } //end if observer
6230 } //end run
6231 });
6232 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 private boolean clearApplicationUserDataLI(String packageName) {
6235 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006236 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 return false;
6238 }
6239 PackageParser.Package p;
6240 boolean dataOnly = false;
6241 synchronized (mPackages) {
6242 p = mPackages.get(packageName);
6243 if(p == null) {
6244 dataOnly = true;
6245 PackageSetting ps = mSettings.mPackages.get(packageName);
6246 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006247 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 return false;
6249 }
6250 p = ps.pkg;
6251 }
6252 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006253 boolean useEncryptedFSDir = false;
6254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 if(!dataOnly) {
6256 //need to check this only for fully installed applications
6257 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006258 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 return false;
6260 }
6261 final ApplicationInfo applicationInfo = p.applicationInfo;
6262 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006263 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 return false;
6265 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006266 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 }
6268 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006269 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006270 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006271 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 + packageName);
6273 return false;
6274 }
6275 }
6276 return true;
6277 }
6278
6279 public void deleteApplicationCacheFiles(final String packageName,
6280 final IPackageDataObserver observer) {
6281 mContext.enforceCallingOrSelfPermission(
6282 android.Manifest.permission.DELETE_CACHE_FILES, null);
6283 // Queue up an async operation since the package deletion may take a little while.
6284 mHandler.post(new Runnable() {
6285 public void run() {
6286 mHandler.removeCallbacks(this);
6287 final boolean succeded;
6288 synchronized (mInstallLock) {
6289 succeded = deleteApplicationCacheFilesLI(packageName);
6290 }
6291 if(observer != null) {
6292 try {
6293 observer.onRemoveCompleted(packageName, succeded);
6294 } catch (RemoteException e) {
6295 Log.i(TAG, "Observer no longer exists.");
6296 }
6297 } //end if observer
6298 } //end run
6299 });
6300 }
6301
6302 private boolean deleteApplicationCacheFilesLI(String packageName) {
6303 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006304 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 return false;
6306 }
6307 PackageParser.Package p;
6308 synchronized (mPackages) {
6309 p = mPackages.get(packageName);
6310 }
6311 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006312 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 return false;
6314 }
6315 final ApplicationInfo applicationInfo = p.applicationInfo;
6316 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006317 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 return false;
6319 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006320 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006322 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006324 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 + packageName);
6326 return false;
6327 }
6328 }
6329 return true;
6330 }
6331
6332 public void getPackageSizeInfo(final String packageName,
6333 final IPackageStatsObserver observer) {
6334 mContext.enforceCallingOrSelfPermission(
6335 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6336 // Queue up an async operation since the package deletion may take a little while.
6337 mHandler.post(new Runnable() {
6338 public void run() {
6339 mHandler.removeCallbacks(this);
6340 PackageStats lStats = new PackageStats(packageName);
6341 final boolean succeded;
6342 synchronized (mInstallLock) {
6343 succeded = getPackageSizeInfoLI(packageName, lStats);
6344 }
6345 if(observer != null) {
6346 try {
6347 observer.onGetStatsCompleted(lStats, succeded);
6348 } catch (RemoteException e) {
6349 Log.i(TAG, "Observer no longer exists.");
6350 }
6351 } //end if observer
6352 } //end run
6353 });
6354 }
6355
6356 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6357 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006358 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 return false;
6360 }
6361 PackageParser.Package p;
6362 boolean dataOnly = false;
6363 synchronized (mPackages) {
6364 p = mPackages.get(packageName);
6365 if(p == null) {
6366 dataOnly = true;
6367 PackageSetting ps = mSettings.mPackages.get(packageName);
6368 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006369 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 return false;
6371 }
6372 p = ps.pkg;
6373 }
6374 }
6375 String publicSrcDir = null;
6376 if(!dataOnly) {
6377 final ApplicationInfo applicationInfo = p.applicationInfo;
6378 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006379 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 return false;
6381 }
6382 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6383 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006384 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 if (mInstaller != null) {
6386 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006387 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006388 if (res < 0) {
6389 return false;
6390 } else {
6391 return true;
6392 }
6393 }
6394 return true;
6395 }
6396
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 public void addPackageToPreferred(String packageName) {
6399 mContext.enforceCallingOrSelfPermission(
6400 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006401 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 }
6403
6404 public void removePackageFromPreferred(String packageName) {
6405 mContext.enforceCallingOrSelfPermission(
6406 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006407 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 }
6409
6410 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006411 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 }
6413
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006414 int getUidTargetSdkVersionLockedLP(int uid) {
6415 Object obj = mSettings.getUserIdLP(uid);
6416 if (obj instanceof SharedUserSetting) {
6417 SharedUserSetting sus = (SharedUserSetting)obj;
6418 final int N = sus.packages.size();
6419 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6420 Iterator<PackageSetting> it = sus.packages.iterator();
6421 int i=0;
6422 while (it.hasNext()) {
6423 PackageSetting ps = it.next();
6424 if (ps.pkg != null) {
6425 int v = ps.pkg.applicationInfo.targetSdkVersion;
6426 if (v < vers) vers = v;
6427 }
6428 }
6429 return vers;
6430 } else if (obj instanceof PackageSetting) {
6431 PackageSetting ps = (PackageSetting)obj;
6432 if (ps.pkg != null) {
6433 return ps.pkg.applicationInfo.targetSdkVersion;
6434 }
6435 }
6436 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6437 }
6438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 public void addPreferredActivity(IntentFilter filter, int match,
6440 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006442 if (mContext.checkCallingOrSelfPermission(
6443 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6444 != PackageManager.PERMISSION_GRANTED) {
6445 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6446 < Build.VERSION_CODES.FROYO) {
6447 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6448 + Binder.getCallingUid());
6449 return;
6450 }
6451 mContext.enforceCallingOrSelfPermission(
6452 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6453 }
6454
6455 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6457 mSettings.mPreferredActivities.addFilter(
6458 new PreferredActivity(filter, match, set, activity));
6459 mSettings.writeLP();
6460 }
6461 }
6462
Satish Sampath8dbe6122009-06-02 23:35:54 +01006463 public void replacePreferredActivity(IntentFilter filter, int match,
6464 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006465 if (filter.countActions() != 1) {
6466 throw new IllegalArgumentException(
6467 "replacePreferredActivity expects filter to have only 1 action.");
6468 }
6469 if (filter.countCategories() != 1) {
6470 throw new IllegalArgumentException(
6471 "replacePreferredActivity expects filter to have only 1 category.");
6472 }
6473 if (filter.countDataAuthorities() != 0
6474 || filter.countDataPaths() != 0
6475 || filter.countDataSchemes() != 0
6476 || filter.countDataTypes() != 0) {
6477 throw new IllegalArgumentException(
6478 "replacePreferredActivity expects filter to have no data authorities, " +
6479 "paths, schemes or types.");
6480 }
6481 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006482 if (mContext.checkCallingOrSelfPermission(
6483 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6484 != PackageManager.PERMISSION_GRANTED) {
6485 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6486 < Build.VERSION_CODES.FROYO) {
6487 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6488 + Binder.getCallingUid());
6489 return;
6490 }
6491 mContext.enforceCallingOrSelfPermission(
6492 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6493 }
6494
Satish Sampath8dbe6122009-06-02 23:35:54 +01006495 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6496 String action = filter.getAction(0);
6497 String category = filter.getCategory(0);
6498 while (it.hasNext()) {
6499 PreferredActivity pa = it.next();
6500 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6501 it.remove();
6502 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6503 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6504 }
6505 }
6506 addPreferredActivity(filter, match, set, activity);
6507 }
6508 }
6509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006510 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006512 int uid = Binder.getCallingUid();
6513 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006514 if (pkg == null || pkg.applicationInfo.uid != uid) {
6515 if (mContext.checkCallingOrSelfPermission(
6516 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6517 != PackageManager.PERMISSION_GRANTED) {
6518 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6519 < Build.VERSION_CODES.FROYO) {
6520 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6521 + Binder.getCallingUid());
6522 return;
6523 }
6524 mContext.enforceCallingOrSelfPermission(
6525 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6526 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006527 }
6528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 if (clearPackagePreferredActivitiesLP(packageName)) {
6530 mSettings.writeLP();
6531 }
6532 }
6533 }
6534
6535 boolean clearPackagePreferredActivitiesLP(String packageName) {
6536 boolean changed = false;
6537 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6538 while (it.hasNext()) {
6539 PreferredActivity pa = it.next();
6540 if (pa.mActivity.getPackageName().equals(packageName)) {
6541 it.remove();
6542 changed = true;
6543 }
6544 }
6545 return changed;
6546 }
6547
6548 public int getPreferredActivities(List<IntentFilter> outFilters,
6549 List<ComponentName> outActivities, String packageName) {
6550
6551 int num = 0;
6552 synchronized (mPackages) {
6553 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6554 while (it.hasNext()) {
6555 PreferredActivity pa = it.next();
6556 if (packageName == null
6557 || pa.mActivity.getPackageName().equals(packageName)) {
6558 if (outFilters != null) {
6559 outFilters.add(new IntentFilter(pa));
6560 }
6561 if (outActivities != null) {
6562 outActivities.add(pa.mActivity);
6563 }
6564 }
6565 }
6566 }
6567
6568 return num;
6569 }
6570
6571 public void setApplicationEnabledSetting(String appPackageName,
6572 int newState, int flags) {
6573 setEnabledSetting(appPackageName, null, newState, flags);
6574 }
6575
6576 public void setComponentEnabledSetting(ComponentName componentName,
6577 int newState, int flags) {
6578 setEnabledSetting(componentName.getPackageName(),
6579 componentName.getClassName(), newState, flags);
6580 }
6581
6582 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006583 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6585 || newState == COMPONENT_ENABLED_STATE_ENABLED
6586 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6587 throw new IllegalArgumentException("Invalid new component state: "
6588 + newState);
6589 }
6590 PackageSetting pkgSetting;
6591 final int uid = Binder.getCallingUid();
6592 final int permission = mContext.checkCallingPermission(
6593 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6594 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006595 boolean sendNow = false;
6596 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006597 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006599 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006600 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006601 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006603 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006605 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 }
6607 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006608 "Unknown component: " + packageName
6609 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 }
6611 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6612 throw new SecurityException(
6613 "Permission Denial: attempt to change component state from pid="
6614 + Binder.getCallingPid()
6615 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6616 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006617 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 // We're dealing with an application/package level state change
6619 pkgSetting.enabled = newState;
6620 } else {
6621 // We're dealing with a component level state change
6622 switch (newState) {
6623 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006624 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006625 break;
6626 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006627 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 break;
6629 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006630 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 break;
6632 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006633 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006634 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 }
6636 }
6637 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006638 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006639 components = mPendingBroadcasts.get(packageName);
6640 boolean newPackage = components == null;
6641 if (newPackage) {
6642 components = new ArrayList<String>();
6643 }
6644 if (!components.contains(componentName)) {
6645 components.add(componentName);
6646 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006647 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6648 sendNow = true;
6649 // Purge entry from pending broadcast list if another one exists already
6650 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006651 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006652 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006653 if (newPackage) {
6654 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006655 }
6656 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6657 // Schedule a message
6658 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6659 }
6660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 long callingId = Binder.clearCallingIdentity();
6664 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006665 if (sendNow) {
6666 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006667 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 } finally {
6670 Binder.restoreCallingIdentity(callingId);
6671 }
6672 }
6673
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006674 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006675 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6676 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6677 + " components=" + componentNames);
6678 Bundle extras = new Bundle(4);
6679 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6680 String nameList[] = new String[componentNames.size()];
6681 componentNames.toArray(nameList);
6682 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006683 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6684 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006685 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006686 }
6687
Jacek Surazski65e13172009-04-28 15:26:38 +02006688 public String getInstallerPackageName(String packageName) {
6689 synchronized (mPackages) {
6690 PackageSetting pkg = mSettings.mPackages.get(packageName);
6691 if (pkg == null) {
6692 throw new IllegalArgumentException("Unknown package: " + packageName);
6693 }
6694 return pkg.installerPackageName;
6695 }
6696 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006698 public int getApplicationEnabledSetting(String appPackageName) {
6699 synchronized (mPackages) {
6700 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6701 if (pkg == null) {
6702 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6703 }
6704 return pkg.enabled;
6705 }
6706 }
6707
6708 public int getComponentEnabledSetting(ComponentName componentName) {
6709 synchronized (mPackages) {
6710 final String packageNameStr = componentName.getPackageName();
6711 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6712 if (pkg == null) {
6713 throw new IllegalArgumentException("Unknown component: " + componentName);
6714 }
6715 final String classNameStr = componentName.getClassName();
6716 return pkg.currentEnabledStateLP(classNameStr);
6717 }
6718 }
6719
6720 public void enterSafeMode() {
6721 if (!mSystemReady) {
6722 mSafeMode = true;
6723 }
6724 }
6725
6726 public void systemReady() {
6727 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006728
6729 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006730 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006731 mContext.getContentResolver(),
6732 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006733 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006734 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006735 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 }
6738
6739 public boolean isSafeMode() {
6740 return mSafeMode;
6741 }
6742
6743 public boolean hasSystemUidErrors() {
6744 return mHasSystemUidErrors;
6745 }
6746
6747 static String arrayToString(int[] array) {
6748 StringBuffer buf = new StringBuffer(128);
6749 buf.append('[');
6750 if (array != null) {
6751 for (int i=0; i<array.length; i++) {
6752 if (i > 0) buf.append(", ");
6753 buf.append(array[i]);
6754 }
6755 }
6756 buf.append(']');
6757 return buf.toString();
6758 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 @Override
6761 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6762 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6763 != PackageManager.PERMISSION_GRANTED) {
6764 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6765 + Binder.getCallingPid()
6766 + ", uid=" + Binder.getCallingUid()
6767 + " without permission "
6768 + android.Manifest.permission.DUMP);
6769 return;
6770 }
6771
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006772 String packageName = null;
6773
6774 int opti = 0;
6775 while (opti < args.length) {
6776 String opt = args[opti];
6777 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6778 break;
6779 }
6780 opti++;
6781 if ("-a".equals(opt)) {
6782 // Right now we only know how to print all.
6783 } else if ("-h".equals(opt)) {
6784 pw.println("Package manager dump options:");
6785 pw.println(" [-h] [cmd] ...");
6786 pw.println(" cmd may be one of:");
6787 pw.println(" [package.name]: info about given package");
6788 return;
6789 } else {
6790 pw.println("Unknown argument: " + opt + "; use -h for help");
6791 }
6792 }
6793
6794 // Is the caller requesting to dump a particular piece of data?
6795 if (opti < args.length) {
6796 String cmd = args[opti];
6797 opti++;
6798 // Is this a package name?
6799 if ("android".equals(cmd) || cmd.contains(".")) {
6800 packageName = cmd;
6801 }
6802 }
6803
6804 boolean printedTitle = false;
6805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006806 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006807 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6808 printedTitle = true;
6809 }
6810 if (mReceivers.dump(pw, printedTitle
6811 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6812 " ", packageName)) {
6813 printedTitle = true;
6814 }
6815 if (mServices.dump(pw, printedTitle
6816 ? "\nService Resolver Table:" : "Service Resolver Table:",
6817 " ", packageName)) {
6818 printedTitle = true;
6819 }
6820 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6821 ? "\nPreferred Activities:" : "Preferred Activities:",
6822 " ", packageName)) {
6823 printedTitle = true;
6824 }
6825 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006826 {
6827 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006828 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6829 continue;
6830 }
6831 if (!printedSomething) {
6832 if (printedTitle) pw.println(" ");
6833 pw.println("Permissions:");
6834 printedSomething = true;
6835 printedTitle = true;
6836 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006837 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6838 pw.print(Integer.toHexString(System.identityHashCode(p)));
6839 pw.println("):");
6840 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6841 pw.print(" uid="); pw.print(p.uid);
6842 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006843 pw.print(" type="); pw.print(p.type);
6844 pw.print(" prot="); pw.println(p.protectionLevel);
6845 if (p.packageSetting != null) {
6846 pw.print(" packageSetting="); pw.println(p.packageSetting);
6847 }
6848 if (p.perm != null) {
6849 pw.print(" perm="); pw.println(p.perm);
6850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006851 }
6852 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006853 printedSomething = false;
6854 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006855 {
6856 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006857 if (packageName != null && !packageName.equals(ps.realName)
6858 && !packageName.equals(ps.name)) {
6859 continue;
6860 }
6861 if (!printedSomething) {
6862 if (printedTitle) pw.println(" ");
6863 pw.println("Packages:");
6864 printedSomething = true;
6865 printedTitle = true;
6866 }
6867 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006868 pw.print(" Package [");
6869 pw.print(ps.realName != null ? ps.realName : ps.name);
6870 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006871 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6872 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006873 if (ps.realName != null) {
6874 pw.print(" compat name="); pw.println(ps.name);
6875 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006876 pw.print(" userId="); pw.print(ps.userId);
6877 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6878 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6879 pw.print(" pkg="); pw.println(ps.pkg);
6880 pw.print(" codePath="); pw.println(ps.codePathString);
6881 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006882 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006883 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006884 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006885 pw.print(" supportsScreens=[");
6886 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006887 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006888 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006889 if (!first) pw.print(", ");
6890 first = false;
6891 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006893 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006894 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006895 if (!first) pw.print(", ");
6896 first = false;
6897 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006899 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006900 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006901 if (!first) pw.print(", ");
6902 first = false;
6903 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006904 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006905 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006906 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006907 if (!first) pw.print(", ");
6908 first = false;
6909 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006910 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006911 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006912 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6913 if (!first) pw.print(", ");
6914 first = false;
6915 pw.print("anyDensity");
6916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006917 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006918 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006919 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6920 pw.print(" signatures="); pw.println(ps.signatures);
6921 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6922 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6923 pw.print(" installStatus="); pw.print(ps.installStatus);
6924 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006925 if (ps.disabledComponents.size() > 0) {
6926 pw.println(" disabledComponents:");
6927 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006928 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006929 }
6930 }
6931 if (ps.enabledComponents.size() > 0) {
6932 pw.println(" enabledComponents:");
6933 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006934 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006935 }
6936 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006937 if (ps.grantedPermissions.size() > 0) {
6938 pw.println(" grantedPermissions:");
6939 for (String s : ps.grantedPermissions) {
6940 pw.print(" "); pw.println(s);
6941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006942 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006943 if (ps.loadedPermissions.size() > 0) {
6944 pw.println(" loadedPermissions:");
6945 for (String s : ps.loadedPermissions) {
6946 pw.print(" "); pw.println(s);
6947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948 }
6949 }
6950 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006951 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006952 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006953 for (HashMap.Entry<String, String> e
6954 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006955 if (packageName != null && !packageName.equals(e.getKey())
6956 && !packageName.equals(e.getValue())) {
6957 continue;
6958 }
6959 if (!printedSomething) {
6960 if (printedTitle) pw.println(" ");
6961 pw.println("Renamed packages:");
6962 printedSomething = true;
6963 printedTitle = true;
6964 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006965 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6966 pw.println(e.getValue());
6967 }
6968 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006969 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006970 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006971 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006972 if (packageName != null && !packageName.equals(ps.realName)
6973 && !packageName.equals(ps.name)) {
6974 continue;
6975 }
6976 if (!printedSomething) {
6977 if (printedTitle) pw.println(" ");
6978 pw.println("Hidden system packages:");
6979 printedSomething = true;
6980 printedTitle = true;
6981 }
6982 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006983 pw.print(ps.realName != null ? ps.realName : ps.name);
6984 pw.print("] (");
6985 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6986 pw.println("):");
6987 if (ps.realName != null) {
6988 pw.print(" compat name="); pw.println(ps.name);
6989 }
6990 pw.print(" userId="); pw.println(ps.userId);
6991 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6992 pw.print(" codePath="); pw.println(ps.codePathString);
6993 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6994 }
6995 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006996 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006997 {
6998 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006999 if (packageName != null && su != packageSharedUser) {
7000 continue;
7001 }
7002 if (!printedSomething) {
7003 if (printedTitle) pw.println(" ");
7004 pw.println("Shared users:");
7005 printedSomething = true;
7006 printedTitle = true;
7007 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007008 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7009 pw.print(Integer.toHexString(System.identityHashCode(su)));
7010 pw.println("):");
7011 pw.print(" userId="); pw.print(su.userId);
7012 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007013 pw.println(" grantedPermissions:");
7014 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007015 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007016 }
7017 pw.println(" loadedPermissions:");
7018 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007019 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007020 }
7021 }
7022 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007023
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007024 if (packageName == null) {
7025 if (printedTitle) pw.println(" ");
7026 printedTitle = true;
7027 pw.println("Settings parse messages:");
7028 pw.println(mSettings.mReadMessages.toString());
7029
7030 pw.println(" ");
7031 pw.println("Package warning messages:");
7032 File fname = getSettingsProblemFile();
7033 FileInputStream in;
7034 try {
7035 in = new FileInputStream(fname);
7036 int avail = in.available();
7037 byte[] data = new byte[avail];
7038 in.read(data);
7039 pw.println(new String(data));
7040 } catch (FileNotFoundException e) {
7041 } catch (IOException e) {
7042 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007045
7046 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007047 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007048 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007049 if (packageName != null && !packageName.equals(p.info.packageName)) {
7050 continue;
7051 }
7052 if (!printedSomething) {
7053 if (printedTitle) pw.println(" ");
7054 pw.println("Registered ContentProviders:");
7055 printedSomething = true;
7056 printedTitle = true;
7057 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007058 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007059 pw.println(p.toString());
7060 }
7061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007062 }
7063
7064 static final class BasePermission {
7065 final static int TYPE_NORMAL = 0;
7066 final static int TYPE_BUILTIN = 1;
7067 final static int TYPE_DYNAMIC = 2;
7068
7069 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007070 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007071 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007072 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007073 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007074 PackageParser.Permission perm;
7075 PermissionInfo pendingInfo;
7076 int uid;
7077 int[] gids;
7078
7079 BasePermission(String _name, String _sourcePackage, int _type) {
7080 name = _name;
7081 sourcePackage = _sourcePackage;
7082 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007083 // Default to most conservative protection level.
7084 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7085 }
7086
7087 public String toString() {
7088 return "BasePermission{"
7089 + Integer.toHexString(System.identityHashCode(this))
7090 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007091 }
7092 }
7093
7094 static class PackageSignatures {
7095 private Signature[] mSignatures;
7096
7097 PackageSignatures(Signature[] sigs) {
7098 assignSignatures(sigs);
7099 }
7100
7101 PackageSignatures() {
7102 }
7103
7104 void writeXml(XmlSerializer serializer, String tagName,
7105 ArrayList<Signature> pastSignatures) throws IOException {
7106 if (mSignatures == null) {
7107 return;
7108 }
7109 serializer.startTag(null, tagName);
7110 serializer.attribute(null, "count",
7111 Integer.toString(mSignatures.length));
7112 for (int i=0; i<mSignatures.length; i++) {
7113 serializer.startTag(null, "cert");
7114 final Signature sig = mSignatures[i];
7115 final int sigHash = sig.hashCode();
7116 final int numPast = pastSignatures.size();
7117 int j;
7118 for (j=0; j<numPast; j++) {
7119 Signature pastSig = pastSignatures.get(j);
7120 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7121 serializer.attribute(null, "index", Integer.toString(j));
7122 break;
7123 }
7124 }
7125 if (j >= numPast) {
7126 pastSignatures.add(sig);
7127 serializer.attribute(null, "index", Integer.toString(numPast));
7128 serializer.attribute(null, "key", sig.toCharsString());
7129 }
7130 serializer.endTag(null, "cert");
7131 }
7132 serializer.endTag(null, tagName);
7133 }
7134
7135 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7136 throws IOException, XmlPullParserException {
7137 String countStr = parser.getAttributeValue(null, "count");
7138 if (countStr == null) {
7139 reportSettingsProblem(Log.WARN,
7140 "Error in package manager settings: <signatures> has"
7141 + " no count at " + parser.getPositionDescription());
7142 XmlUtils.skipCurrentTag(parser);
7143 }
7144 final int count = Integer.parseInt(countStr);
7145 mSignatures = new Signature[count];
7146 int pos = 0;
7147
7148 int outerDepth = parser.getDepth();
7149 int type;
7150 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7151 && (type != XmlPullParser.END_TAG
7152 || parser.getDepth() > outerDepth)) {
7153 if (type == XmlPullParser.END_TAG
7154 || type == XmlPullParser.TEXT) {
7155 continue;
7156 }
7157
7158 String tagName = parser.getName();
7159 if (tagName.equals("cert")) {
7160 if (pos < count) {
7161 String index = parser.getAttributeValue(null, "index");
7162 if (index != null) {
7163 try {
7164 int idx = Integer.parseInt(index);
7165 String key = parser.getAttributeValue(null, "key");
7166 if (key == null) {
7167 if (idx >= 0 && idx < pastSignatures.size()) {
7168 Signature sig = pastSignatures.get(idx);
7169 if (sig != null) {
7170 mSignatures[pos] = pastSignatures.get(idx);
7171 pos++;
7172 } else {
7173 reportSettingsProblem(Log.WARN,
7174 "Error in package manager settings: <cert> "
7175 + "index " + index + " is not defined at "
7176 + parser.getPositionDescription());
7177 }
7178 } else {
7179 reportSettingsProblem(Log.WARN,
7180 "Error in package manager settings: <cert> "
7181 + "index " + index + " is out of bounds at "
7182 + parser.getPositionDescription());
7183 }
7184 } else {
7185 while (pastSignatures.size() <= idx) {
7186 pastSignatures.add(null);
7187 }
7188 Signature sig = new Signature(key);
7189 pastSignatures.set(idx, sig);
7190 mSignatures[pos] = sig;
7191 pos++;
7192 }
7193 } catch (NumberFormatException e) {
7194 reportSettingsProblem(Log.WARN,
7195 "Error in package manager settings: <cert> "
7196 + "index " + index + " is not a number at "
7197 + parser.getPositionDescription());
7198 }
7199 } else {
7200 reportSettingsProblem(Log.WARN,
7201 "Error in package manager settings: <cert> has"
7202 + " no index at " + parser.getPositionDescription());
7203 }
7204 } else {
7205 reportSettingsProblem(Log.WARN,
7206 "Error in package manager settings: too "
7207 + "many <cert> tags, expected " + count
7208 + " at " + parser.getPositionDescription());
7209 }
7210 } else {
7211 reportSettingsProblem(Log.WARN,
7212 "Unknown element under <cert>: "
7213 + parser.getName());
7214 }
7215 XmlUtils.skipCurrentTag(parser);
7216 }
7217
7218 if (pos < count) {
7219 // Should never happen -- there is an error in the written
7220 // settings -- but if it does we don't want to generate
7221 // a bad array.
7222 Signature[] newSigs = new Signature[pos];
7223 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7224 mSignatures = newSigs;
7225 }
7226 }
7227
7228 /**
7229 * If any of the given 'sigs' is contained in the existing signatures,
7230 * then completely replace the current signatures with the ones in
7231 * 'sigs'. This is used for updating an existing package to a newly
7232 * installed version.
7233 */
7234 boolean updateSignatures(Signature[] sigs, boolean update) {
7235 if (mSignatures == null) {
7236 if (update) {
7237 assignSignatures(sigs);
7238 }
7239 return true;
7240 }
7241 if (sigs == null) {
7242 return false;
7243 }
7244
7245 for (int i=0; i<sigs.length; i++) {
7246 Signature sig = sigs[i];
7247 for (int j=0; j<mSignatures.length; j++) {
7248 if (mSignatures[j].equals(sig)) {
7249 if (update) {
7250 assignSignatures(sigs);
7251 }
7252 return true;
7253 }
7254 }
7255 }
7256 return false;
7257 }
7258
7259 /**
7260 * If any of the given 'sigs' is contained in the existing signatures,
7261 * then add in any new signatures found in 'sigs'. This is used for
7262 * including a new package into an existing shared user id.
7263 */
7264 boolean mergeSignatures(Signature[] sigs, boolean update) {
7265 if (mSignatures == null) {
7266 if (update) {
7267 assignSignatures(sigs);
7268 }
7269 return true;
7270 }
7271 if (sigs == null) {
7272 return false;
7273 }
7274
7275 Signature[] added = null;
7276 int addedCount = 0;
7277 boolean haveMatch = false;
7278 for (int i=0; i<sigs.length; i++) {
7279 Signature sig = sigs[i];
7280 boolean found = false;
7281 for (int j=0; j<mSignatures.length; j++) {
7282 if (mSignatures[j].equals(sig)) {
7283 found = true;
7284 haveMatch = true;
7285 break;
7286 }
7287 }
7288
7289 if (!found) {
7290 if (added == null) {
7291 added = new Signature[sigs.length];
7292 }
7293 added[i] = sig;
7294 addedCount++;
7295 }
7296 }
7297
7298 if (!haveMatch) {
7299 // Nothing matched -- reject the new signatures.
7300 return false;
7301 }
7302 if (added == null) {
7303 // Completely matched -- nothing else to do.
7304 return true;
7305 }
7306
7307 // Add additional signatures in.
7308 if (update) {
7309 Signature[] total = new Signature[addedCount+mSignatures.length];
7310 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
7311 int j = mSignatures.length;
7312 for (int i=0; i<added.length; i++) {
7313 if (added[i] != null) {
7314 total[j] = added[i];
7315 j++;
7316 }
7317 }
7318 mSignatures = total;
7319 }
7320 return true;
7321 }
7322
7323 private void assignSignatures(Signature[] sigs) {
7324 if (sigs == null) {
7325 mSignatures = null;
7326 return;
7327 }
7328 mSignatures = new Signature[sigs.length];
7329 for (int i=0; i<sigs.length; i++) {
7330 mSignatures[i] = sigs[i];
7331 }
7332 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 @Override
7335 public String toString() {
7336 StringBuffer buf = new StringBuffer(128);
7337 buf.append("PackageSignatures{");
7338 buf.append(Integer.toHexString(System.identityHashCode(this)));
7339 buf.append(" [");
7340 if (mSignatures != null) {
7341 for (int i=0; i<mSignatures.length; i++) {
7342 if (i > 0) buf.append(", ");
7343 buf.append(Integer.toHexString(
7344 System.identityHashCode(mSignatures[i])));
7345 }
7346 }
7347 buf.append("]}");
7348 return buf.toString();
7349 }
7350 }
7351
7352 static class PreferredActivity extends IntentFilter {
7353 final int mMatch;
7354 final String[] mSetPackages;
7355 final String[] mSetClasses;
7356 final String[] mSetComponents;
7357 final ComponentName mActivity;
7358 final String mShortActivity;
7359 String mParseError;
7360
7361 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7362 ComponentName activity) {
7363 super(filter);
7364 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7365 mActivity = activity;
7366 mShortActivity = activity.flattenToShortString();
7367 mParseError = null;
7368 if (set != null) {
7369 final int N = set.length;
7370 String[] myPackages = new String[N];
7371 String[] myClasses = new String[N];
7372 String[] myComponents = new String[N];
7373 for (int i=0; i<N; i++) {
7374 ComponentName cn = set[i];
7375 if (cn == null) {
7376 mSetPackages = null;
7377 mSetClasses = null;
7378 mSetComponents = null;
7379 return;
7380 }
7381 myPackages[i] = cn.getPackageName().intern();
7382 myClasses[i] = cn.getClassName().intern();
7383 myComponents[i] = cn.flattenToShortString().intern();
7384 }
7385 mSetPackages = myPackages;
7386 mSetClasses = myClasses;
7387 mSetComponents = myComponents;
7388 } else {
7389 mSetPackages = null;
7390 mSetClasses = null;
7391 mSetComponents = null;
7392 }
7393 }
7394
7395 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7396 IOException {
7397 mShortActivity = parser.getAttributeValue(null, "name");
7398 mActivity = ComponentName.unflattenFromString(mShortActivity);
7399 if (mActivity == null) {
7400 mParseError = "Bad activity name " + mShortActivity;
7401 }
7402 String matchStr = parser.getAttributeValue(null, "match");
7403 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7404 String setCountStr = parser.getAttributeValue(null, "set");
7405 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7406
7407 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7408 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7409 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7410
7411 int setPos = 0;
7412
7413 int outerDepth = parser.getDepth();
7414 int type;
7415 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7416 && (type != XmlPullParser.END_TAG
7417 || parser.getDepth() > outerDepth)) {
7418 if (type == XmlPullParser.END_TAG
7419 || type == XmlPullParser.TEXT) {
7420 continue;
7421 }
7422
7423 String tagName = parser.getName();
7424 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7425 // + parser.getDepth() + " tag=" + tagName);
7426 if (tagName.equals("set")) {
7427 String name = parser.getAttributeValue(null, "name");
7428 if (name == null) {
7429 if (mParseError == null) {
7430 mParseError = "No name in set tag in preferred activity "
7431 + mShortActivity;
7432 }
7433 } else if (setPos >= setCount) {
7434 if (mParseError == null) {
7435 mParseError = "Too many set tags in preferred activity "
7436 + mShortActivity;
7437 }
7438 } else {
7439 ComponentName cn = ComponentName.unflattenFromString(name);
7440 if (cn == null) {
7441 if (mParseError == null) {
7442 mParseError = "Bad set name " + name + " in preferred activity "
7443 + mShortActivity;
7444 }
7445 } else {
7446 myPackages[setPos] = cn.getPackageName();
7447 myClasses[setPos] = cn.getClassName();
7448 myComponents[setPos] = name;
7449 setPos++;
7450 }
7451 }
7452 XmlUtils.skipCurrentTag(parser);
7453 } else if (tagName.equals("filter")) {
7454 //Log.i(TAG, "Starting to parse filter...");
7455 readFromXml(parser);
7456 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7457 // + parser.getDepth() + " tag=" + parser.getName());
7458 } else {
7459 reportSettingsProblem(Log.WARN,
7460 "Unknown element under <preferred-activities>: "
7461 + parser.getName());
7462 XmlUtils.skipCurrentTag(parser);
7463 }
7464 }
7465
7466 if (setPos != setCount) {
7467 if (mParseError == null) {
7468 mParseError = "Not enough set tags (expected " + setCount
7469 + " but found " + setPos + ") in " + mShortActivity;
7470 }
7471 }
7472
7473 mSetPackages = myPackages;
7474 mSetClasses = myClasses;
7475 mSetComponents = myComponents;
7476 }
7477
7478 public void writeToXml(XmlSerializer serializer) throws IOException {
7479 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7480 serializer.attribute(null, "name", mShortActivity);
7481 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7482 serializer.attribute(null, "set", Integer.toString(NS));
7483 for (int s=0; s<NS; s++) {
7484 serializer.startTag(null, "set");
7485 serializer.attribute(null, "name", mSetComponents[s]);
7486 serializer.endTag(null, "set");
7487 }
7488 serializer.startTag(null, "filter");
7489 super.writeToXml(serializer);
7490 serializer.endTag(null, "filter");
7491 }
7492
7493 boolean sameSet(List<ResolveInfo> query, int priority) {
7494 if (mSetPackages == null) return false;
7495 final int NQ = query.size();
7496 final int NS = mSetPackages.length;
7497 int numMatch = 0;
7498 for (int i=0; i<NQ; i++) {
7499 ResolveInfo ri = query.get(i);
7500 if (ri.priority != priority) continue;
7501 ActivityInfo ai = ri.activityInfo;
7502 boolean good = false;
7503 for (int j=0; j<NS; j++) {
7504 if (mSetPackages[j].equals(ai.packageName)
7505 && mSetClasses[j].equals(ai.name)) {
7506 numMatch++;
7507 good = true;
7508 break;
7509 }
7510 }
7511 if (!good) return false;
7512 }
7513 return numMatch == NS;
7514 }
7515 }
7516
7517 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007518 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007520 HashSet<String> grantedPermissions = new HashSet<String>();
7521 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007525 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007526 setFlags(pkgFlags);
7527 }
7528
7529 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007530 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007531 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08007532 (pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) |
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08007533 (pkgFlags & ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007534 }
7535 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007537 /**
7538 * Settings base class for pending and resolved classes.
7539 */
7540 static class PackageSettingBase extends GrantedPermissions {
7541 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007542 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007543 File codePath;
7544 String codePathString;
7545 File resourcePath;
7546 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007547 private long timeStamp;
7548 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007549 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007550
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007551 boolean uidError;
7552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007553 PackageSignatures signatures = new PackageSignatures();
7554
7555 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007557 /* Explicitly disabled components */
7558 HashSet<String> disabledComponents = new HashSet<String>(0);
7559 /* Explicitly enabled components */
7560 HashSet<String> enabledComponents = new HashSet<String>(0);
7561 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7562 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007563
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007564 PackageSettingBase origPackage;
7565
Jacek Surazski65e13172009-04-28 15:26:38 +02007566 /* package name of the app that installed this package */
7567 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007568
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007569 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007570 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007571 super(pkgFlags);
7572 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007573 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007574 init(codePath, resourcePath, pVersionCode);
7575 }
7576
7577 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007578 this.codePath = codePath;
7579 this.codePathString = codePath.toString();
7580 this.resourcePath = resourcePath;
7581 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007582 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007584
Jacek Surazski65e13172009-04-28 15:26:38 +02007585 public void setInstallerPackageName(String packageName) {
7586 installerPackageName = packageName;
7587 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007588
Jacek Surazski65e13172009-04-28 15:26:38 +02007589 String getInstallerPackageName() {
7590 return installerPackageName;
7591 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007593 public void setInstallStatus(int newStatus) {
7594 installStatus = newStatus;
7595 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007597 public int getInstallStatus() {
7598 return installStatus;
7599 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007601 public void setTimeStamp(long newStamp) {
7602 if (newStamp != timeStamp) {
7603 timeStamp = newStamp;
7604 timeStampString = Long.toString(newStamp);
7605 }
7606 }
7607
7608 public void setTimeStamp(long newStamp, String newStampStr) {
7609 timeStamp = newStamp;
7610 timeStampString = newStampStr;
7611 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613 public long getTimeStamp() {
7614 return timeStamp;
7615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007617 public String getTimeStampStr() {
7618 return timeStampString;
7619 }
7620
7621 public void copyFrom(PackageSettingBase base) {
7622 grantedPermissions = base.grantedPermissions;
7623 gids = base.gids;
7624 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007626 timeStamp = base.timeStamp;
7627 timeStampString = base.timeStampString;
7628 signatures = base.signatures;
7629 permissionsFixed = base.permissionsFixed;
7630 disabledComponents = base.disabledComponents;
7631 enabledComponents = base.enabledComponents;
7632 enabled = base.enabled;
7633 installStatus = base.installStatus;
7634 }
7635
7636 void enableComponentLP(String componentClassName) {
7637 disabledComponents.remove(componentClassName);
7638 enabledComponents.add(componentClassName);
7639 }
7640
7641 void disableComponentLP(String componentClassName) {
7642 enabledComponents.remove(componentClassName);
7643 disabledComponents.add(componentClassName);
7644 }
7645
7646 void restoreComponentLP(String componentClassName) {
7647 enabledComponents.remove(componentClassName);
7648 disabledComponents.remove(componentClassName);
7649 }
7650
7651 int currentEnabledStateLP(String componentName) {
7652 if (enabledComponents.contains(componentName)) {
7653 return COMPONENT_ENABLED_STATE_ENABLED;
7654 } else if (disabledComponents.contains(componentName)) {
7655 return COMPONENT_ENABLED_STATE_DISABLED;
7656 } else {
7657 return COMPONENT_ENABLED_STATE_DEFAULT;
7658 }
7659 }
7660 }
7661
7662 /**
7663 * Settings data for a particular package we know about.
7664 */
7665 static final class PackageSetting extends PackageSettingBase {
7666 int userId;
7667 PackageParser.Package pkg;
7668 SharedUserSetting sharedUser;
7669
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007670 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007671 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007672 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 @Override
7676 public String toString() {
7677 return "PackageSetting{"
7678 + Integer.toHexString(System.identityHashCode(this))
7679 + " " + name + "/" + userId + "}";
7680 }
7681 }
7682
7683 /**
7684 * Settings data for a particular shared user ID we know about.
7685 */
7686 static final class SharedUserSetting extends GrantedPermissions {
7687 final String name;
7688 int userId;
7689 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7690 final PackageSignatures signatures = new PackageSignatures();
7691
7692 SharedUserSetting(String _name, int _pkgFlags) {
7693 super(_pkgFlags);
7694 name = _name;
7695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007697 @Override
7698 public String toString() {
7699 return "SharedUserSetting{"
7700 + Integer.toHexString(System.identityHashCode(this))
7701 + " " + name + "/" + userId + "}";
7702 }
7703 }
7704
7705 /**
7706 * Holds information about dynamic settings.
7707 */
7708 private static final class Settings {
7709 private final File mSettingsFilename;
7710 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007711 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 private final HashMap<String, PackageSetting> mPackages =
7713 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 // List of replaced system applications
7715 final HashMap<String, PackageSetting> mDisabledSysPackages =
7716 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 // The user's preferred activities associated with particular intent
7719 // filters.
7720 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7721 new IntentResolver<PreferredActivity, PreferredActivity>() {
7722 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007723 protected String packageForFilter(PreferredActivity filter) {
7724 return filter.mActivity.getPackageName();
7725 }
7726 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007727 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007728 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007729 out.print(prefix); out.print(
7730 Integer.toHexString(System.identityHashCode(filter)));
7731 out.print(' ');
7732 out.print(filter.mActivity.flattenToShortString());
7733 out.print(" match=0x");
7734 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007736 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007738 out.print(prefix); out.print(" ");
7739 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 }
7741 }
7742 }
7743 };
7744 private final HashMap<String, SharedUserSetting> mSharedUsers =
7745 new HashMap<String, SharedUserSetting>();
7746 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7747 private final SparseArray<Object> mOtherUserIds =
7748 new SparseArray<Object>();
7749
7750 // For reading/writing settings file.
7751 private final ArrayList<Signature> mPastSignatures =
7752 new ArrayList<Signature>();
7753
7754 // Mapping from permission names to info about them.
7755 final HashMap<String, BasePermission> mPermissions =
7756 new HashMap<String, BasePermission>();
7757
7758 // Mapping from permission tree names to info about them.
7759 final HashMap<String, BasePermission> mPermissionTrees =
7760 new HashMap<String, BasePermission>();
7761
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007762 // Packages that have been uninstalled and still need their external
7763 // storage data deleted.
7764 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7765
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007766 // Packages that have been renamed since they were first installed.
7767 // Keys are the new names of the packages, values are the original
7768 // names. The packages appear everwhere else under their original
7769 // names.
7770 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007772 private final StringBuilder mReadMessages = new StringBuilder();
7773
7774 private static final class PendingPackage extends PackageSettingBase {
7775 final int sharedId;
7776
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007777 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007778 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007779 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 this.sharedId = sharedId;
7781 }
7782 }
7783 private final ArrayList<PendingPackage> mPendingPackages
7784 = new ArrayList<PendingPackage>();
7785
7786 Settings() {
7787 File dataDir = Environment.getDataDirectory();
7788 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007789 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7790 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007792 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 FileUtils.setPermissions(systemDir.toString(),
7794 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7795 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7796 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007797 FileUtils.setPermissions(systemSecureDir.toString(),
7798 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7799 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7800 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 mSettingsFilename = new File(systemDir, "packages.xml");
7802 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007803 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007804 }
7805
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007806 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007807 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007808 int pkgFlags, boolean create, boolean add) {
7809 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007810 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007811 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007812 return p;
7813 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007814
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007815 PackageSetting peekPackageLP(String name) {
7816 return mPackages.get(name);
7817 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 PackageSetting p = mPackages.get(name);
7819 if (p != null && p.codePath.getPath().equals(codePath)) {
7820 return p;
7821 }
7822 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007823 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 void setInstallStatus(String pkgName, int status) {
7827 PackageSetting p = mPackages.get(pkgName);
7828 if(p != null) {
7829 if(p.getInstallStatus() != status) {
7830 p.setInstallStatus(status);
7831 }
7832 }
7833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007834
Jacek Surazski65e13172009-04-28 15:26:38 +02007835 void setInstallerPackageName(String pkgName,
7836 String installerPkgName) {
7837 PackageSetting p = mPackages.get(pkgName);
7838 if(p != null) {
7839 p.setInstallerPackageName(installerPkgName);
7840 }
7841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007842
Jacek Surazski65e13172009-04-28 15:26:38 +02007843 String getInstallerPackageName(String pkgName) {
7844 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007845 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007846 }
7847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 int getInstallStatus(String pkgName) {
7849 PackageSetting p = mPackages.get(pkgName);
7850 if(p != null) {
7851 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007853 return -1;
7854 }
7855
7856 SharedUserSetting getSharedUserLP(String name,
7857 int pkgFlags, boolean create) {
7858 SharedUserSetting s = mSharedUsers.get(name);
7859 if (s == null) {
7860 if (!create) {
7861 return null;
7862 }
7863 s = new SharedUserSetting(name, pkgFlags);
7864 if (MULTIPLE_APPLICATION_UIDS) {
7865 s.userId = newUserIdLP(s);
7866 } else {
7867 s.userId = FIRST_APPLICATION_UID;
7868 }
7869 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7870 // < 0 means we couldn't assign a userid; fall out and return
7871 // s, which is currently null
7872 if (s.userId >= 0) {
7873 mSharedUsers.put(name, s);
7874 }
7875 }
7876
7877 return s;
7878 }
7879
7880 int disableSystemPackageLP(String name) {
7881 PackageSetting p = mPackages.get(name);
7882 if(p == null) {
7883 Log.w(TAG, "Package:"+name+" is not an installed package");
7884 return -1;
7885 }
7886 PackageSetting dp = mDisabledSysPackages.get(name);
7887 // always make sure the system package code and resource paths dont change
7888 if(dp == null) {
7889 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7890 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7891 }
7892 mDisabledSysPackages.put(name, p);
7893 }
7894 return removePackageLP(name);
7895 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007897 PackageSetting enableSystemPackageLP(String name) {
7898 PackageSetting p = mDisabledSysPackages.get(name);
7899 if(p == null) {
7900 Log.w(TAG, "Package:"+name+" is not disabled");
7901 return null;
7902 }
7903 // Reset flag in ApplicationInfo object
7904 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7905 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7906 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007907 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007908 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 mDisabledSysPackages.remove(name);
7910 return ret;
7911 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007912
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007913 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007914 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007915 PackageSetting p = mPackages.get(name);
7916 if (p != null) {
7917 if (p.userId == uid) {
7918 return p;
7919 }
7920 reportSettingsProblem(Log.ERROR,
7921 "Adding duplicate package, keeping first: " + name);
7922 return null;
7923 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007924 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007925 p.userId = uid;
7926 if (addUserIdLP(uid, p, name)) {
7927 mPackages.put(name, p);
7928 return p;
7929 }
7930 return null;
7931 }
7932
7933 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7934 SharedUserSetting s = mSharedUsers.get(name);
7935 if (s != null) {
7936 if (s.userId == uid) {
7937 return s;
7938 }
7939 reportSettingsProblem(Log.ERROR,
7940 "Adding duplicate shared user, keeping first: " + name);
7941 return null;
7942 }
7943 s = new SharedUserSetting(name, pkgFlags);
7944 s.userId = uid;
7945 if (addUserIdLP(uid, s, name)) {
7946 mSharedUsers.put(name, s);
7947 return s;
7948 }
7949 return null;
7950 }
7951
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007952 // Transfer ownership of permissions from one package to another.
7953 private void transferPermissions(String origPkg, String newPkg) {
7954 // Transfer ownership of permissions to the new package.
7955 for (int i=0; i<2; i++) {
7956 HashMap<String, BasePermission> permissions =
7957 i == 0 ? mPermissionTrees : mPermissions;
7958 for (BasePermission bp : permissions.values()) {
7959 if (origPkg.equals(bp.sourcePackage)) {
7960 if (DEBUG_UPGRADE) Log.v(TAG,
7961 "Moving permission " + bp.name
7962 + " from pkg " + bp.sourcePackage
7963 + " to " + newPkg);
7964 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007965 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007966 bp.perm = null;
7967 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007968 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007969 }
7970 bp.uid = 0;
7971 bp.gids = null;
7972 }
7973 }
7974 }
7975 }
7976
7977 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007978 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007979 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 PackageSetting p = mPackages.get(name);
7981 if (p != null) {
7982 if (!p.codePath.equals(codePath)) {
7983 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007984 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007985 // This is an updated system app with versions in both system
7986 // and data partition. Just let the most recent version
7987 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007988 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007989 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007990 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007991 // Just a change in the code path is not an issue, but
7992 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007993 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007994 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007995 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007996 }
7997 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 reportSettingsProblem(Log.WARN,
7999 "Package " + name + " shared user changed from "
8000 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8001 + " to "
8002 + (sharedUser != null ? sharedUser.name : "<nothing>")
8003 + "; replacing with new");
8004 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008005 } else {
8006 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8007 // If what we are scanning is a system package, then
8008 // make it so, regardless of whether it was previously
8009 // installed only in the data partition.
8010 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008012 }
8013 }
8014 if (p == null) {
8015 // Create a new PackageSettings entry. this can end up here because
8016 // of code path mismatch or user id mismatch of an updated system partition
8017 if (!create) {
8018 return null;
8019 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008020 if (origPackage != null) {
8021 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008022 p = new PackageSetting(origPackage.name, name, codePath,
8023 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008024 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8025 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008026 // Note that we will retain the new package's signature so
8027 // that we can keep its data.
8028 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008029 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008030 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008031 p.sharedUser = origPackage.sharedUser;
8032 p.userId = origPackage.userId;
8033 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008034 mRenamedPackages.put(name, origPackage.name);
8035 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008036 // Update new package state.
8037 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008038 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008039 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008040 p.setTimeStamp(codePath.lastModified());
8041 p.sharedUser = sharedUser;
8042 if (sharedUser != null) {
8043 p.userId = sharedUser.userId;
8044 } else if (MULTIPLE_APPLICATION_UIDS) {
8045 // Clone the setting here for disabled system packages
8046 PackageSetting dis = mDisabledSysPackages.get(name);
8047 if (dis != null) {
8048 // For disabled packages a new setting is created
8049 // from the existing user id. This still has to be
8050 // added to list of user id's
8051 // Copy signatures from previous setting
8052 if (dis.signatures.mSignatures != null) {
8053 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8054 }
8055 p.userId = dis.userId;
8056 // Clone permissions
8057 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
8058 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
8059 // Clone component info
8060 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8061 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8062 // Add new setting to list of user ids
8063 addUserIdLP(p.userId, p, name);
8064 } else {
8065 // Assign new user id
8066 p.userId = newUserIdLP(p);
8067 }
8068 } else {
8069 p.userId = FIRST_APPLICATION_UID;
8070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008071 }
8072 if (p.userId < 0) {
8073 reportSettingsProblem(Log.WARN,
8074 "Package " + name + " could not be assigned a valid uid");
8075 return null;
8076 }
8077 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008078 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008079 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008080 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008081 }
8082 }
8083 return p;
8084 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008085
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008086 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008087 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008088 String codePath = pkg.applicationInfo.sourceDir;
8089 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008090 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008091 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008092 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008093 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008094 p.codePath = new File(codePath);
8095 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008096 }
8097 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008098 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008099 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008100 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008101 p.resourcePath = new File(resourcePath);
8102 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008103 }
8104 // Update version code if needed
8105 if (pkg.mVersionCode != p.versionCode) {
8106 p.versionCode = pkg.mVersionCode;
8107 }
8108 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8109 }
8110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008111 // Utility method that adds a PackageSetting to mPackages and
8112 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008113 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008114 SharedUserSetting sharedUser) {
8115 mPackages.put(name, p);
8116 if (sharedUser != null) {
8117 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8118 reportSettingsProblem(Log.ERROR,
8119 "Package " + p.name + " was user "
8120 + p.sharedUser + " but is now " + sharedUser
8121 + "; I am not changing its files so it will probably fail!");
8122 p.sharedUser.packages.remove(p);
8123 } else if (p.userId != sharedUser.userId) {
8124 reportSettingsProblem(Log.ERROR,
8125 "Package " + p.name + " was user id " + p.userId
8126 + " but is now user " + sharedUser
8127 + " with id " + sharedUser.userId
8128 + "; I am not changing its files so it will probably fail!");
8129 }
8130
8131 sharedUser.packages.add(p);
8132 p.sharedUser = sharedUser;
8133 p.userId = sharedUser.userId;
8134 }
8135 }
8136
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008137 /*
8138 * Update the shared user setting when a package using
8139 * specifying the shared user id is removed. The gids
8140 * associated with each permission of the deleted package
8141 * are removed from the shared user's gid list only if its
8142 * not in use by other permissions of packages in the
8143 * shared user setting.
8144 */
8145 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008146 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008147 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 return;
8149 }
8150 // No sharedUserId
8151 if (deletedPs.sharedUser == null) {
8152 return;
8153 }
8154 SharedUserSetting sus = deletedPs.sharedUser;
8155 // Update permissions
8156 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8157 boolean used = false;
8158 if (!sus.grantedPermissions.contains (eachPerm)) {
8159 continue;
8160 }
8161 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008162 if (pkg.pkg != null &&
8163 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
8164 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165 used = true;
8166 break;
8167 }
8168 }
8169 if (!used) {
8170 // can safely delete this permission from list
8171 sus.grantedPermissions.remove(eachPerm);
8172 sus.loadedPermissions.remove(eachPerm);
8173 }
8174 }
8175 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008176 int newGids[] = globalGids;
8177 for (String eachPerm : sus.grantedPermissions) {
8178 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008179 if (bp != null) {
8180 newGids = appendInts(newGids, bp.gids);
8181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008182 }
8183 sus.gids = newGids;
8184 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008186 private int removePackageLP(String name) {
8187 PackageSetting p = mPackages.get(name);
8188 if (p != null) {
8189 mPackages.remove(name);
8190 if (p.sharedUser != null) {
8191 p.sharedUser.packages.remove(p);
8192 if (p.sharedUser.packages.size() == 0) {
8193 mSharedUsers.remove(p.sharedUser.name);
8194 removeUserIdLP(p.sharedUser.userId);
8195 return p.sharedUser.userId;
8196 }
8197 } else {
8198 removeUserIdLP(p.userId);
8199 return p.userId;
8200 }
8201 }
8202 return -1;
8203 }
8204
8205 private boolean addUserIdLP(int uid, Object obj, Object name) {
8206 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8207 return false;
8208 }
8209
8210 if (uid >= FIRST_APPLICATION_UID) {
8211 int N = mUserIds.size();
8212 final int index = uid - FIRST_APPLICATION_UID;
8213 while (index >= N) {
8214 mUserIds.add(null);
8215 N++;
8216 }
8217 if (mUserIds.get(index) != null) {
8218 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008219 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220 + " name=" + name);
8221 return false;
8222 }
8223 mUserIds.set(index, obj);
8224 } else {
8225 if (mOtherUserIds.get(uid) != null) {
8226 reportSettingsProblem(Log.ERROR,
8227 "Adding duplicate shared id: " + uid
8228 + " name=" + name);
8229 return false;
8230 }
8231 mOtherUserIds.put(uid, obj);
8232 }
8233 return true;
8234 }
8235
8236 public Object getUserIdLP(int uid) {
8237 if (uid >= FIRST_APPLICATION_UID) {
8238 int N = mUserIds.size();
8239 final int index = uid - FIRST_APPLICATION_UID;
8240 return index < N ? mUserIds.get(index) : null;
8241 } else {
8242 return mOtherUserIds.get(uid);
8243 }
8244 }
8245
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008246 private Set<String> findPackagesWithFlag(int flag) {
8247 Set<String> ret = new HashSet<String>();
8248 for (PackageSetting ps : mPackages.values()) {
8249 // Has to match atleast all the flag bits set on flag
8250 if ((ps.pkgFlags & flag) == flag) {
8251 ret.add(ps.name);
8252 }
8253 }
8254 return ret;
8255 }
8256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008257 private void removeUserIdLP(int uid) {
8258 if (uid >= FIRST_APPLICATION_UID) {
8259 int N = mUserIds.size();
8260 final int index = uid - FIRST_APPLICATION_UID;
8261 if (index < N) mUserIds.set(index, null);
8262 } else {
8263 mOtherUserIds.remove(uid);
8264 }
8265 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008267 void writeLP() {
8268 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8269
8270 // Keep the old settings around until we know the new ones have
8271 // been successfully written.
8272 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008273 // Presence of backup settings file indicates that we failed
8274 // to persist settings earlier. So preserve the older
8275 // backup for future reference since the current settings
8276 // might have been corrupted.
8277 if (!mBackupSettingsFilename.exists()) {
8278 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008279 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008280 return;
8281 }
8282 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008283 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008284 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008286 }
8287
8288 mPastSignatures.clear();
8289
8290 try {
8291 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8292
8293 //XmlSerializer serializer = XmlUtils.serializerInstance();
8294 XmlSerializer serializer = new FastXmlSerializer();
8295 serializer.setOutput(str, "utf-8");
8296 serializer.startDocument(null, true);
8297 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8298
8299 serializer.startTag(null, "packages");
8300
8301 serializer.startTag(null, "permission-trees");
8302 for (BasePermission bp : mPermissionTrees.values()) {
8303 writePermission(serializer, bp);
8304 }
8305 serializer.endTag(null, "permission-trees");
8306
8307 serializer.startTag(null, "permissions");
8308 for (BasePermission bp : mPermissions.values()) {
8309 writePermission(serializer, bp);
8310 }
8311 serializer.endTag(null, "permissions");
8312
8313 for (PackageSetting pkg : mPackages.values()) {
8314 writePackage(serializer, pkg);
8315 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008317 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8318 writeDisabledSysPackage(serializer, pkg);
8319 }
8320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008321 serializer.startTag(null, "preferred-activities");
8322 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8323 serializer.startTag(null, "item");
8324 pa.writeToXml(serializer);
8325 serializer.endTag(null, "item");
8326 }
8327 serializer.endTag(null, "preferred-activities");
8328
8329 for (SharedUserSetting usr : mSharedUsers.values()) {
8330 serializer.startTag(null, "shared-user");
8331 serializer.attribute(null, "name", usr.name);
8332 serializer.attribute(null, "userId",
8333 Integer.toString(usr.userId));
8334 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8335 serializer.startTag(null, "perms");
8336 for (String name : usr.grantedPermissions) {
8337 serializer.startTag(null, "item");
8338 serializer.attribute(null, "name", name);
8339 serializer.endTag(null, "item");
8340 }
8341 serializer.endTag(null, "perms");
8342 serializer.endTag(null, "shared-user");
8343 }
8344
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008345 if (mPackagesToBeCleaned.size() > 0) {
8346 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8347 serializer.startTag(null, "cleaning-package");
8348 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8349 serializer.endTag(null, "cleaning-package");
8350 }
8351 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008352
8353 if (mRenamedPackages.size() > 0) {
8354 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8355 serializer.startTag(null, "renamed-package");
8356 serializer.attribute(null, "new", e.getKey());
8357 serializer.attribute(null, "old", e.getValue());
8358 serializer.endTag(null, "renamed-package");
8359 }
8360 }
8361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008362 serializer.endTag(null, "packages");
8363
8364 serializer.endDocument();
8365
8366 str.flush();
8367 str.close();
8368
8369 // New settings successfully written, old ones are no longer
8370 // needed.
8371 mBackupSettingsFilename.delete();
8372 FileUtils.setPermissions(mSettingsFilename.toString(),
8373 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8374 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8375 |FileUtils.S_IROTH,
8376 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008377
8378 // Write package list file now, use a JournaledFile.
8379 //
8380 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8381 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8382
8383 str = new FileOutputStream(journal.chooseForWrite());
8384 try {
8385 StringBuilder sb = new StringBuilder();
8386 for (PackageSetting pkg : mPackages.values()) {
8387 ApplicationInfo ai = pkg.pkg.applicationInfo;
8388 String dataPath = ai.dataDir;
8389 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8390
8391 // Avoid any application that has a space in its path
8392 // or that is handled by the system.
8393 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8394 continue;
8395
8396 // we store on each line the following information for now:
8397 //
8398 // pkgName - package name
8399 // userId - application-specific user id
8400 // debugFlag - 0 or 1 if the package is debuggable.
8401 // dataPath - path to package's data path
8402 //
8403 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8404 //
8405 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8406 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8407 // system/core/run-as/run-as.c
8408 //
8409 sb.setLength(0);
8410 sb.append(ai.packageName);
8411 sb.append(" ");
8412 sb.append((int)ai.uid);
8413 sb.append(isDebug ? " 1 " : " 0 ");
8414 sb.append(dataPath);
8415 sb.append("\n");
8416 str.write(sb.toString().getBytes());
8417 }
8418 str.flush();
8419 str.close();
8420 journal.commit();
8421 }
8422 catch (Exception e) {
8423 journal.rollback();
8424 }
8425
8426 FileUtils.setPermissions(mPackageListFilename.toString(),
8427 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8428 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8429 |FileUtils.S_IROTH,
8430 -1, -1);
8431
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008432 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008433
8434 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008435 Slog.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008436 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008437 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 -08008438 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008439 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008440 if (mSettingsFilename.exists()) {
8441 if (!mSettingsFilename.delete()) {
8442 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8443 }
8444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008445 //Debug.stopMethodTracing();
8446 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008447
8448 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008449 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008450 serializer.startTag(null, "updated-package");
8451 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008452 if (pkg.realName != null) {
8453 serializer.attribute(null, "realName", pkg.realName);
8454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008455 serializer.attribute(null, "codePath", pkg.codePathString);
8456 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008457 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8459 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8460 }
8461 if (pkg.sharedUser == null) {
8462 serializer.attribute(null, "userId",
8463 Integer.toString(pkg.userId));
8464 } else {
8465 serializer.attribute(null, "sharedUserId",
8466 Integer.toString(pkg.userId));
8467 }
8468 serializer.startTag(null, "perms");
8469 if (pkg.sharedUser == null) {
8470 // If this is a shared user, the permissions will
8471 // be written there. We still need to write an
8472 // empty permissions list so permissionsFixed will
8473 // be set.
8474 for (final String name : pkg.grantedPermissions) {
8475 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008476 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008477 // We only need to write signature or system permissions but this wont
8478 // match the semantics of grantedPermissions. So write all permissions.
8479 serializer.startTag(null, "item");
8480 serializer.attribute(null, "name", name);
8481 serializer.endTag(null, "item");
8482 }
8483 }
8484 }
8485 serializer.endTag(null, "perms");
8486 serializer.endTag(null, "updated-package");
8487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008488
8489 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008490 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008491 serializer.startTag(null, "package");
8492 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008493 if (pkg.realName != null) {
8494 serializer.attribute(null, "realName", pkg.realName);
8495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008496 serializer.attribute(null, "codePath", pkg.codePathString);
8497 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8498 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8499 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008500 serializer.attribute(null, "flags",
8501 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008503 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008504 if (pkg.sharedUser == null) {
8505 serializer.attribute(null, "userId",
8506 Integer.toString(pkg.userId));
8507 } else {
8508 serializer.attribute(null, "sharedUserId",
8509 Integer.toString(pkg.userId));
8510 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008511 if (pkg.uidError) {
8512 serializer.attribute(null, "uidError", "true");
8513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008514 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8515 serializer.attribute(null, "enabled",
8516 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8517 ? "true" : "false");
8518 }
8519 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8520 serializer.attribute(null, "installStatus", "false");
8521 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008522 if (pkg.installerPackageName != null) {
8523 serializer.attribute(null, "installer", pkg.installerPackageName);
8524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008525 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8526 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8527 serializer.startTag(null, "perms");
8528 if (pkg.sharedUser == null) {
8529 // If this is a shared user, the permissions will
8530 // be written there. We still need to write an
8531 // empty permissions list so permissionsFixed will
8532 // be set.
8533 for (final String name : pkg.grantedPermissions) {
8534 serializer.startTag(null, "item");
8535 serializer.attribute(null, "name", name);
8536 serializer.endTag(null, "item");
8537 }
8538 }
8539 serializer.endTag(null, "perms");
8540 }
8541 if (pkg.disabledComponents.size() > 0) {
8542 serializer.startTag(null, "disabled-components");
8543 for (final String name : pkg.disabledComponents) {
8544 serializer.startTag(null, "item");
8545 serializer.attribute(null, "name", name);
8546 serializer.endTag(null, "item");
8547 }
8548 serializer.endTag(null, "disabled-components");
8549 }
8550 if (pkg.enabledComponents.size() > 0) {
8551 serializer.startTag(null, "enabled-components");
8552 for (final String name : pkg.enabledComponents) {
8553 serializer.startTag(null, "item");
8554 serializer.attribute(null, "name", name);
8555 serializer.endTag(null, "item");
8556 }
8557 serializer.endTag(null, "enabled-components");
8558 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008560 serializer.endTag(null, "package");
8561 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 void writePermission(XmlSerializer serializer, BasePermission bp)
8564 throws XmlPullParserException, java.io.IOException {
8565 if (bp.type != BasePermission.TYPE_BUILTIN
8566 && bp.sourcePackage != null) {
8567 serializer.startTag(null, "item");
8568 serializer.attribute(null, "name", bp.name);
8569 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008570 if (bp.protectionLevel !=
8571 PermissionInfo.PROTECTION_NORMAL) {
8572 serializer.attribute(null, "protection",
8573 Integer.toString(bp.protectionLevel));
8574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008575 if (DEBUG_SETTINGS) Log.v(TAG,
8576 "Writing perm: name=" + bp.name + " type=" + bp.type);
8577 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8578 PermissionInfo pi = bp.perm != null ? bp.perm.info
8579 : bp.pendingInfo;
8580 if (pi != null) {
8581 serializer.attribute(null, "type", "dynamic");
8582 if (pi.icon != 0) {
8583 serializer.attribute(null, "icon",
8584 Integer.toString(pi.icon));
8585 }
8586 if (pi.nonLocalizedLabel != null) {
8587 serializer.attribute(null, "label",
8588 pi.nonLocalizedLabel.toString());
8589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590 }
8591 }
8592 serializer.endTag(null, "item");
8593 }
8594 }
8595
8596 String getReadMessagesLP() {
8597 return mReadMessages.toString();
8598 }
8599
Oscar Montemayora8529f62009-11-18 10:14:20 -08008600 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8602 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008603 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008604 while(its.hasNext()) {
8605 String key = its.next();
8606 PackageSetting ps = mPackages.get(key);
8607 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008608 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008609 }
8610 }
8611 return ret;
8612 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008614 boolean readLP() {
8615 FileInputStream str = null;
8616 if (mBackupSettingsFilename.exists()) {
8617 try {
8618 str = new FileInputStream(mBackupSettingsFilename);
8619 mReadMessages.append("Reading from backup settings file\n");
8620 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008621 if (mSettingsFilename.exists()) {
8622 // If both the backup and settings file exist, we
8623 // ignore the settings since it might have been
8624 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008625 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008626 mSettingsFilename.delete();
8627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628 } catch (java.io.IOException e) {
8629 // We'll try for the normal settings file.
8630 }
8631 }
8632
8633 mPastSignatures.clear();
8634
8635 try {
8636 if (str == null) {
8637 if (!mSettingsFilename.exists()) {
8638 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008639 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 return false;
8641 }
8642 str = new FileInputStream(mSettingsFilename);
8643 }
8644 XmlPullParser parser = Xml.newPullParser();
8645 parser.setInput(str, null);
8646
8647 int type;
8648 while ((type=parser.next()) != XmlPullParser.START_TAG
8649 && type != XmlPullParser.END_DOCUMENT) {
8650 ;
8651 }
8652
8653 if (type != XmlPullParser.START_TAG) {
8654 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008655 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 return false;
8657 }
8658
8659 int outerDepth = parser.getDepth();
8660 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8661 && (type != XmlPullParser.END_TAG
8662 || parser.getDepth() > outerDepth)) {
8663 if (type == XmlPullParser.END_TAG
8664 || type == XmlPullParser.TEXT) {
8665 continue;
8666 }
8667
8668 String tagName = parser.getName();
8669 if (tagName.equals("package")) {
8670 readPackageLP(parser);
8671 } else if (tagName.equals("permissions")) {
8672 readPermissionsLP(mPermissions, parser);
8673 } else if (tagName.equals("permission-trees")) {
8674 readPermissionsLP(mPermissionTrees, parser);
8675 } else if (tagName.equals("shared-user")) {
8676 readSharedUserLP(parser);
8677 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008678 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008679 } else if (tagName.equals("preferred-activities")) {
8680 readPreferredActivitiesLP(parser);
8681 } else if(tagName.equals("updated-package")) {
8682 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008683 } else if (tagName.equals("cleaning-package")) {
8684 String name = parser.getAttributeValue(null, "name");
8685 if (name != null) {
8686 mPackagesToBeCleaned.add(name);
8687 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008688 } else if (tagName.equals("renamed-package")) {
8689 String nname = parser.getAttributeValue(null, "new");
8690 String oname = parser.getAttributeValue(null, "old");
8691 if (nname != null && oname != null) {
8692 mRenamedPackages.put(nname, oname);
8693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008694 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008695 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 + parser.getName());
8697 XmlUtils.skipCurrentTag(parser);
8698 }
8699 }
8700
8701 str.close();
8702
8703 } catch(XmlPullParserException e) {
8704 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008705 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706
8707 } catch(java.io.IOException e) {
8708 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008709 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008710
8711 }
8712
8713 int N = mPendingPackages.size();
8714 for (int i=0; i<N; i++) {
8715 final PendingPackage pp = mPendingPackages.get(i);
8716 Object idObj = getUserIdLP(pp.sharedId);
8717 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008718 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008719 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008720 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008721 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008722 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723 + pp.name);
8724 continue;
8725 }
8726 p.copyFrom(pp);
8727 } else if (idObj != null) {
8728 String msg = "Bad package setting: package " + pp.name
8729 + " has shared uid " + pp.sharedId
8730 + " that is not a shared uid\n";
8731 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008732 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008733 } else {
8734 String msg = "Bad package setting: package " + pp.name
8735 + " has shared uid " + pp.sharedId
8736 + " that is not defined\n";
8737 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008738 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008739 }
8740 }
8741 mPendingPackages.clear();
8742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008743 mReadMessages.append("Read completed successfully: "
8744 + mPackages.size() + " packages, "
8745 + mSharedUsers.size() + " shared uids\n");
8746
8747 return true;
8748 }
8749
8750 private int readInt(XmlPullParser parser, String ns, String name,
8751 int defValue) {
8752 String v = parser.getAttributeValue(ns, name);
8753 try {
8754 if (v == null) {
8755 return defValue;
8756 }
8757 return Integer.parseInt(v);
8758 } catch (NumberFormatException e) {
8759 reportSettingsProblem(Log.WARN,
8760 "Error in package manager settings: attribute " +
8761 name + " has bad integer value " + v + " at "
8762 + parser.getPositionDescription());
8763 }
8764 return defValue;
8765 }
8766
8767 private void readPermissionsLP(HashMap<String, BasePermission> out,
8768 XmlPullParser parser)
8769 throws IOException, XmlPullParserException {
8770 int outerDepth = parser.getDepth();
8771 int type;
8772 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8773 && (type != XmlPullParser.END_TAG
8774 || parser.getDepth() > outerDepth)) {
8775 if (type == XmlPullParser.END_TAG
8776 || type == XmlPullParser.TEXT) {
8777 continue;
8778 }
8779
8780 String tagName = parser.getName();
8781 if (tagName.equals("item")) {
8782 String name = parser.getAttributeValue(null, "name");
8783 String sourcePackage = parser.getAttributeValue(null, "package");
8784 String ptype = parser.getAttributeValue(null, "type");
8785 if (name != null && sourcePackage != null) {
8786 boolean dynamic = "dynamic".equals(ptype);
8787 BasePermission bp = new BasePermission(name, sourcePackage,
8788 dynamic
8789 ? BasePermission.TYPE_DYNAMIC
8790 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008791 bp.protectionLevel = readInt(parser, null, "protection",
8792 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008793 if (dynamic) {
8794 PermissionInfo pi = new PermissionInfo();
8795 pi.packageName = sourcePackage.intern();
8796 pi.name = name.intern();
8797 pi.icon = readInt(parser, null, "icon", 0);
8798 pi.nonLocalizedLabel = parser.getAttributeValue(
8799 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008800 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008801 bp.pendingInfo = pi;
8802 }
8803 out.put(bp.name, bp);
8804 } else {
8805 reportSettingsProblem(Log.WARN,
8806 "Error in package manager settings: permissions has"
8807 + " no name at " + parser.getPositionDescription());
8808 }
8809 } else {
8810 reportSettingsProblem(Log.WARN,
8811 "Unknown element reading permissions: "
8812 + parser.getName() + " at "
8813 + parser.getPositionDescription());
8814 }
8815 XmlUtils.skipCurrentTag(parser);
8816 }
8817 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008819 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008820 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008821 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008822 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008823 String codePathStr = parser.getAttributeValue(null, "codePath");
8824 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008825 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008826 resourcePathStr = codePathStr;
8827 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008828 String version = parser.getAttributeValue(null, "version");
8829 int versionCode = 0;
8830 if (version != null) {
8831 try {
8832 versionCode = Integer.parseInt(version);
8833 } catch (NumberFormatException e) {
8834 }
8835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008837 int pkgFlags = 0;
8838 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008839 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008840 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008841 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008842 String timeStampStr = parser.getAttributeValue(null, "ts");
8843 if (timeStampStr != null) {
8844 try {
8845 long timeStamp = Long.parseLong(timeStampStr);
8846 ps.setTimeStamp(timeStamp, timeStampStr);
8847 } catch (NumberFormatException e) {
8848 }
8849 }
8850 String idStr = parser.getAttributeValue(null, "userId");
8851 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8852 if(ps.userId <= 0) {
8853 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8854 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8855 }
8856 int outerDepth = parser.getDepth();
8857 int type;
8858 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8859 && (type != XmlPullParser.END_TAG
8860 || parser.getDepth() > outerDepth)) {
8861 if (type == XmlPullParser.END_TAG
8862 || type == XmlPullParser.TEXT) {
8863 continue;
8864 }
8865
8866 String tagName = parser.getName();
8867 if (tagName.equals("perms")) {
8868 readGrantedPermissionsLP(parser,
8869 ps.grantedPermissions);
8870 } else {
8871 reportSettingsProblem(Log.WARN,
8872 "Unknown element under <updated-package>: "
8873 + parser.getName());
8874 XmlUtils.skipCurrentTag(parser);
8875 }
8876 }
8877 mDisabledSysPackages.put(name, ps);
8878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008880 private void readPackageLP(XmlPullParser parser)
8881 throws XmlPullParserException, IOException {
8882 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008883 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008884 String idStr = null;
8885 String sharedIdStr = null;
8886 String codePathStr = null;
8887 String resourcePathStr = null;
8888 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008889 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008890 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008891 int pkgFlags = 0;
8892 String timeStampStr;
8893 long timeStamp = 0;
8894 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008895 String version = null;
8896 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008897 try {
8898 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008899 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008900 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008901 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008902 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8903 codePathStr = parser.getAttributeValue(null, "codePath");
8904 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008905 version = parser.getAttributeValue(null, "version");
8906 if (version != null) {
8907 try {
8908 versionCode = Integer.parseInt(version);
8909 } catch (NumberFormatException e) {
8910 }
8911 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008912 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008913
8914 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008916 try {
8917 pkgFlags = Integer.parseInt(systemStr);
8918 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008919 }
8920 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008921 // For backward compatibility
8922 systemStr = parser.getAttributeValue(null, "system");
8923 if (systemStr != null) {
8924 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8925 } else {
8926 // Old settings that don't specify system... just treat
8927 // them as system, good enough.
8928 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008930 }
8931 timeStampStr = parser.getAttributeValue(null, "ts");
8932 if (timeStampStr != null) {
8933 try {
8934 timeStamp = Long.parseLong(timeStampStr);
8935 } catch (NumberFormatException e) {
8936 }
8937 }
8938 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8939 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8940 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8941 if (resourcePathStr == null) {
8942 resourcePathStr = codePathStr;
8943 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008944 if (realName != null) {
8945 realName = realName.intern();
8946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947 if (name == null) {
8948 reportSettingsProblem(Log.WARN,
8949 "Error in package manager settings: <package> has no name at "
8950 + parser.getPositionDescription());
8951 } else if (codePathStr == null) {
8952 reportSettingsProblem(Log.WARN,
8953 "Error in package manager settings: <package> has no codePath at "
8954 + parser.getPositionDescription());
8955 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008956 packageSetting = addPackageLP(name.intern(), realName,
8957 new File(codePathStr), new File(resourcePathStr),
8958 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008959 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8960 + ": userId=" + userId + " pkg=" + packageSetting);
8961 if (packageSetting == null) {
8962 reportSettingsProblem(Log.ERROR,
8963 "Failure adding uid " + userId
8964 + " while parsing settings at "
8965 + parser.getPositionDescription());
8966 } else {
8967 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8968 }
8969 } else if (sharedIdStr != null) {
8970 userId = sharedIdStr != null
8971 ? Integer.parseInt(sharedIdStr) : 0;
8972 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008973 packageSetting = new PendingPackage(name.intern(), realName,
8974 new File(codePathStr), new File(resourcePathStr),
8975 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008976 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8977 mPendingPackages.add((PendingPackage) packageSetting);
8978 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8979 + ": sharedUserId=" + userId + " pkg="
8980 + packageSetting);
8981 } else {
8982 reportSettingsProblem(Log.WARN,
8983 "Error in package manager settings: package "
8984 + name + " has bad sharedId " + sharedIdStr
8985 + " at " + parser.getPositionDescription());
8986 }
8987 } else {
8988 reportSettingsProblem(Log.WARN,
8989 "Error in package manager settings: package "
8990 + name + " has bad userId " + idStr + " at "
8991 + parser.getPositionDescription());
8992 }
8993 } catch (NumberFormatException e) {
8994 reportSettingsProblem(Log.WARN,
8995 "Error in package manager settings: package "
8996 + name + " has bad userId " + idStr + " at "
8997 + parser.getPositionDescription());
8998 }
8999 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009000 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009001 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009002 final String enabledStr = parser.getAttributeValue(null, "enabled");
9003 if (enabledStr != null) {
9004 if (enabledStr.equalsIgnoreCase("true")) {
9005 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9006 } else if (enabledStr.equalsIgnoreCase("false")) {
9007 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9008 } else if (enabledStr.equalsIgnoreCase("default")) {
9009 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9010 } else {
9011 reportSettingsProblem(Log.WARN,
9012 "Error in package manager settings: package "
9013 + name + " has bad enabled value: " + idStr
9014 + " at " + parser.getPositionDescription());
9015 }
9016 } else {
9017 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9018 }
9019 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9020 if (installStatusStr != null) {
9021 if (installStatusStr.equalsIgnoreCase("false")) {
9022 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9023 } else {
9024 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9025 }
9026 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 int outerDepth = parser.getDepth();
9029 int type;
9030 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9031 && (type != XmlPullParser.END_TAG
9032 || parser.getDepth() > outerDepth)) {
9033 if (type == XmlPullParser.END_TAG
9034 || type == XmlPullParser.TEXT) {
9035 continue;
9036 }
9037
9038 String tagName = parser.getName();
9039 if (tagName.equals("disabled-components")) {
9040 readDisabledComponentsLP(packageSetting, parser);
9041 } else if (tagName.equals("enabled-components")) {
9042 readEnabledComponentsLP(packageSetting, parser);
9043 } else if (tagName.equals("sigs")) {
9044 packageSetting.signatures.readXml(parser, mPastSignatures);
9045 } else if (tagName.equals("perms")) {
9046 readGrantedPermissionsLP(parser,
9047 packageSetting.loadedPermissions);
9048 packageSetting.permissionsFixed = true;
9049 } else {
9050 reportSettingsProblem(Log.WARN,
9051 "Unknown element under <package>: "
9052 + parser.getName());
9053 XmlUtils.skipCurrentTag(parser);
9054 }
9055 }
9056 } else {
9057 XmlUtils.skipCurrentTag(parser);
9058 }
9059 }
9060
9061 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9062 XmlPullParser parser)
9063 throws IOException, XmlPullParserException {
9064 int outerDepth = parser.getDepth();
9065 int type;
9066 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9067 && (type != XmlPullParser.END_TAG
9068 || parser.getDepth() > outerDepth)) {
9069 if (type == XmlPullParser.END_TAG
9070 || type == XmlPullParser.TEXT) {
9071 continue;
9072 }
9073
9074 String tagName = parser.getName();
9075 if (tagName.equals("item")) {
9076 String name = parser.getAttributeValue(null, "name");
9077 if (name != null) {
9078 packageSetting.disabledComponents.add(name.intern());
9079 } else {
9080 reportSettingsProblem(Log.WARN,
9081 "Error in package manager settings: <disabled-components> has"
9082 + " no name at " + parser.getPositionDescription());
9083 }
9084 } else {
9085 reportSettingsProblem(Log.WARN,
9086 "Unknown element under <disabled-components>: "
9087 + parser.getName());
9088 }
9089 XmlUtils.skipCurrentTag(parser);
9090 }
9091 }
9092
9093 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9094 XmlPullParser parser)
9095 throws IOException, XmlPullParserException {
9096 int outerDepth = parser.getDepth();
9097 int type;
9098 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9099 && (type != XmlPullParser.END_TAG
9100 || parser.getDepth() > outerDepth)) {
9101 if (type == XmlPullParser.END_TAG
9102 || type == XmlPullParser.TEXT) {
9103 continue;
9104 }
9105
9106 String tagName = parser.getName();
9107 if (tagName.equals("item")) {
9108 String name = parser.getAttributeValue(null, "name");
9109 if (name != null) {
9110 packageSetting.enabledComponents.add(name.intern());
9111 } else {
9112 reportSettingsProblem(Log.WARN,
9113 "Error in package manager settings: <enabled-components> has"
9114 + " no name at " + parser.getPositionDescription());
9115 }
9116 } else {
9117 reportSettingsProblem(Log.WARN,
9118 "Unknown element under <enabled-components>: "
9119 + parser.getName());
9120 }
9121 XmlUtils.skipCurrentTag(parser);
9122 }
9123 }
9124
9125 private void readSharedUserLP(XmlPullParser parser)
9126 throws XmlPullParserException, IOException {
9127 String name = null;
9128 String idStr = null;
9129 int pkgFlags = 0;
9130 SharedUserSetting su = null;
9131 try {
9132 name = parser.getAttributeValue(null, "name");
9133 idStr = parser.getAttributeValue(null, "userId");
9134 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9135 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9136 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9137 }
9138 if (name == null) {
9139 reportSettingsProblem(Log.WARN,
9140 "Error in package manager settings: <shared-user> has no name at "
9141 + parser.getPositionDescription());
9142 } else if (userId == 0) {
9143 reportSettingsProblem(Log.WARN,
9144 "Error in package manager settings: shared-user "
9145 + name + " has bad userId " + idStr + " at "
9146 + parser.getPositionDescription());
9147 } else {
9148 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9149 reportSettingsProblem(Log.ERROR,
9150 "Occurred while parsing settings at "
9151 + parser.getPositionDescription());
9152 }
9153 }
9154 } catch (NumberFormatException e) {
9155 reportSettingsProblem(Log.WARN,
9156 "Error in package manager settings: package "
9157 + name + " has bad userId " + idStr + " at "
9158 + parser.getPositionDescription());
9159 };
9160
9161 if (su != null) {
9162 int outerDepth = parser.getDepth();
9163 int type;
9164 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9165 && (type != XmlPullParser.END_TAG
9166 || parser.getDepth() > outerDepth)) {
9167 if (type == XmlPullParser.END_TAG
9168 || type == XmlPullParser.TEXT) {
9169 continue;
9170 }
9171
9172 String tagName = parser.getName();
9173 if (tagName.equals("sigs")) {
9174 su.signatures.readXml(parser, mPastSignatures);
9175 } else if (tagName.equals("perms")) {
9176 readGrantedPermissionsLP(parser, su.loadedPermissions);
9177 } else {
9178 reportSettingsProblem(Log.WARN,
9179 "Unknown element under <shared-user>: "
9180 + parser.getName());
9181 XmlUtils.skipCurrentTag(parser);
9182 }
9183 }
9184
9185 } else {
9186 XmlUtils.skipCurrentTag(parser);
9187 }
9188 }
9189
9190 private void readGrantedPermissionsLP(XmlPullParser parser,
9191 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9192 int outerDepth = parser.getDepth();
9193 int type;
9194 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9195 && (type != XmlPullParser.END_TAG
9196 || parser.getDepth() > outerDepth)) {
9197 if (type == XmlPullParser.END_TAG
9198 || type == XmlPullParser.TEXT) {
9199 continue;
9200 }
9201
9202 String tagName = parser.getName();
9203 if (tagName.equals("item")) {
9204 String name = parser.getAttributeValue(null, "name");
9205 if (name != null) {
9206 outPerms.add(name.intern());
9207 } else {
9208 reportSettingsProblem(Log.WARN,
9209 "Error in package manager settings: <perms> has"
9210 + " no name at " + parser.getPositionDescription());
9211 }
9212 } else {
9213 reportSettingsProblem(Log.WARN,
9214 "Unknown element under <perms>: "
9215 + parser.getName());
9216 }
9217 XmlUtils.skipCurrentTag(parser);
9218 }
9219 }
9220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009221 private void readPreferredActivitiesLP(XmlPullParser parser)
9222 throws XmlPullParserException, IOException {
9223 int outerDepth = parser.getDepth();
9224 int type;
9225 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9226 && (type != XmlPullParser.END_TAG
9227 || parser.getDepth() > outerDepth)) {
9228 if (type == XmlPullParser.END_TAG
9229 || type == XmlPullParser.TEXT) {
9230 continue;
9231 }
9232
9233 String tagName = parser.getName();
9234 if (tagName.equals("item")) {
9235 PreferredActivity pa = new PreferredActivity(parser);
9236 if (pa.mParseError == null) {
9237 mPreferredActivities.addFilter(pa);
9238 } else {
9239 reportSettingsProblem(Log.WARN,
9240 "Error in package manager settings: <preferred-activity> "
9241 + pa.mParseError + " at "
9242 + parser.getPositionDescription());
9243 }
9244 } else {
9245 reportSettingsProblem(Log.WARN,
9246 "Unknown element under <preferred-activities>: "
9247 + parser.getName());
9248 XmlUtils.skipCurrentTag(parser);
9249 }
9250 }
9251 }
9252
9253 // Returns -1 if we could not find an available UserId to assign
9254 private int newUserIdLP(Object obj) {
9255 // Let's be stupidly inefficient for now...
9256 final int N = mUserIds.size();
9257 for (int i=0; i<N; i++) {
9258 if (mUserIds.get(i) == null) {
9259 mUserIds.set(i, obj);
9260 return FIRST_APPLICATION_UID + i;
9261 }
9262 }
9263
9264 // None left?
9265 if (N >= MAX_APPLICATION_UIDS) {
9266 return -1;
9267 }
9268
9269 mUserIds.add(obj);
9270 return FIRST_APPLICATION_UID + N;
9271 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009273 public PackageSetting getDisabledSystemPkg(String name) {
9274 synchronized(mPackages) {
9275 PackageSetting ps = mDisabledSysPackages.get(name);
9276 return ps;
9277 }
9278 }
9279
9280 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9281 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9282 if (Config.LOGV) {
9283 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9284 + " componentName = " + componentInfo.name);
9285 Log.v(TAG, "enabledComponents: "
9286 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9287 Log.v(TAG, "disabledComponents: "
9288 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9289 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009290 if (packageSettings == null) {
9291 if (false) {
9292 Log.w(TAG, "WAITING FOR DEBUGGER");
9293 Debug.waitForDebugger();
9294 Log.i(TAG, "We will crash!");
9295 }
9296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9298 || ((componentInfo.enabled
9299 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9300 || (componentInfo.applicationInfo.enabled
9301 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9302 && !packageSettings.disabledComponents.contains(componentInfo.name))
9303 || packageSettings.enabledComponents.contains(componentInfo.name));
9304 }
9305 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009306
9307 // ------- apps on sdcard specific code -------
9308 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009309 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009310 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009311 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009312 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009313
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009314 private String getEncryptKey() {
9315 try {
9316 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9317 if (sdEncKey == null) {
9318 sdEncKey = SystemKeyStore.getInstance().
9319 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9320 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009321 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009322 return null;
9323 }
9324 }
9325 return sdEncKey;
9326 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009327 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009328 return null;
9329 }
9330 }
9331
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009332 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009333 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009334 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009335 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009336 if (list != null) {
9337 int idx = 0;
9338 int idList[] = new int[MAX_CONTAINERS];
9339 boolean neverFound = true;
9340 for (String name : list) {
9341 // Ignore null entries
9342 if (name == null) {
9343 continue;
9344 }
9345 int sidx = name.indexOf(prefix);
9346 if (sidx == -1) {
9347 // Not a temp file. just ignore
9348 continue;
9349 }
9350 String subStr = name.substring(sidx + prefix.length());
9351 idList[idx] = -1;
9352 if (subStr != null) {
9353 try {
9354 int cid = Integer.parseInt(subStr);
9355 idList[idx++] = cid;
9356 neverFound = false;
9357 } catch (NumberFormatException e) {
9358 }
9359 }
9360 }
9361 if (!neverFound) {
9362 // Sort idList
9363 Arrays.sort(idList);
9364 for (int j = 1; j <= idList.length; j++) {
9365 if (idList[j-1] != j) {
9366 tmpIdx = j;
9367 break;
9368 }
9369 }
9370 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009371 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009372 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009373 }
9374
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009375 /*
9376 * Return true if PackageManager does have packages to be updated.
9377 */
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009378 public boolean updateExternalMediaStatus(final boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009379 final boolean ret;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009380 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009381 Log.i(TAG, "Updating external media status from " +
9382 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9383 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009384 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9385 mediaStatus+", mMediaMounted=" + mMediaMounted);
9386 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009387 return false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009388 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009389 mMediaMounted = mediaStatus;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009390 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_EXTERNAL_STORAGE);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009391 ret = appList != null && appList.size() > 0;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009392 if (DEBUG_SD_INSTALL) {
9393 if (appList != null) {
9394 for (String app : appList) {
9395 Log.i(TAG, "Should enable " + app + " on sdcard");
9396 }
9397 }
9398 }
9399 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus returning " + ret);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009400 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009401 // Queue up an async operation since the package installation may take a little while.
9402 mHandler.post(new Runnable() {
9403 public void run() {
9404 mHandler.removeCallbacks(this);
9405 updateExternalMediaStatusInner(mediaStatus, ret);
9406 }
9407 });
9408 return ret;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009409 }
9410
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009411 private void updateExternalMediaStatusInner(boolean mediaStatus,
9412 boolean sendUpdateBroadcast) {
9413 // If we are up here that means there are packages to be
9414 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009415 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009416 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009417 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009418 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009419 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009420
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009421 int uidList[] = new int[list.length];
9422 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009423 HashSet<String> removeCids = new HashSet<String>();
9424 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009425 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009426 for (String cid : list) {
9427 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009428 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9429 boolean failed = true;
9430 try {
9431 String pkgName = args.getPackageName();
9432 if (pkgName == null) {
9433 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009434 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009435 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9436 PackageSetting ps = mSettings.mPackages.get(pkgName);
9437 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009438 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009439 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9440 " corresponds to pkg : " + pkgName +
9441 " at code path: " + ps.codePathString);
9442 // We do have a valid package installed on sdcard
9443 processCids.put(args, ps.codePathString);
9444 failed = false;
9445 int uid = ps.userId;
9446 if (uid != -1) {
9447 uidList[num++] = uid;
9448 }
9449 }
9450 } finally {
9451 if (failed) {
9452 // Stale container on sdcard. Just delete
9453 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9454 removeCids.add(cid);
9455 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009456 }
9457 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009458 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009459 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009460 int uidArr[] = null;
9461 if (num > 0) {
9462 // Sort uid list
9463 Arrays.sort(uidList, 0, num);
9464 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009465 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009466 uidArr[0] = uidList[0];
9467 int di = 0;
9468 for (int i = 1; i < num; i++) {
9469 if (uidList[i-1] != uidList[i]) {
9470 uidArr[di++] = uidList[i];
9471 }
9472 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009473 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009474 // Process packages with valid entries.
9475 if (mediaStatus) {
9476 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
9477 loadMediaPackages(processCids, uidArr, sendUpdateBroadcast, removeCids);
9478 startCleaningPackages();
9479 } else {
9480 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
9481 unloadMediaPackages(processCids, uidArr, sendUpdateBroadcast);
9482 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009483 }
9484
9485 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9486 ArrayList<String> pkgList, int uidArr[]) {
9487 int size = pkgList.size();
9488 if (size > 0) {
9489 // Send broadcasts here
9490 Bundle extras = new Bundle();
9491 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9492 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009493 if (uidArr != null) {
9494 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9495 }
9496 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9497 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009498 sendPackageBroadcast(action, null, extras);
9499 }
9500 }
9501
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009502 /*
9503 * Look at potentially valid container ids from processCids
9504 * If package information doesn't match the one on record
9505 * or package scanning fails, the cid is added to list of
9506 * removeCids and cleaned up. Since cleaning up containers
9507 * involves destroying them, we do not want any parse
9508 * references to such stale containers. So force gc's
9509 * to avoid unnecessary crashes.
9510 */
9511 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9512 int uidArr[], boolean sendUpdateBroadcast,
9513 HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009514 ArrayList<String> pkgList = new ArrayList<String>();
9515 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009516 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009517 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009518 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009519 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9520 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009521 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009522 try {
9523 // Make sure there are no container errors first.
9524 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9525 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009526 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009527 " when installing from sdcard");
9528 continue;
9529 }
9530 // Check code path here.
9531 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009532 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009533 " does not match one in settings " + codePath);
9534 continue;
9535 }
9536 // Parse package
9537 int parseFlags = PackageParser.PARSE_CHATTY |
9538 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9539 PackageParser pp = new PackageParser(codePath);
9540 pp.setSeparateProcesses(mSeparateProcesses);
9541 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9542 codePath, mMetrics, parseFlags);
9543 pp = null;
9544 doGc = true;
9545 // Check for parse errors
9546 if (pkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009547 Slog.e(TAG, "Parse error when installing install pkg : "
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009548 + args.cid + " from " + args.cachePath);
9549 continue;
9550 }
9551 setApplicationInfoPaths(pkg, codePath, codePath);
9552 synchronized (mInstallLock) {
9553 // Scan the package
9554 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9555 synchronized (mPackages) {
Suchi Amalapurapuebb83ad2010-03-19 11:55:29 -07009556 updatePermissionsLP(pkg.packageName, pkg,
9557 pkg.permissions.size() > 0, false);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009558 retCode = PackageManager.INSTALL_SUCCEEDED;
9559 pkgList.add(pkg.packageName);
9560 // Post process args
9561 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9562 }
9563 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009564 Slog.i(TAG, "Failed to install pkg: " +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009565 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009566 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009567 }
9568
9569 } finally {
9570 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9571 // Don't destroy container here. Wait till gc clears things up.
9572 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009573 }
9574 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009575 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009576 synchronized (mPackages) {
9577 // Persist settings
9578 mSettings.writeLP();
9579 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009580 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009581 if (sendUpdateBroadcast) {
9582 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9583 }
9584 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009585 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009586 }
9587 // Delete any stale containers if needed.
9588 if (removeCids != null) {
9589 for (String cid : removeCids) {
9590 Log.i(TAG, "Destroying stale container : " + cid);
9591 PackageHelper.destroySdDir(cid);
9592 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009593 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009594 }
9595
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009596 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9597 int uidArr[], boolean sendUpdateBroadcast) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009598 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009599 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009600 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009601 Set<SdInstallArgs> keys = processCids.keySet();
9602 for (SdInstallArgs args : keys) {
9603 String cid = args.cid;
9604 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009605 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009606 // Delete package internally
9607 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9608 synchronized (mInstallLock) {
9609 boolean res = deletePackageLI(pkgName, false,
9610 PackageManager.DONT_DELETE_DATA, outInfo);
9611 if (res) {
9612 pkgList.add(pkgName);
9613 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009614 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009615 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009616 }
9617 }
9618 }
9619 // Send broadcasts
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009620 if (sendUpdateBroadcast) {
9621 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009622 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009623 // Force gc
9624 Runtime.getRuntime().gc();
9625 // Just unmount all valid containers.
9626 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009627 synchronized (mInstallLock) {
9628 args.doPostDeleteLI(false);
9629 }
9630 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009631 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009632
9633 public void movePackage(final String packageName,
9634 final IPackageMoveObserver observer, final int flags) {
9635 if (packageName == null) {
9636 return;
9637 }
9638 mContext.enforceCallingOrSelfPermission(
9639 android.Manifest.permission.MOVE_PACKAGE, null);
9640 int returnCode = PackageManager.MOVE_SUCCEEDED;
9641 int currFlags = 0;
9642 int newFlags = 0;
9643 synchronized (mPackages) {
9644 PackageParser.Package pkg = mPackages.get(packageName);
9645 if (pkg == null) {
9646 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9647 }
9648 // Disable moving fwd locked apps and system packages
9649 if (pkg.applicationInfo != null &&
9650 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009651 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009652 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9653 } else if (pkg.applicationInfo != null &&
9654 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009655 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009656 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9657 } else {
9658 // Find install location first
9659 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9660 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009661 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009662 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9663 } else {
9664 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9665 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009666 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009667 PackageManager.INSTALL_EXTERNAL : 0;
9668 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009669 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009670 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9671 }
9672 }
9673 }
9674 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9675 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9676 } else {
9677 Message msg = mHandler.obtainMessage(INIT_COPY);
9678 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9679 pkg.applicationInfo.publicSourceDir);
9680 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9681 packageName);
9682 msg.obj = mp;
9683 mHandler.sendMessage(msg);
9684 }
9685 }
9686 }
9687
9688 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9689 // Queue up an async operation since the package deletion may take a little while.
9690 mHandler.post(new Runnable() {
9691 public void run() {
9692 mHandler.removeCallbacks(this);
9693 int returnCode = currentStatus;
9694 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9695 if (moveSucceeded) {
9696 int uid = -1;
9697 synchronized (mPackages) {
9698 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9699 }
9700 ArrayList<String> pkgList = new ArrayList<String>();
9701 pkgList.add(mp.packageName);
9702 int uidArr[] = new int[] { uid };
9703 // Send resources unavailable broadcast
9704 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9705
9706 // Update package code and resource paths
9707 synchronized (mPackages) {
9708 PackageParser.Package pkg = mPackages.get(mp.packageName);
9709 if (pkg != null) {
9710 String oldCodePath = pkg.mPath;
9711 String newCodePath = mp.targetArgs.getCodePath();
9712 String newResPath = mp.targetArgs.getResourcePath();
9713 pkg.mPath = newCodePath;
9714 // Move dex files around
9715 if (moveDexFiles(pkg)
9716 != PackageManager.INSTALL_SUCCEEDED) {
9717 // Moving of dex files failed. Set
9718 // error code and abort move.
9719 pkg.mPath = pkg.mScanPath;
9720 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9721 moveSucceeded = false;
9722 } else {
9723 pkg.mScanPath = newCodePath;
9724 pkg.applicationInfo.sourceDir = newCodePath;
9725 pkg.applicationInfo.publicSourceDir = newResPath;
9726 PackageSetting ps = (PackageSetting) pkg.mExtras;
9727 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9728 ps.codePathString = ps.codePath.getPath();
9729 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9730 ps.resourcePathString = ps.resourcePath.getPath();
9731 // Set the application info flag correctly.
9732 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009733 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009734 } else {
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009735 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009736 }
9737 ps.setFlags(pkg.applicationInfo.flags);
9738 mAppDirs.remove(oldCodePath);
9739 mAppDirs.put(newCodePath, pkg);
9740 // Persist settings
9741 mSettings.writeLP();
9742 }
9743 }
9744 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009745 // Send resources available broadcast
9746 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009747 }
9748 if (!moveSucceeded){
9749 // Clean up failed installation
9750 if (mp.targetArgs != null) {
9751 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009752 returnCode);
9753 }
9754 } else {
9755 // Force a gc to clear things up.
9756 Runtime.getRuntime().gc();
9757 // Delete older code
9758 synchronized (mInstallLock) {
9759 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009760 }
9761 }
9762 IPackageMoveObserver observer = mp.observer;
9763 if (observer != null) {
9764 try {
9765 observer.packageMoved(mp.packageName, returnCode);
9766 } catch (RemoteException e) {
9767 Log.i(TAG, "Observer no longer exists.");
9768 }
9769 }
9770 }
9771 });
9772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009773}