blob: a1a703f5b7d32042761b008d6d38ad9ecec05b40 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080021import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080022import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070023import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080024import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080032import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080033import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070038import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080039import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.pm.ActivityInfo;
42import android.content.pm.ApplicationInfo;
43import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070044import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.IPackageDataObserver;
46import android.content.pm.IPackageDeleteObserver;
47import android.content.pm.IPackageInstallObserver;
48import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080049import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.content.pm.IPackageStatsObserver;
51import android.content.pm.InstrumentationInfo;
52import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080053import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.content.pm.PackageManager;
55import android.content.pm.PackageStats;
56import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.pm.PackageParser;
60import android.content.pm.PermissionInfo;
61import android.content.pm.PermissionGroupInfo;
62import android.content.pm.ProviderInfo;
63import android.content.pm.ResolveInfo;
64import android.content.pm.ServiceInfo;
65import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.Uri;
67import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070068import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080070import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080072import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070073import android.os.Looper;
74import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Parcel;
76import android.os.RemoteException;
77import android.os.Environment;
78import android.os.FileObserver;
79import android.os.FileUtils;
80import android.os.Handler;
81import android.os.ParcelFileDescriptor;
82import android.os.Process;
83import android.os.ServiceManager;
84import android.os.SystemClock;
85import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080086import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.util.*;
88import android.view.Display;
89import android.view.WindowManager;
90
91import java.io.File;
92import java.io.FileDescriptor;
93import java.io.FileInputStream;
94import java.io.FileNotFoundException;
95import java.io.FileOutputStream;
96import java.io.FileReader;
97import java.io.FilenameFilter;
98import java.io.IOException;
99import java.io.InputStream;
100import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800101import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800102import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.util.ArrayList;
104import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700105import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.Collections;
107import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800108import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.Enumeration;
110import java.util.HashMap;
111import java.util.HashSet;
112import java.util.Iterator;
113import java.util.List;
114import java.util.Map;
115import java.util.Set;
116import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800117import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.zip.ZipFile;
119import java.util.zip.ZipOutputStream;
120
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700121/**
122 * Keep track of all those .apks everywhere.
123 *
124 * This is very central to the platform's security; please run the unit
125 * tests whenever making modifications here:
126 *
127mmm frameworks/base/tests/AndroidTests
128adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
129adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
130 *
131 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132class PackageManagerService extends IPackageManager.Stub {
133 private static final String TAG = "PackageManager";
134 private static final boolean DEBUG_SETTINGS = false;
135 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800136 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800137 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
139 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
140 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400141 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 private static final int FIRST_APPLICATION_UID =
143 Process.FIRST_APPLICATION_UID;
144 private static final int MAX_APPLICATION_UIDS = 1000;
145
146 private static final boolean SHOW_INFO = false;
147
148 private static final boolean GET_CERTIFICATES = true;
149
Oscar Montemayora8529f62009-11-18 10:14:20 -0800150 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 private static final int REMOVE_EVENTS =
153 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
154 private static final int ADD_EVENTS =
155 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
156
157 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800158 // Suffix used during package installation when copying/moving
159 // package apks to install directory.
160 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800162 /**
163 * Indicates the state of installation. Used by PackageManager to
164 * figure out incomplete installations. Say a package is being installed
165 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
166 * the package installation is successful or unsuccesful lin which case
167 * the PackageManager will no longer maintain state information associated
168 * with the package. If some exception(like device freeze or battery being
169 * pulled out) occurs during installation of a package, the PackageManager
170 * needs this information to clean up the previously failed installation.
171 */
172 private static final int PKG_INSTALL_INCOMPLETE = 0;
173 private static final int PKG_INSTALL_COMPLETE = 1;
174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final int SCAN_MONITOR = 1<<0;
176 static final int SCAN_NO_DEX = 1<<1;
177 static final int SCAN_FORCE_DEX = 1<<2;
178 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800179 static final int SCAN_NEW_INSTALL = 1<<4;
180 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800182 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
183 "com.android.defcontainer",
184 "com.android.defcontainer.DefaultContainerService");
185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
187 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700188 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
Dianne Hackborn851a5412009-05-08 12:06:44 -0700190 final int mSdkVersion = Build.VERSION.SDK_INT;
191 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
192 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 final Context mContext;
195 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700196 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 final DisplayMetrics mMetrics;
198 final int mDefParseFlags;
199 final String[] mSeparateProcesses;
200
201 // This is where all application persistent data goes.
202 final File mAppDataDir;
203
Oscar Montemayora8529f62009-11-18 10:14:20 -0800204 // If Encrypted File System feature is enabled, all application persistent data
205 // should go here instead.
206 final File mSecureAppDataDir;
207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 // This is the object monitoring the framework dir.
209 final FileObserver mFrameworkInstallObserver;
210
211 // This is the object monitoring the system app dir.
212 final FileObserver mSystemInstallObserver;
213
214 // This is the object monitoring mAppInstallDir.
215 final FileObserver mAppInstallObserver;
216
217 // This is the object monitoring mDrmAppPrivateInstallDir.
218 final FileObserver mDrmAppInstallObserver;
219
220 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
221 // LOCK HELD. Can be called with mInstallLock held.
222 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 final File mFrameworkDir;
225 final File mSystemAppDir;
226 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700227 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228
229 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
230 // apps.
231 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 // Lock for state used when installing and doing other long running
236 // operations. Methods that must be called with this lock held have
237 // the prefix "LI".
238 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // These are the directories in the 3rd party applications installed dir
241 // that we have currently loaded packages from. Keys are the application's
242 // installed zip file (absolute codePath), and values are Package.
243 final HashMap<String, PackageParser.Package> mAppDirs =
244 new HashMap<String, PackageParser.Package>();
245
246 // Information for the parser to write more useful error messages.
247 File mScanningPath;
248 int mLastScanError;
249
250 final int[] mOutPermissions = new int[3];
251
252 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 // Keys are String (package name), values are Package. This also serves
255 // as the lock for the global state. Methods that must be called with
256 // this lock held have the prefix "LP".
257 final HashMap<String, PackageParser.Package> mPackages =
258 new HashMap<String, PackageParser.Package>();
259
260 final Settings mSettings;
261 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262
263 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
264 int[] mGlobalGids;
265
266 // These are the built-in uid -> permission mappings that were read from the
267 // etc/permissions.xml file.
268 final SparseArray<HashSet<String>> mSystemPermissions =
269 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 // These are the built-in shared libraries that were read from the
272 // etc/permissions.xml file.
273 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800274
Dianne Hackborn49237342009-08-27 20:08:01 -0700275 // Temporary for building the final shared libraries for an .apk.
276 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800277
Dianne Hackborn49237342009-08-27 20:08:01 -0700278 // These are the features this devices supports that were read from the
279 // etc/permissions.xml file.
280 final HashMap<String, FeatureInfo> mAvailableFeatures =
281 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 // All available activities, for your resolving pleasure.
284 final ActivityIntentResolver mActivities =
285 new ActivityIntentResolver();
286
287 // All available receivers, for your resolving pleasure.
288 final ActivityIntentResolver mReceivers =
289 new ActivityIntentResolver();
290
291 // All available services, for your resolving pleasure.
292 final ServiceIntentResolver mServices = new ServiceIntentResolver();
293
294 // Keys are String (provider class name), values are Provider.
295 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
296 new HashMap<ComponentName, PackageParser.Provider>();
297
298 // Mapping from provider base names (first directory in content URI codePath)
299 // to the provider information.
300 final HashMap<String, PackageParser.Provider> mProviders =
301 new HashMap<String, PackageParser.Provider>();
302
303 // Mapping from instrumentation class names to info about them.
304 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
305 new HashMap<ComponentName, PackageParser.Instrumentation>();
306
307 // Mapping from permission names to info about them.
308 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
309 new HashMap<String, PackageParser.PermissionGroup>();
310
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800311 // Packages whose data we have transfered into another package, thus
312 // should no longer exist.
313 final HashSet<String> mTransferedPackages = new HashSet<String>();
314
Dianne Hackborn854060af2009-07-09 18:14:31 -0700315 // Broadcast actions that are only available to the system.
316 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 boolean mSystemReady;
319 boolean mSafeMode;
320 boolean mHasSystemUidErrors;
321
322 ApplicationInfo mAndroidApplication;
323 final ActivityInfo mResolveActivity = new ActivityInfo();
324 final ResolveInfo mResolveInfo = new ResolveInfo();
325 ComponentName mResolveComponentName;
326 PackageParser.Package mPlatformPackage;
327
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700328 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800329 final HashMap<String, ArrayList<String>> mPendingBroadcasts
330 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800331 // Service Connection to remote media container service to copy
332 // package uri's from external media onto secure containers
333 // or internal storage.
334 private IMediaContainerService mContainerService = null;
335
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700336 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800337 static final int MCS_BOUND = 3;
338 static final int END_COPY = 4;
339 static final int INIT_COPY = 5;
340 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800341 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800342 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800343 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800344 static final int MCS_RECONNECT = 10;
345 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700346 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700347 static final int WRITE_SETTINGS = 13;
348
349 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800350
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700351 // Delay time in millisecs
352 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800353 final private DefaultContainerConnection mDefContainerConn =
354 new DefaultContainerConnection();
355 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800356 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800357 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800358 IMediaContainerService imcs =
359 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800360 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800361 }
362
363 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800364 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800365 }
366 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700367
Christopher Tate1bb69062010-02-19 17:02:12 -0800368 // Recordkeeping of restore-after-install operations that are currently in flight
369 // between the Package Manager and the Backup Manager
370 class PostInstallData {
371 public InstallArgs args;
372 public PackageInstalledInfo res;
373
374 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
375 args = _a;
376 res = _r;
377 }
378 };
379 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
380 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
381
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700382 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800383 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800384 final ArrayList<HandlerParams> mPendingInstalls =
385 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800386
387 private boolean connectToService() {
388 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
389 " DefaultContainerService");
390 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700391 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800392 if (mContext.bindService(service, mDefContainerConn,
393 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700394 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800395 mBound = true;
396 return true;
397 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700398 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800399 return false;
400 }
401
402 private void disconnectService() {
403 mContainerService = null;
404 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700405 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800406 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700407 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800408 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800409
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700410 PackageHandler(Looper looper) {
411 super(looper);
412 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700413
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700414 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700415 try {
416 doHandleMessage(msg);
417 } finally {
418 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
419 }
420 }
421
422 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700423 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800424 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800425 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800426 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800427 int idx = mPendingInstalls.size();
428 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
429 // If a bind was already initiated we dont really
430 // need to do anything. The pending install
431 // will be processed later on.
432 if (!mBound) {
433 // If this is the only one pending we might
434 // have to bind to the service again.
435 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800436 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800437 params.serviceError();
438 return;
439 } else {
440 // Once we bind to the service, the first
441 // pending request will be processed.
442 mPendingInstalls.add(idx, params);
443 }
444 } else {
445 mPendingInstalls.add(idx, params);
446 // Already bound to the service. Just make
447 // sure we trigger off processing the first request.
448 if (idx == 0) {
449 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800450 }
451 }
452 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800453 }
454 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800455 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800456 if (msg.obj != null) {
457 mContainerService = (IMediaContainerService) msg.obj;
458 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800459 if (mContainerService == null) {
460 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800461 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800462 for (HandlerParams params : mPendingInstalls) {
463 mPendingInstalls.remove(0);
464 // Indicate service bind error
465 params.serviceError();
466 }
467 mPendingInstalls.clear();
468 } else if (mPendingInstalls.size() > 0) {
469 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800470 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800471 params.startCopy();
472 }
473 } else {
474 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800475 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800476 }
477 break;
478 }
479 case MCS_RECONNECT : {
480 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
481 if (mPendingInstalls.size() > 0) {
482 if (mBound) {
483 disconnectService();
484 }
485 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800486 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800487 for (HandlerParams params : mPendingInstalls) {
488 mPendingInstalls.remove(0);
489 // Indicate service bind error
490 params.serviceError();
491 }
492 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800493 }
494 }
495 break;
496 }
497 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800498 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
499 // Delete pending install
500 if (mPendingInstalls.size() > 0) {
501 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800502 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800503 if (mPendingInstalls.size() == 0) {
504 if (mBound) {
505 disconnectService();
506 }
507 } else {
508 // There are more pending requests in queue.
509 // Just post MCS_BOUND message to trigger processing
510 // of next pending install.
511 mHandler.sendEmptyMessage(MCS_BOUND);
512 }
513 break;
514 }
515 case MCS_GIVE_UP: {
516 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
517 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800518 break;
519 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700520 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800521 String packages[];
522 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700523 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700524 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700525 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700526 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800527 if (mPendingBroadcasts == null) {
528 return;
529 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700530 size = mPendingBroadcasts.size();
531 if (size <= 0) {
532 // Nothing to be done. Just return
533 return;
534 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800535 packages = new String[size];
536 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700537 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800538 Iterator<HashMap.Entry<String, ArrayList<String>>>
539 it = mPendingBroadcasts.entrySet().iterator();
540 int i = 0;
541 while (it.hasNext() && i < size) {
542 HashMap.Entry<String, ArrayList<String>> ent = it.next();
543 packages[i] = ent.getKey();
544 components[i] = ent.getValue();
545 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700546 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800547 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700548 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800549 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700550 mPendingBroadcasts.clear();
551 }
552 // Send broadcasts
553 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800554 sendPackageChangedBroadcast(packages[i], true,
555 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700556 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700557 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700558 break;
559 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800560 case START_CLEANING_PACKAGE: {
561 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700562 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800563 synchronized (mPackages) {
564 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
565 mSettings.mPackagesToBeCleaned.add(packageName);
566 }
567 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800569 startCleaningPackages();
570 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800571 case POST_INSTALL: {
572 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
573 PostInstallData data = mRunningInstalls.get(msg.arg1);
574 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800575 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800576
577 if (data != null) {
578 InstallArgs args = data.args;
579 PackageInstalledInfo res = data.res;
580
581 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
582 res.removedInfo.sendBroadcast(false, true);
583 Bundle extras = new Bundle(1);
584 extras.putInt(Intent.EXTRA_UID, res.uid);
585 final boolean update = res.removedInfo.removedPackage != null;
586 if (update) {
587 extras.putBoolean(Intent.EXTRA_REPLACING, true);
588 }
589 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
590 res.pkg.applicationInfo.packageName,
591 extras);
592 if (update) {
593 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
594 res.pkg.applicationInfo.packageName,
595 extras);
596 }
597 if (res.removedInfo.args != null) {
598 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800599 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800600 }
601 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800602 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800603 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800604 // We delete after a gc for applications on sdcard.
605 if (deleteOld) {
606 synchronized (mInstallLock) {
607 res.removedInfo.args.doPostDeleteLI(true);
608 }
609 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800610 if (args.observer != null) {
611 try {
612 args.observer.packageInstalled(res.name, res.returnCode);
613 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800614 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800615 }
616 }
617 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800618 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800619 }
620 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700621 case UPDATED_MEDIA_STATUS: {
622 try {
623 PackageHelper.getMountService().finishMediaUpdate();
624 } catch (RemoteException e) {
625 Log.e(TAG, "MountService not running?");
626 }
627 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700628 case WRITE_SETTINGS: {
629 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
630 synchronized (mPackages) {
631 removeMessages(WRITE_SETTINGS);
632 mSettings.writeLP();
633 }
634 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
635 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700636 }
637 }
638 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800639
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700640 void scheduleWriteSettingsLocked() {
641 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
642 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
643 }
644 }
645
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800646 static boolean installOnSd(int flags) {
647 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700648 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800649 return false;
650 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700651 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
652 return true;
653 }
654 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800655 }
656
657 static boolean isFwdLocked(int flags) {
658 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
659 return true;
660 }
661 return false;
662 }
663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 public static final IPackageManager main(Context context, boolean factoryTest) {
665 PackageManagerService m = new PackageManagerService(context, factoryTest);
666 ServiceManager.addService("package", m);
667 return m;
668 }
669
670 static String[] splitString(String str, char sep) {
671 int count = 1;
672 int i = 0;
673 while ((i=str.indexOf(sep, i)) >= 0) {
674 count++;
675 i++;
676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 String[] res = new String[count];
679 i=0;
680 count = 0;
681 int lastI=0;
682 while ((i=str.indexOf(sep, i)) >= 0) {
683 res[count] = str.substring(lastI, i);
684 count++;
685 i++;
686 lastI = i;
687 }
688 res[count] = str.substring(lastI, str.length());
689 return res;
690 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800693 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800697 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 mContext = context;
701 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700702 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 mMetrics = new DisplayMetrics();
704 mSettings = new Settings();
705 mSettings.addSharedUserLP("android.uid.system",
706 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
707 mSettings.addSharedUserLP("android.uid.phone",
708 MULTIPLE_APPLICATION_UIDS
709 ? RADIO_UID : FIRST_APPLICATION_UID,
710 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400711 mSettings.addSharedUserLP("android.uid.log",
712 MULTIPLE_APPLICATION_UIDS
713 ? LOG_UID : FIRST_APPLICATION_UID,
714 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715
716 String separateProcesses = SystemProperties.get("debug.separate_processes");
717 if (separateProcesses != null && separateProcesses.length() > 0) {
718 if ("*".equals(separateProcesses)) {
719 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
720 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800721 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 } else {
723 mDefParseFlags = 0;
724 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800725 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 + separateProcesses);
727 }
728 } else {
729 mDefParseFlags = 0;
730 mSeparateProcesses = null;
731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 Installer installer = new Installer();
734 // Little hacky thing to check if installd is here, to determine
735 // whether we are running on the simulator and thus need to take
736 // care of building the /data file structure ourself.
737 // (apparently the sim now has a working installer)
738 if (installer.ping() && Process.supportsProcesses()) {
739 mInstaller = installer;
740 } else {
741 mInstaller = null;
742 }
743
744 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
745 Display d = wm.getDefaultDisplay();
746 d.getMetrics(mMetrics);
747
748 synchronized (mInstallLock) {
749 synchronized (mPackages) {
750 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700751 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 File dataDir = Environment.getDataDirectory();
754 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800755 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
757
758 if (mInstaller == null) {
759 // Make sure these dirs exist, when we are running in
760 // the simulator.
761 // Make a wide-open directory for random misc stuff.
762 File miscDir = new File(dataDir, "misc");
763 miscDir.mkdirs();
764 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800765 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 mDrmAppPrivateInstallDir.mkdirs();
767 }
768
769 readPermissions();
770
771 mRestoredSettings = mSettings.readLP();
772 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800773
774 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800776
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800777 // Set flag to monitor and not change apk file paths when
778 // scanning install directories.
779 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700780 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800781 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800782 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700788 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700791 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 /**
794 * Out of paranoia, ensure that everything in the boot class
795 * path has been dexed.
796 */
797 String bootClassPath = System.getProperty("java.boot.class.path");
798 if (bootClassPath != null) {
799 String[] paths = splitString(bootClassPath, ':');
800 for (int i=0; i<paths.length; i++) {
801 try {
802 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
803 libFiles.add(paths[i]);
804 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700805 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 }
807 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800808 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800810 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 }
812 }
813 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800814 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 /**
818 * Also ensure all external libraries have had dexopt run on them.
819 */
820 if (mSharedLibraries.size() > 0) {
821 Iterator<String> libs = mSharedLibraries.values().iterator();
822 while (libs.hasNext()) {
823 String lib = libs.next();
824 try {
825 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
826 libFiles.add(lib);
827 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700828 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 }
830 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800831 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800833 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
835 }
836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 // Gross hack for now: we know this file doesn't contain any
839 // code, so don't dexopt it to avoid the resulting log spew.
840 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 /**
843 * And there are a number of commands implemented in Java, which
844 * we currently need to do the dexopt on so that they can be
845 * run from a non-root shell.
846 */
847 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700848 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 for (int i=0; i<frameworkFiles.length; i++) {
850 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
851 String path = libPath.getPath();
852 // Skip the file if we alrady did it.
853 if (libFiles.contains(path)) {
854 continue;
855 }
856 // Skip the file if it is not a type we want to dexopt.
857 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
858 continue;
859 }
860 try {
861 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
862 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700863 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 }
865 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800866 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800868 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 }
870 }
871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800872
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700873 if (didDexOpt) {
874 // If we had to do a dexopt of one of the previous
875 // things, then something on the system has changed.
876 // Consider this significant, and wipe away all other
877 // existing dexopt files to ensure we don't leave any
878 // dangling around.
879 String[] files = mDalvikCacheDir.list();
880 if (files != null) {
881 for (int i=0; i<files.length; i++) {
882 String fn = files[i];
883 if (fn.startsWith("data@app@")
884 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800885 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700886 (new File(mDalvikCacheDir, fn)).delete();
887 }
888 }
889 }
890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800892
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800893 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 mFrameworkInstallObserver = new AppDirObserver(
895 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
896 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700897 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
898 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800899 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800900
901 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
903 mSystemInstallObserver = new AppDirObserver(
904 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
905 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700906 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
907 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800908
909 if (mInstaller != null) {
910 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
911 mInstaller.moveFiles();
912 }
913
914 // Prune any system packages that no longer exist.
915 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
916 while (psit.hasNext()) {
917 PackageSetting ps = psit.next();
918 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800919 && !mPackages.containsKey(ps.name)
920 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800921 psit.remove();
922 String msg = "System package " + ps.name
923 + " no longer exists; wiping its data";
924 reportSettingsProblem(Log.WARN, msg);
925 if (mInstaller != null) {
926 // XXX how to set useEncryptedFSDir for packages that
927 // are not encrypted?
928 mInstaller.remove(ps.name, true);
929 }
930 }
931 }
932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 mAppInstallDir = new File(dataDir, "app");
934 if (mInstaller == null) {
935 // Make sure these dirs exist, when we are running in
936 // the simulator.
937 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
938 }
939 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800940 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 //clean up list
942 for(int i = 0; i < deletePkgsList.size(); i++) {
943 //clean up here
944 cleanupInstallFailedPackage(deletePkgsList.get(i));
945 }
946 //delete tmp files
947 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800948
949 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 SystemClock.uptimeMillis());
951 mAppInstallObserver = new AppDirObserver(
952 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
953 mAppInstallObserver.startWatching();
954 scanDirLI(mAppInstallDir, 0, scanMode);
955
956 mDrmAppInstallObserver = new AppDirObserver(
957 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
958 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800959 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800961 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800963 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 + ((SystemClock.uptimeMillis()-startTime)/1000f)
965 + " seconds");
966
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700967 updatePermissionsLP(null, null, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968
969 mSettings.writeLP();
970
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800971 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 // Now after opening every single application zip, make sure they
975 // are all flushed. Not really needed, but keeps things nice and
976 // tidy.
977 Runtime.getRuntime().gc();
978 } // synchronized (mPackages)
979 } // synchronized (mInstallLock)
980 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 @Override
983 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
984 throws RemoteException {
985 try {
986 return super.onTransact(code, data, reply, flags);
987 } catch (RuntimeException e) {
988 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800989 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 }
991 throw e;
992 }
993 }
994
Dianne Hackborne6620b22010-01-22 14:46:21 -0800995 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800996 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800998 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
999 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001001 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001002 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 }
1004 } else {
1005 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001006 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 File dataDir = new File(pkg.applicationInfo.dataDir);
1008 dataDir.delete();
1009 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001010 if (ps.codePath != null) {
1011 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001012 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001013 }
1014 }
1015 if (ps.resourcePath != null) {
1016 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001017 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001018 }
1019 }
1020 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 }
1022
1023 void readPermissions() {
1024 // Read permissions from .../etc/permission directory.
1025 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1026 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001027 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 return;
1029 }
1030 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001031 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 return;
1033 }
1034
1035 // Iterate over the files in the directory and scan .xml files
1036 for (File f : libraryDir.listFiles()) {
1037 // We'll read platform.xml last
1038 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1039 continue;
1040 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001043 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 continue;
1045 }
1046 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001047 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 continue;
1049 }
1050
1051 readPermissionsFromXml(f);
1052 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1055 final File permFile = new File(Environment.getRootDirectory(),
1056 "etc/permissions/platform.xml");
1057 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001058
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001059 StringBuilder sb = new StringBuilder(128);
1060 sb.append("Libs:");
1061 Iterator<String> it = mSharedLibraries.keySet().iterator();
1062 while (it.hasNext()) {
1063 sb.append(' ');
1064 String name = it.next();
1065 sb.append(name);
1066 sb.append(':');
1067 sb.append(mSharedLibraries.get(name));
1068 }
1069 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001070
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001071 sb.setLength(0);
1072 sb.append("Features:");
1073 it = mAvailableFeatures.keySet().iterator();
1074 while (it.hasNext()) {
1075 sb.append(' ');
1076 sb.append(it.next());
1077 }
1078 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001080
1081 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 FileReader permReader = null;
1083 try {
1084 permReader = new FileReader(permFile);
1085 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001086 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 return;
1088 }
1089
1090 try {
1091 XmlPullParser parser = Xml.newPullParser();
1092 parser.setInput(permReader);
1093
1094 XmlUtils.beginDocument(parser, "permissions");
1095
1096 while (true) {
1097 XmlUtils.nextElement(parser);
1098 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1099 break;
1100 }
1101
1102 String name = parser.getName();
1103 if ("group".equals(name)) {
1104 String gidStr = parser.getAttributeValue(null, "gid");
1105 if (gidStr != null) {
1106 int gid = Integer.parseInt(gidStr);
1107 mGlobalGids = appendInt(mGlobalGids, gid);
1108 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001109 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 + parser.getPositionDescription());
1111 }
1112
1113 XmlUtils.skipCurrentTag(parser);
1114 continue;
1115 } else if ("permission".equals(name)) {
1116 String perm = parser.getAttributeValue(null, "name");
1117 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001118 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 + parser.getPositionDescription());
1120 XmlUtils.skipCurrentTag(parser);
1121 continue;
1122 }
1123 perm = perm.intern();
1124 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 } else if ("assign-permission".equals(name)) {
1127 String perm = parser.getAttributeValue(null, "name");
1128 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001129 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 + parser.getPositionDescription());
1131 XmlUtils.skipCurrentTag(parser);
1132 continue;
1133 }
1134 String uidStr = parser.getAttributeValue(null, "uid");
1135 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001136 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 + parser.getPositionDescription());
1138 XmlUtils.skipCurrentTag(parser);
1139 continue;
1140 }
1141 int uid = Process.getUidForName(uidStr);
1142 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001143 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 + uidStr + "\" at "
1145 + parser.getPositionDescription());
1146 XmlUtils.skipCurrentTag(parser);
1147 continue;
1148 }
1149 perm = perm.intern();
1150 HashSet<String> perms = mSystemPermissions.get(uid);
1151 if (perms == null) {
1152 perms = new HashSet<String>();
1153 mSystemPermissions.put(uid, perms);
1154 }
1155 perms.add(perm);
1156 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 } else if ("library".equals(name)) {
1159 String lname = parser.getAttributeValue(null, "name");
1160 String lfile = parser.getAttributeValue(null, "file");
1161 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001162 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 + parser.getPositionDescription());
1164 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001165 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 + parser.getPositionDescription());
1167 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001168 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001169 mSharedLibraries.put(lname, lfile);
1170 }
1171 XmlUtils.skipCurrentTag(parser);
1172 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001173
Dianne Hackborn49237342009-08-27 20:08:01 -07001174 } else if ("feature".equals(name)) {
1175 String fname = parser.getAttributeValue(null, "name");
1176 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001177 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001178 + parser.getPositionDescription());
1179 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001180 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001181 FeatureInfo fi = new FeatureInfo();
1182 fi.name = fname;
1183 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
1185 XmlUtils.skipCurrentTag(parser);
1186 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 } else {
1189 XmlUtils.skipCurrentTag(parser);
1190 continue;
1191 }
1192
1193 }
1194 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001195 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001197 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 }
1199 }
1200
1201 void readPermission(XmlPullParser parser, String name)
1202 throws IOException, XmlPullParserException {
1203
1204 name = name.intern();
1205
1206 BasePermission bp = mSettings.mPermissions.get(name);
1207 if (bp == null) {
1208 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1209 mSettings.mPermissions.put(name, bp);
1210 }
1211 int outerDepth = parser.getDepth();
1212 int type;
1213 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1214 && (type != XmlPullParser.END_TAG
1215 || parser.getDepth() > outerDepth)) {
1216 if (type == XmlPullParser.END_TAG
1217 || type == XmlPullParser.TEXT) {
1218 continue;
1219 }
1220
1221 String tagName = parser.getName();
1222 if ("group".equals(tagName)) {
1223 String gidStr = parser.getAttributeValue(null, "gid");
1224 if (gidStr != null) {
1225 int gid = Process.getGidForName(gidStr);
1226 bp.gids = appendInt(bp.gids, gid);
1227 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001228 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 + parser.getPositionDescription());
1230 }
1231 }
1232 XmlUtils.skipCurrentTag(parser);
1233 }
1234 }
1235
1236 static int[] appendInt(int[] cur, int val) {
1237 if (cur == null) {
1238 return new int[] { val };
1239 }
1240 final int N = cur.length;
1241 for (int i=0; i<N; i++) {
1242 if (cur[i] == val) {
1243 return cur;
1244 }
1245 }
1246 int[] ret = new int[N+1];
1247 System.arraycopy(cur, 0, ret, 0, N);
1248 ret[N] = val;
1249 return ret;
1250 }
1251
1252 static int[] appendInts(int[] cur, int[] add) {
1253 if (add == null) return cur;
1254 if (cur == null) return add;
1255 final int N = add.length;
1256 for (int i=0; i<N; i++) {
1257 cur = appendInt(cur, add[i]);
1258 }
1259 return cur;
1260 }
1261
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001262 static int[] removeInt(int[] cur, int val) {
1263 if (cur == null) {
1264 return null;
1265 }
1266 final int N = cur.length;
1267 for (int i=0; i<N; i++) {
1268 if (cur[i] == val) {
1269 int[] ret = new int[N-1];
1270 if (i > 0) {
1271 System.arraycopy(cur, 0, ret, 0, i);
1272 }
1273 if (i < (N-1)) {
1274 System.arraycopy(cur, i, ret, i+1, N-i-1);
1275 }
1276 return ret;
1277 }
1278 }
1279 return cur;
1280 }
1281
1282 static int[] removeInts(int[] cur, int[] rem) {
1283 if (rem == null) return cur;
1284 if (cur == null) return cur;
1285 final int N = rem.length;
1286 for (int i=0; i<N; i++) {
1287 cur = removeInt(cur, rem[i]);
1288 }
1289 return cur;
1290 }
1291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001293 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1294 // The package has been uninstalled but has retained data and resources.
1295 return PackageParser.generatePackageInfo(p, null, flags);
1296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 final PackageSetting ps = (PackageSetting)p.mExtras;
1298 if (ps == null) {
1299 return null;
1300 }
1301 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1302 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1303 }
1304
1305 public PackageInfo getPackageInfo(String packageName, int flags) {
1306 synchronized (mPackages) {
1307 PackageParser.Package p = mPackages.get(packageName);
1308 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001309 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 + ": " + p);
1311 if (p != null) {
1312 return generatePackageInfo(p, flags);
1313 }
1314 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1315 return generatePackageInfoFromSettingsLP(packageName, flags);
1316 }
1317 }
1318 return null;
1319 }
1320
Dianne Hackborn47096932010-02-11 15:57:09 -08001321 public String[] currentToCanonicalPackageNames(String[] names) {
1322 String[] out = new String[names.length];
1323 synchronized (mPackages) {
1324 for (int i=names.length-1; i>=0; i--) {
1325 PackageSetting ps = mSettings.mPackages.get(names[i]);
1326 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1327 }
1328 }
1329 return out;
1330 }
1331
1332 public String[] canonicalToCurrentPackageNames(String[] names) {
1333 String[] out = new String[names.length];
1334 synchronized (mPackages) {
1335 for (int i=names.length-1; i>=0; i--) {
1336 String cur = mSettings.mRenamedPackages.get(names[i]);
1337 out[i] = cur != null ? cur : names[i];
1338 }
1339 }
1340 return out;
1341 }
1342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 public int getPackageUid(String packageName) {
1344 synchronized (mPackages) {
1345 PackageParser.Package p = mPackages.get(packageName);
1346 if(p != null) {
1347 return p.applicationInfo.uid;
1348 }
1349 PackageSetting ps = mSettings.mPackages.get(packageName);
1350 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1351 return -1;
1352 }
1353 p = ps.pkg;
1354 return p != null ? p.applicationInfo.uid : -1;
1355 }
1356 }
1357
1358 public int[] getPackageGids(String packageName) {
1359 synchronized (mPackages) {
1360 PackageParser.Package p = mPackages.get(packageName);
1361 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001362 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 + ": " + p);
1364 if (p != null) {
1365 final PackageSetting ps = (PackageSetting)p.mExtras;
1366 final SharedUserSetting suid = ps.sharedUser;
1367 return suid != null ? suid.gids : ps.gids;
1368 }
1369 }
1370 // stupid thing to indicate an error.
1371 return new int[0];
1372 }
1373
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001374 static final PermissionInfo generatePermissionInfo(
1375 BasePermission bp, int flags) {
1376 if (bp.perm != null) {
1377 return PackageParser.generatePermissionInfo(bp.perm, flags);
1378 }
1379 PermissionInfo pi = new PermissionInfo();
1380 pi.name = bp.name;
1381 pi.packageName = bp.sourcePackage;
1382 pi.nonLocalizedLabel = bp.name;
1383 pi.protectionLevel = bp.protectionLevel;
1384 return pi;
1385 }
1386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 public PermissionInfo getPermissionInfo(String name, int flags) {
1388 synchronized (mPackages) {
1389 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001390 if (p != null) {
1391 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 }
1393 return null;
1394 }
1395 }
1396
1397 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1398 synchronized (mPackages) {
1399 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1400 for (BasePermission p : mSettings.mPermissions.values()) {
1401 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001402 if (p.perm == null || p.perm.info.group == null) {
1403 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
1405 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001406 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1408 }
1409 }
1410 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 if (out.size() > 0) {
1413 return out;
1414 }
1415 return mPermissionGroups.containsKey(group) ? out : null;
1416 }
1417 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1420 synchronized (mPackages) {
1421 return PackageParser.generatePermissionGroupInfo(
1422 mPermissionGroups.get(name), flags);
1423 }
1424 }
1425
1426 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1427 synchronized (mPackages) {
1428 final int N = mPermissionGroups.size();
1429 ArrayList<PermissionGroupInfo> out
1430 = new ArrayList<PermissionGroupInfo>(N);
1431 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1432 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1433 }
1434 return out;
1435 }
1436 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1439 PackageSetting ps = mSettings.mPackages.get(packageName);
1440 if(ps != null) {
1441 if(ps.pkg == null) {
1442 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1443 if(pInfo != null) {
1444 return pInfo.applicationInfo;
1445 }
1446 return null;
1447 }
1448 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1449 }
1450 return null;
1451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1454 PackageSetting ps = mSettings.mPackages.get(packageName);
1455 if(ps != null) {
1456 if(ps.pkg == null) {
1457 ps.pkg = new PackageParser.Package(packageName);
1458 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001459 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1460 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1461 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1462 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 }
1464 return generatePackageInfo(ps.pkg, flags);
1465 }
1466 return null;
1467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1470 synchronized (mPackages) {
1471 PackageParser.Package p = mPackages.get(packageName);
1472 if (Config.LOGV) Log.v(
1473 TAG, "getApplicationInfo " + packageName
1474 + ": " + p);
1475 if (p != null) {
1476 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001477 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 }
1479 if ("android".equals(packageName)||"system".equals(packageName)) {
1480 return mAndroidApplication;
1481 }
1482 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1483 return generateApplicationInfoFromSettingsLP(packageName, flags);
1484 }
1485 }
1486 return null;
1487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001488
1489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1491 mContext.enforceCallingOrSelfPermission(
1492 android.Manifest.permission.CLEAR_APP_CACHE, null);
1493 // Queue up an async operation since clearing cache may take a little while.
1494 mHandler.post(new Runnable() {
1495 public void run() {
1496 mHandler.removeCallbacks(this);
1497 int retCode = -1;
1498 if (mInstaller != null) {
1499 retCode = mInstaller.freeCache(freeStorageSize);
1500 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001501 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 }
1503 } //end if mInstaller
1504 if (observer != null) {
1505 try {
1506 observer.onRemoveCompleted(null, (retCode >= 0));
1507 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001508 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 }
1510 }
1511 }
1512 });
1513 }
1514
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001515 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001516 mContext.enforceCallingOrSelfPermission(
1517 android.Manifest.permission.CLEAR_APP_CACHE, null);
1518 // Queue up an async operation since clearing cache may take a little while.
1519 mHandler.post(new Runnable() {
1520 public void run() {
1521 mHandler.removeCallbacks(this);
1522 int retCode = -1;
1523 if (mInstaller != null) {
1524 retCode = mInstaller.freeCache(freeStorageSize);
1525 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001526 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001527 }
1528 }
1529 if(pi != null) {
1530 try {
1531 // Callback via pending intent
1532 int code = (retCode >= 0) ? 1 : 0;
1533 pi.sendIntent(null, code, null,
1534 null, null);
1535 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001536 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001537 }
1538 }
1539 }
1540 });
1541 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1544 synchronized (mPackages) {
1545 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001546
1547 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001549 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
1551 if (mResolveComponentName.equals(component)) {
1552 return mResolveActivity;
1553 }
1554 }
1555 return null;
1556 }
1557
1558 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1559 synchronized (mPackages) {
1560 PackageParser.Activity a = mReceivers.mActivities.get(component);
1561 if (Config.LOGV) Log.v(
1562 TAG, "getReceiverInfo " + component + ": " + a);
1563 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1564 return PackageParser.generateActivityInfo(a, flags);
1565 }
1566 }
1567 return null;
1568 }
1569
1570 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1571 synchronized (mPackages) {
1572 PackageParser.Service s = mServices.mServices.get(component);
1573 if (Config.LOGV) Log.v(
1574 TAG, "getServiceInfo " + component + ": " + s);
1575 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1576 return PackageParser.generateServiceInfo(s, flags);
1577 }
1578 }
1579 return null;
1580 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 public String[] getSystemSharedLibraryNames() {
1583 Set<String> libSet;
1584 synchronized (mPackages) {
1585 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001586 int size = libSet.size();
1587 if (size > 0) {
1588 String[] libs = new String[size];
1589 libSet.toArray(libs);
1590 return libs;
1591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001593 return null;
1594 }
1595
1596 public FeatureInfo[] getSystemAvailableFeatures() {
1597 Collection<FeatureInfo> featSet;
1598 synchronized (mPackages) {
1599 featSet = mAvailableFeatures.values();
1600 int size = featSet.size();
1601 if (size > 0) {
1602 FeatureInfo[] features = new FeatureInfo[size+1];
1603 featSet.toArray(features);
1604 FeatureInfo fi = new FeatureInfo();
1605 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1606 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1607 features[size] = fi;
1608 return features;
1609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 }
1611 return null;
1612 }
1613
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001614 public boolean hasSystemFeature(String name) {
1615 synchronized (mPackages) {
1616 return mAvailableFeatures.containsKey(name);
1617 }
1618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 public int checkPermission(String permName, String pkgName) {
1621 synchronized (mPackages) {
1622 PackageParser.Package p = mPackages.get(pkgName);
1623 if (p != null && p.mExtras != null) {
1624 PackageSetting ps = (PackageSetting)p.mExtras;
1625 if (ps.sharedUser != null) {
1626 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1627 return PackageManager.PERMISSION_GRANTED;
1628 }
1629 } else if (ps.grantedPermissions.contains(permName)) {
1630 return PackageManager.PERMISSION_GRANTED;
1631 }
1632 }
1633 }
1634 return PackageManager.PERMISSION_DENIED;
1635 }
1636
1637 public int checkUidPermission(String permName, int uid) {
1638 synchronized (mPackages) {
1639 Object obj = mSettings.getUserIdLP(uid);
1640 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001641 GrantedPermissions gp = (GrantedPermissions)obj;
1642 if (gp.grantedPermissions.contains(permName)) {
1643 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645 } else {
1646 HashSet<String> perms = mSystemPermissions.get(uid);
1647 if (perms != null && perms.contains(permName)) {
1648 return PackageManager.PERMISSION_GRANTED;
1649 }
1650 }
1651 }
1652 return PackageManager.PERMISSION_DENIED;
1653 }
1654
1655 private BasePermission findPermissionTreeLP(String permName) {
1656 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1657 if (permName.startsWith(bp.name) &&
1658 permName.length() > bp.name.length() &&
1659 permName.charAt(bp.name.length()) == '.') {
1660 return bp;
1661 }
1662 }
1663 return null;
1664 }
1665
1666 private BasePermission checkPermissionTreeLP(String permName) {
1667 if (permName != null) {
1668 BasePermission bp = findPermissionTreeLP(permName);
1669 if (bp != null) {
1670 if (bp.uid == Binder.getCallingUid()) {
1671 return bp;
1672 }
1673 throw new SecurityException("Calling uid "
1674 + Binder.getCallingUid()
1675 + " is not allowed to add to permission tree "
1676 + bp.name + " owned by uid " + bp.uid);
1677 }
1678 }
1679 throw new SecurityException("No permission tree found for " + permName);
1680 }
1681
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001682 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1683 if (s1 == null) {
1684 return s2 == null;
1685 }
1686 if (s2 == null) {
1687 return false;
1688 }
1689 if (s1.getClass() != s2.getClass()) {
1690 return false;
1691 }
1692 return s1.equals(s2);
1693 }
1694
1695 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1696 if (pi1.icon != pi2.icon) return false;
1697 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1698 if (!compareStrings(pi1.name, pi2.name)) return false;
1699 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1700 // We'll take care of setting this one.
1701 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1702 // These are not currently stored in settings.
1703 //if (!compareStrings(pi1.group, pi2.group)) return false;
1704 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1705 //if (pi1.labelRes != pi2.labelRes) return false;
1706 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1707 return true;
1708 }
1709
1710 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1711 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1712 throw new SecurityException("Label must be specified in permission");
1713 }
1714 BasePermission tree = checkPermissionTreeLP(info.name);
1715 BasePermission bp = mSettings.mPermissions.get(info.name);
1716 boolean added = bp == null;
1717 boolean changed = true;
1718 if (added) {
1719 bp = new BasePermission(info.name, tree.sourcePackage,
1720 BasePermission.TYPE_DYNAMIC);
1721 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1722 throw new SecurityException(
1723 "Not allowed to modify non-dynamic permission "
1724 + info.name);
1725 } else {
1726 if (bp.protectionLevel == info.protectionLevel
1727 && bp.perm.owner.equals(tree.perm.owner)
1728 && bp.uid == tree.uid
1729 && comparePermissionInfos(bp.perm.info, info)) {
1730 changed = false;
1731 }
1732 }
1733 bp.protectionLevel = info.protectionLevel;
1734 bp.perm = new PackageParser.Permission(tree.perm.owner,
1735 new PermissionInfo(info));
1736 bp.perm.info.packageName = tree.perm.info.packageName;
1737 bp.uid = tree.uid;
1738 if (added) {
1739 mSettings.mPermissions.put(info.name, bp);
1740 }
1741 if (changed) {
1742 if (!async) {
1743 mSettings.writeLP();
1744 } else {
1745 scheduleWriteSettingsLocked();
1746 }
1747 }
1748 return added;
1749 }
1750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 public boolean addPermission(PermissionInfo info) {
1752 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001753 return addPermissionLocked(info, false);
1754 }
1755 }
1756
1757 public boolean addPermissionAsync(PermissionInfo info) {
1758 synchronized (mPackages) {
1759 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
1761 }
1762
1763 public void removePermission(String name) {
1764 synchronized (mPackages) {
1765 checkPermissionTreeLP(name);
1766 BasePermission bp = mSettings.mPermissions.get(name);
1767 if (bp != null) {
1768 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1769 throw new SecurityException(
1770 "Not allowed to modify non-dynamic permission "
1771 + name);
1772 }
1773 mSettings.mPermissions.remove(name);
1774 mSettings.writeLP();
1775 }
1776 }
1777 }
1778
Dianne Hackborn854060af2009-07-09 18:14:31 -07001779 public boolean isProtectedBroadcast(String actionName) {
1780 synchronized (mPackages) {
1781 return mProtectedBroadcasts.contains(actionName);
1782 }
1783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 public int checkSignatures(String pkg1, String pkg2) {
1786 synchronized (mPackages) {
1787 PackageParser.Package p1 = mPackages.get(pkg1);
1788 PackageParser.Package p2 = mPackages.get(pkg2);
1789 if (p1 == null || p1.mExtras == null
1790 || p2 == null || p2.mExtras == null) {
1791 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1792 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001793 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 }
1795 }
1796
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001797 public int checkUidSignatures(int uid1, int uid2) {
1798 synchronized (mPackages) {
1799 Signature[] s1;
1800 Signature[] s2;
1801 Object obj = mSettings.getUserIdLP(uid1);
1802 if (obj != null) {
1803 if (obj instanceof SharedUserSetting) {
1804 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1805 } else if (obj instanceof PackageSetting) {
1806 s1 = ((PackageSetting)obj).signatures.mSignatures;
1807 } else {
1808 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1809 }
1810 } else {
1811 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1812 }
1813 obj = mSettings.getUserIdLP(uid2);
1814 if (obj != null) {
1815 if (obj instanceof SharedUserSetting) {
1816 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1817 } else if (obj instanceof PackageSetting) {
1818 s2 = ((PackageSetting)obj).signatures.mSignatures;
1819 } else {
1820 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1821 }
1822 } else {
1823 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1824 }
1825 return checkSignaturesLP(s1, s2);
1826 }
1827 }
1828
1829 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1830 if (s1 == null) {
1831 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1833 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1834 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001835 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1837 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001838 final int N1 = s1.length;
1839 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 for (int i=0; i<N1; i++) {
1841 boolean match = false;
1842 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001843 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 match = true;
1845 break;
1846 }
1847 }
1848 if (!match) {
1849 return PackageManager.SIGNATURE_NO_MATCH;
1850 }
1851 }
1852 return PackageManager.SIGNATURE_MATCH;
1853 }
1854
1855 public String[] getPackagesForUid(int uid) {
1856 synchronized (mPackages) {
1857 Object obj = mSettings.getUserIdLP(uid);
1858 if (obj instanceof SharedUserSetting) {
1859 SharedUserSetting sus = (SharedUserSetting)obj;
1860 final int N = sus.packages.size();
1861 String[] res = new String[N];
1862 Iterator<PackageSetting> it = sus.packages.iterator();
1863 int i=0;
1864 while (it.hasNext()) {
1865 res[i++] = it.next().name;
1866 }
1867 return res;
1868 } else if (obj instanceof PackageSetting) {
1869 PackageSetting ps = (PackageSetting)obj;
1870 return new String[] { ps.name };
1871 }
1872 }
1873 return null;
1874 }
1875
1876 public String getNameForUid(int uid) {
1877 synchronized (mPackages) {
1878 Object obj = mSettings.getUserIdLP(uid);
1879 if (obj instanceof SharedUserSetting) {
1880 SharedUserSetting sus = (SharedUserSetting)obj;
1881 return sus.name + ":" + sus.userId;
1882 } else if (obj instanceof PackageSetting) {
1883 PackageSetting ps = (PackageSetting)obj;
1884 return ps.name;
1885 }
1886 }
1887 return null;
1888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 public int getUidForSharedUser(String sharedUserName) {
1891 if(sharedUserName == null) {
1892 return -1;
1893 }
1894 synchronized (mPackages) {
1895 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1896 if(suid == null) {
1897 return -1;
1898 }
1899 return suid.userId;
1900 }
1901 }
1902
1903 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1904 int flags) {
1905 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001906 return chooseBestActivity(intent, resolvedType, flags, query);
1907 }
1908
Mihai Predaeae850c2009-05-13 10:13:48 +02001909 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1910 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 if (query != null) {
1912 final int N = query.size();
1913 if (N == 1) {
1914 return query.get(0);
1915 } else if (N > 1) {
1916 // If there is more than one activity with the same priority,
1917 // then let the user decide between them.
1918 ResolveInfo r0 = query.get(0);
1919 ResolveInfo r1 = query.get(1);
1920 if (false) {
1921 System.out.println(r0.activityInfo.name +
1922 "=" + r0.priority + " vs " +
1923 r1.activityInfo.name +
1924 "=" + r1.priority);
1925 }
1926 // If the first activity has a higher priority, or a different
1927 // default, then it is always desireable to pick it.
1928 if (r0.priority != r1.priority
1929 || r0.preferredOrder != r1.preferredOrder
1930 || r0.isDefault != r1.isDefault) {
1931 return query.get(0);
1932 }
1933 // If we have saved a preference for a preferred activity for
1934 // this Intent, use that.
1935 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1936 flags, query, r0.priority);
1937 if (ri != null) {
1938 return ri;
1939 }
1940 return mResolveInfo;
1941 }
1942 }
1943 return null;
1944 }
1945
1946 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1947 int flags, List<ResolveInfo> query, int priority) {
1948 synchronized (mPackages) {
1949 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1950 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001951 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1953 if (prefs != null && prefs.size() > 0) {
1954 // First figure out how good the original match set is.
1955 // We will only allow preferred activities that came
1956 // from the same match quality.
1957 int match = 0;
1958 final int N = query.size();
1959 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1960 for (int j=0; j<N; j++) {
1961 ResolveInfo ri = query.get(j);
1962 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1963 + ": 0x" + Integer.toHexString(match));
1964 if (ri.match > match) match = ri.match;
1965 }
1966 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1967 + Integer.toHexString(match));
1968 match &= IntentFilter.MATCH_CATEGORY_MASK;
1969 final int M = prefs.size();
1970 for (int i=0; i<M; i++) {
1971 PreferredActivity pa = prefs.get(i);
1972 if (pa.mMatch != match) {
1973 continue;
1974 }
1975 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1976 if (DEBUG_PREFERRED) {
1977 Log.v(TAG, "Got preferred activity:");
1978 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1979 }
1980 if (ai != null) {
1981 for (int j=0; j<N; j++) {
1982 ResolveInfo ri = query.get(j);
1983 if (!ri.activityInfo.applicationInfo.packageName
1984 .equals(ai.applicationInfo.packageName)) {
1985 continue;
1986 }
1987 if (!ri.activityInfo.name.equals(ai.name)) {
1988 continue;
1989 }
1990
1991 // Okay we found a previously set preferred app.
1992 // If the result set is different from when this
1993 // was created, we need to clear it and re-ask the
1994 // user their preference.
1995 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001996 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 + intent + " type " + resolvedType);
1998 mSettings.mPreferredActivities.removeFilter(pa);
1999 return null;
2000 }
2001
2002 // Yay!
2003 return ri;
2004 }
2005 }
2006 }
2007 }
2008 }
2009 return null;
2010 }
2011
2012 public List<ResolveInfo> queryIntentActivities(Intent intent,
2013 String resolvedType, int flags) {
2014 ComponentName comp = intent.getComponent();
2015 if (comp != null) {
2016 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2017 ActivityInfo ai = getActivityInfo(comp, flags);
2018 if (ai != null) {
2019 ResolveInfo ri = new ResolveInfo();
2020 ri.activityInfo = ai;
2021 list.add(ri);
2022 }
2023 return list;
2024 }
2025
2026 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002027 String pkgName = intent.getPackage();
2028 if (pkgName == null) {
2029 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2030 resolvedType, flags);
2031 }
2032 PackageParser.Package pkg = mPackages.get(pkgName);
2033 if (pkg != null) {
2034 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2035 resolvedType, flags, pkg.activities);
2036 }
2037 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 }
2039 }
2040
2041 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2042 Intent[] specifics, String[] specificTypes, Intent intent,
2043 String resolvedType, int flags) {
2044 final String resultsAction = intent.getAction();
2045
2046 List<ResolveInfo> results = queryIntentActivities(
2047 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2048 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2049
2050 int specificsPos = 0;
2051 int N;
2052
2053 // todo: note that the algorithm used here is O(N^2). This
2054 // isn't a problem in our current environment, but if we start running
2055 // into situations where we have more than 5 or 10 matches then this
2056 // should probably be changed to something smarter...
2057
2058 // First we go through and resolve each of the specific items
2059 // that were supplied, taking care of removing any corresponding
2060 // duplicate items in the generic resolve list.
2061 if (specifics != null) {
2062 for (int i=0; i<specifics.length; i++) {
2063 final Intent sintent = specifics[i];
2064 if (sintent == null) {
2065 continue;
2066 }
2067
2068 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2069 String action = sintent.getAction();
2070 if (resultsAction != null && resultsAction.equals(action)) {
2071 // If this action was explicitly requested, then don't
2072 // remove things that have it.
2073 action = null;
2074 }
2075 ComponentName comp = sintent.getComponent();
2076 ResolveInfo ri = null;
2077 ActivityInfo ai = null;
2078 if (comp == null) {
2079 ri = resolveIntent(
2080 sintent,
2081 specificTypes != null ? specificTypes[i] : null,
2082 flags);
2083 if (ri == null) {
2084 continue;
2085 }
2086 if (ri == mResolveInfo) {
2087 // ACK! Must do something better with this.
2088 }
2089 ai = ri.activityInfo;
2090 comp = new ComponentName(ai.applicationInfo.packageName,
2091 ai.name);
2092 } else {
2093 ai = getActivityInfo(comp, flags);
2094 if (ai == null) {
2095 continue;
2096 }
2097 }
2098
2099 // Look for any generic query activities that are duplicates
2100 // of this specific one, and remove them from the results.
2101 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2102 N = results.size();
2103 int j;
2104 for (j=specificsPos; j<N; j++) {
2105 ResolveInfo sri = results.get(j);
2106 if ((sri.activityInfo.name.equals(comp.getClassName())
2107 && sri.activityInfo.applicationInfo.packageName.equals(
2108 comp.getPackageName()))
2109 || (action != null && sri.filter.matchAction(action))) {
2110 results.remove(j);
2111 if (Config.LOGV) Log.v(
2112 TAG, "Removing duplicate item from " + j
2113 + " due to specific " + specificsPos);
2114 if (ri == null) {
2115 ri = sri;
2116 }
2117 j--;
2118 N--;
2119 }
2120 }
2121
2122 // Add this specific item to its proper place.
2123 if (ri == null) {
2124 ri = new ResolveInfo();
2125 ri.activityInfo = ai;
2126 }
2127 results.add(specificsPos, ri);
2128 ri.specificIndex = i;
2129 specificsPos++;
2130 }
2131 }
2132
2133 // Now we go through the remaining generic results and remove any
2134 // duplicate actions that are found here.
2135 N = results.size();
2136 for (int i=specificsPos; i<N-1; i++) {
2137 final ResolveInfo rii = results.get(i);
2138 if (rii.filter == null) {
2139 continue;
2140 }
2141
2142 // Iterate over all of the actions of this result's intent
2143 // filter... typically this should be just one.
2144 final Iterator<String> it = rii.filter.actionsIterator();
2145 if (it == null) {
2146 continue;
2147 }
2148 while (it.hasNext()) {
2149 final String action = it.next();
2150 if (resultsAction != null && resultsAction.equals(action)) {
2151 // If this action was explicitly requested, then don't
2152 // remove things that have it.
2153 continue;
2154 }
2155 for (int j=i+1; j<N; j++) {
2156 final ResolveInfo rij = results.get(j);
2157 if (rij.filter != null && rij.filter.hasAction(action)) {
2158 results.remove(j);
2159 if (Config.LOGV) Log.v(
2160 TAG, "Removing duplicate item from " + j
2161 + " due to action " + action + " at " + i);
2162 j--;
2163 N--;
2164 }
2165 }
2166 }
2167
2168 // If the caller didn't request filter information, drop it now
2169 // so we don't have to marshall/unmarshall it.
2170 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2171 rii.filter = null;
2172 }
2173 }
2174
2175 // Filter out the caller activity if so requested.
2176 if (caller != null) {
2177 N = results.size();
2178 for (int i=0; i<N; i++) {
2179 ActivityInfo ainfo = results.get(i).activityInfo;
2180 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2181 && caller.getClassName().equals(ainfo.name)) {
2182 results.remove(i);
2183 break;
2184 }
2185 }
2186 }
2187
2188 // If the caller didn't request filter information,
2189 // drop them now so we don't have to
2190 // marshall/unmarshall it.
2191 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2192 N = results.size();
2193 for (int i=0; i<N; i++) {
2194 results.get(i).filter = null;
2195 }
2196 }
2197
2198 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2199 return results;
2200 }
2201
2202 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2203 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002204 ComponentName comp = intent.getComponent();
2205 if (comp != null) {
2206 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2207 ActivityInfo ai = getReceiverInfo(comp, flags);
2208 if (ai != null) {
2209 ResolveInfo ri = new ResolveInfo();
2210 ri.activityInfo = ai;
2211 list.add(ri);
2212 }
2213 return list;
2214 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002217 String pkgName = intent.getPackage();
2218 if (pkgName == null) {
2219 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2220 resolvedType, flags);
2221 }
2222 PackageParser.Package pkg = mPackages.get(pkgName);
2223 if (pkg != null) {
2224 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2225 resolvedType, flags, pkg.receivers);
2226 }
2227 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228 }
2229 }
2230
2231 public ResolveInfo resolveService(Intent intent, String resolvedType,
2232 int flags) {
2233 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2234 flags);
2235 if (query != null) {
2236 if (query.size() >= 1) {
2237 // If there is more than one service with the same priority,
2238 // just arbitrarily pick the first one.
2239 return query.get(0);
2240 }
2241 }
2242 return null;
2243 }
2244
2245 public List<ResolveInfo> queryIntentServices(Intent intent,
2246 String resolvedType, int flags) {
2247 ComponentName comp = intent.getComponent();
2248 if (comp != null) {
2249 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2250 ServiceInfo si = getServiceInfo(comp, flags);
2251 if (si != null) {
2252 ResolveInfo ri = new ResolveInfo();
2253 ri.serviceInfo = si;
2254 list.add(ri);
2255 }
2256 return list;
2257 }
2258
2259 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002260 String pkgName = intent.getPackage();
2261 if (pkgName == null) {
2262 return (List<ResolveInfo>)mServices.queryIntent(intent,
2263 resolvedType, flags);
2264 }
2265 PackageParser.Package pkg = mPackages.get(pkgName);
2266 if (pkg != null) {
2267 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2268 resolvedType, flags, pkg.services);
2269 }
2270 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 }
2272 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 public List<PackageInfo> getInstalledPackages(int flags) {
2275 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2276
2277 synchronized (mPackages) {
2278 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2279 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2280 while (i.hasNext()) {
2281 final PackageSetting ps = i.next();
2282 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2283 if(psPkg != null) {
2284 finalList.add(psPkg);
2285 }
2286 }
2287 }
2288 else {
2289 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2290 while (i.hasNext()) {
2291 final PackageParser.Package p = i.next();
2292 if (p.applicationInfo != null) {
2293 PackageInfo pi = generatePackageInfo(p, flags);
2294 if(pi != null) {
2295 finalList.add(pi);
2296 }
2297 }
2298 }
2299 }
2300 }
2301 return finalList;
2302 }
2303
2304 public List<ApplicationInfo> getInstalledApplications(int flags) {
2305 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2306 synchronized(mPackages) {
2307 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2308 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2309 while (i.hasNext()) {
2310 final PackageSetting ps = i.next();
2311 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2312 if(ai != null) {
2313 finalList.add(ai);
2314 }
2315 }
2316 }
2317 else {
2318 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2319 while (i.hasNext()) {
2320 final PackageParser.Package p = i.next();
2321 if (p.applicationInfo != null) {
2322 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2323 if(ai != null) {
2324 finalList.add(ai);
2325 }
2326 }
2327 }
2328 }
2329 }
2330 return finalList;
2331 }
2332
2333 public List<ApplicationInfo> getPersistentApplications(int flags) {
2334 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2335
2336 synchronized (mPackages) {
2337 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2338 while (i.hasNext()) {
2339 PackageParser.Package p = i.next();
2340 if (p.applicationInfo != null
2341 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2342 && (!mSafeMode || (p.applicationInfo.flags
2343 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2344 finalList.add(p.applicationInfo);
2345 }
2346 }
2347 }
2348
2349 return finalList;
2350 }
2351
2352 public ProviderInfo resolveContentProvider(String name, int flags) {
2353 synchronized (mPackages) {
2354 final PackageParser.Provider provider = mProviders.get(name);
2355 return provider != null
2356 && mSettings.isEnabledLP(provider.info, flags)
2357 && (!mSafeMode || (provider.info.applicationInfo.flags
2358 &ApplicationInfo.FLAG_SYSTEM) != 0)
2359 ? PackageParser.generateProviderInfo(provider, flags)
2360 : null;
2361 }
2362 }
2363
Fred Quintana718d8a22009-04-29 17:53:20 -07002364 /**
2365 * @deprecated
2366 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 public void querySyncProviders(List outNames, List outInfo) {
2368 synchronized (mPackages) {
2369 Iterator<Map.Entry<String, PackageParser.Provider>> i
2370 = mProviders.entrySet().iterator();
2371
2372 while (i.hasNext()) {
2373 Map.Entry<String, PackageParser.Provider> entry = i.next();
2374 PackageParser.Provider p = entry.getValue();
2375
2376 if (p.syncable
2377 && (!mSafeMode || (p.info.applicationInfo.flags
2378 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2379 outNames.add(entry.getKey());
2380 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2381 }
2382 }
2383 }
2384 }
2385
2386 public List<ProviderInfo> queryContentProviders(String processName,
2387 int uid, int flags) {
2388 ArrayList<ProviderInfo> finalList = null;
2389
2390 synchronized (mPackages) {
2391 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2392 while (i.hasNext()) {
2393 PackageParser.Provider p = i.next();
2394 if (p.info.authority != null
2395 && (processName == null ||
2396 (p.info.processName.equals(processName)
2397 && p.info.applicationInfo.uid == uid))
2398 && mSettings.isEnabledLP(p.info, flags)
2399 && (!mSafeMode || (p.info.applicationInfo.flags
2400 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2401 if (finalList == null) {
2402 finalList = new ArrayList<ProviderInfo>(3);
2403 }
2404 finalList.add(PackageParser.generateProviderInfo(p,
2405 flags));
2406 }
2407 }
2408 }
2409
2410 if (finalList != null) {
2411 Collections.sort(finalList, mProviderInitOrderSorter);
2412 }
2413
2414 return finalList;
2415 }
2416
2417 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2418 int flags) {
2419 synchronized (mPackages) {
2420 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2421 return PackageParser.generateInstrumentationInfo(i, flags);
2422 }
2423 }
2424
2425 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2426 int flags) {
2427 ArrayList<InstrumentationInfo> finalList =
2428 new ArrayList<InstrumentationInfo>();
2429
2430 synchronized (mPackages) {
2431 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2432 while (i.hasNext()) {
2433 PackageParser.Instrumentation p = i.next();
2434 if (targetPackage == null
2435 || targetPackage.equals(p.info.targetPackage)) {
2436 finalList.add(PackageParser.generateInstrumentationInfo(p,
2437 flags));
2438 }
2439 }
2440 }
2441
2442 return finalList;
2443 }
2444
2445 private void scanDirLI(File dir, int flags, int scanMode) {
2446 Log.d(TAG, "Scanning app dir " + dir);
2447
2448 String[] files = dir.list();
2449
2450 int i;
2451 for (i=0; i<files.length; i++) {
2452 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002453 if (!isPackageFilename(files[i])) {
2454 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002455 continue;
2456 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002457 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002459 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002460 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2461 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002462 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002463 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002464 file.delete();
2465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 }
2467 }
2468
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002469 private static File getSettingsProblemFile() {
2470 File dataDir = Environment.getDataDirectory();
2471 File systemDir = new File(dataDir, "system");
2472 File fname = new File(systemDir, "uiderrors.txt");
2473 return fname;
2474 }
2475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 private static void reportSettingsProblem(int priority, String msg) {
2477 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002478 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 FileOutputStream out = new FileOutputStream(fname, true);
2480 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002481 SimpleDateFormat formatter = new SimpleDateFormat();
2482 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2483 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 pw.close();
2485 FileUtils.setPermissions(
2486 fname.toString(),
2487 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2488 -1, -1);
2489 } catch (java.io.IOException e) {
2490 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002491 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 }
2493
2494 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2495 PackageParser.Package pkg, File srcFile, int parseFlags) {
2496 if (GET_CERTIFICATES) {
2497 if (ps == null || !ps.codePath.equals(srcFile)
2498 || ps.getTimeStamp() != srcFile.lastModified()) {
2499 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2500 if (!pp.collectCertificates(pkg, parseFlags)) {
2501 mLastScanError = pp.getParseError();
2502 return false;
2503 }
2504 }
2505 }
2506 return true;
2507 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 /*
2510 * Scan a package and return the newly parsed package.
2511 * Returns null in case of errors and the error code is stored in mLastScanError
2512 */
2513 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002514 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002516 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002518 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002521 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 if (pkg == null) {
2523 mLastScanError = pp.getParseError();
2524 return null;
2525 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002526 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 PackageSetting updatedPkg;
2528 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002529 // Look to see if we already know about this package.
2530 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002531 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002532 // This package has been renamed to its original name. Let's
2533 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002534 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002535 }
2536 // If there was no original package, see one for the real package name.
2537 if (ps == null) {
2538 ps = mSettings.peekPackageLP(pkg.packageName);
2539 }
2540 // Check to see if this package could be hiding/updating a system
2541 // package. Must look for it either under the original or real
2542 // package name depending on our state.
2543 updatedPkg = mSettings.mDisabledSysPackages.get(
2544 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002546 // First check if this is a system package that may involve an update
2547 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2548 if (!ps.codePath.equals(scanFile)) {
2549 // The path has changed from what was last scanned... check the
2550 // version of the new path against what we have stored to determine
2551 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002552 if (pkg.mVersionCode < ps.versionCode) {
2553 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002554 // Ignore entry. Skip it.
2555 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2556 + "ignored: updated version " + ps.versionCode
2557 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002558 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2559 return null;
2560 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002561 // The current app on the system partion is better than
2562 // what we have updated to on the data partition; switch
2563 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002564 // At this point, its safely assumed that package installation for
2565 // apps in system partition will go through. If not there won't be a working
2566 // version of the app
2567 synchronized (mPackages) {
2568 // Just remove the loaded entries from package lists.
2569 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002570 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002571 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002572 + "reverting from " + ps.codePathString
2573 + ": new version " + pkg.mVersionCode
2574 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002575 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2576 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002577 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 }
2580 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002581 if (updatedPkg != null) {
2582 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2583 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2584 }
2585 // Verify certificates against what was last scanned
2586 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002587 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002588 return null;
2589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 // The apk is forward locked (not public) if its code and resources
2591 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002592 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002594 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002595 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002596
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002597 String codePath = null;
2598 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002599 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2600 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002601 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002602 } else {
2603 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002604 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002605 }
2606 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002607 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002608 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002609 codePath = pkg.mScanPath;
2610 // Set application objects path explicitly.
2611 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002613 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 }
2615
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002616 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2617 String destCodePath, String destResPath) {
2618 pkg.mPath = pkg.mScanPath = destCodePath;
2619 pkg.applicationInfo.sourceDir = destCodePath;
2620 pkg.applicationInfo.publicSourceDir = destResPath;
2621 }
2622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 private static String fixProcessName(String defProcessName,
2624 String processName, int uid) {
2625 if (processName == null) {
2626 return defProcessName;
2627 }
2628 return processName;
2629 }
2630
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002631 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2633 if (pkg.mSignatures != null) {
2634 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2635 updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002636 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 + " signatures do not match the previously installed version; ignoring!");
2638 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2639 return false;
2640 }
2641
2642 if (pkgSetting.sharedUser != null) {
2643 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2644 pkg.mSignatures, updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002645 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 + " has no signatures that match those in shared user "
2647 + pkgSetting.sharedUser.name + "; ignoring!");
2648 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2649 return false;
2650 }
2651 }
2652 } else {
2653 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2654 }
2655 return true;
2656 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002657
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002658 public boolean performDexOpt(String packageName) {
2659 if (!mNoDexOpt) {
2660 return false;
2661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002662
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002663 PackageParser.Package p;
2664 synchronized (mPackages) {
2665 p = mPackages.get(packageName);
2666 if (p == null || p.mDidDexOpt) {
2667 return false;
2668 }
2669 }
2670 synchronized (mInstallLock) {
2671 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2672 }
2673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002674
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002675 static final int DEX_OPT_SKIPPED = 0;
2676 static final int DEX_OPT_PERFORMED = 1;
2677 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002678
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002679 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2680 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002681 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002682 String path = pkg.mScanPath;
2683 int ret = 0;
2684 try {
2685 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002686 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002687 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002688 pkg.mDidDexOpt = true;
2689 performed = true;
2690 }
2691 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002692 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002693 ret = -1;
2694 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002695 Slog.w(TAG, "Exception reading apk: " + path, e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002696 ret = -1;
2697 }
2698 if (ret < 0) {
2699 //error from installer
2700 return DEX_OPT_FAILED;
2701 }
2702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002703
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002704 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2705 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002706
2707 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2708 return Environment.isEncryptedFilesystemEnabled() &&
2709 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2710 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002711
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002712 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2713 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002714 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002715 + " to " + newPkg.packageName
2716 + ": old package not in system partition");
2717 return false;
2718 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002719 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002720 + " to " + newPkg.packageName
2721 + ": old package still exists");
2722 return false;
2723 }
2724 return true;
2725 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002726
2727 private File getDataPathForPackage(PackageParser.Package pkg) {
2728 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2729 File dataPath;
2730 if (useEncryptedFSDir) {
2731 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2732 } else {
2733 dataPath = new File(mAppDataDir, pkg.packageName);
2734 }
2735 return dataPath;
2736 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002737
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002738 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2739 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002740 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002741 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2742 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002743 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002744 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002745 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2746 return null;
2747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 mScanningPath = scanFile;
2749 if (pkg == null) {
2750 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2751 return null;
2752 }
2753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2755 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2756 }
2757
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002758 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 synchronized (mPackages) {
2760 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002761 Slog.w(TAG, "*************************************************");
2762 Slog.w(TAG, "Core android package being redefined. Skipping.");
2763 Slog.w(TAG, " file=" + mScanningPath);
2764 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2766 return null;
2767 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 // Set up information for our fall-back user intent resolution
2770 // activity.
2771 mPlatformPackage = pkg;
2772 pkg.mVersionCode = mSdkVersion;
2773 mAndroidApplication = pkg.applicationInfo;
2774 mResolveActivity.applicationInfo = mAndroidApplication;
2775 mResolveActivity.name = ResolverActivity.class.getName();
2776 mResolveActivity.packageName = mAndroidApplication.packageName;
2777 mResolveActivity.processName = mAndroidApplication.processName;
2778 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2779 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2780 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2781 mResolveActivity.exported = true;
2782 mResolveActivity.enabled = true;
2783 mResolveInfo.activityInfo = mResolveActivity;
2784 mResolveInfo.priority = 0;
2785 mResolveInfo.preferredOrder = 0;
2786 mResolveInfo.match = 0;
2787 mResolveComponentName = new ComponentName(
2788 mAndroidApplication.packageName, mResolveActivity.name);
2789 }
2790 }
2791
2792 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002793 TAG, "Scanning package " + pkg.packageName);
2794 if (mPackages.containsKey(pkg.packageName)
2795 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002796 Slog.w(TAG, "*************************************************");
2797 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002799 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2801 return null;
2802 }
2803
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002804 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002805 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2806 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 SharedUserSetting suid = null;
2809 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002810
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002811 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2812 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002813 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002814 pkg.mRealPackage = null;
2815 pkg.mAdoptPermissions = null;
2816 }
2817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 synchronized (mPackages) {
2819 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002820 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2821 if (mTmpSharedLibraries == null ||
2822 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2823 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2824 }
2825 int num = 0;
2826 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2827 for (int i=0; i<N; i++) {
2828 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002830 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002832 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2834 return null;
2835 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002836 mTmpSharedLibraries[num] = file;
2837 num++;
2838 }
2839 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2840 for (int i=0; i<N; i++) {
2841 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2842 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002843 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002844 + " desires unavailable shared library "
2845 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2846 } else {
2847 mTmpSharedLibraries[num] = file;
2848 num++;
2849 }
2850 }
2851 if (num > 0) {
2852 pkg.usesLibraryFiles = new String[num];
2853 System.arraycopy(mTmpSharedLibraries, 0,
2854 pkg.usesLibraryFiles, 0, num);
2855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002856
Dianne Hackborn49237342009-08-27 20:08:01 -07002857 if (pkg.reqFeatures != null) {
2858 N = pkg.reqFeatures.size();
2859 for (int i=0; i<N; i++) {
2860 FeatureInfo fi = pkg.reqFeatures.get(i);
2861 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2862 // Don't care.
2863 continue;
2864 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002865
Dianne Hackborn49237342009-08-27 20:08:01 -07002866 if (fi.name != null) {
2867 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002868 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002869 + " requires unavailable feature "
2870 + fi.name + "; failing!");
2871 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2872 return null;
2873 }
2874 }
2875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 }
2877 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 if (pkg.mSharedUserId != null) {
2880 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2881 pkg.applicationInfo.flags, true);
2882 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002883 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 + " for shared user failed");
2885 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2886 return null;
2887 }
2888 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2889 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2890 + suid.userId + "): packages=" + suid.packages);
2891 }
2892 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002893
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002894 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002895 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002896 Log.w(TAG, "WAITING FOR DEBUGGER");
2897 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002898 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2899 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002900 }
2901 }
2902
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002903 // Check if we are renaming from an original package name.
2904 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002905 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002906 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002907 // This package may need to be renamed to a previously
2908 // installed name. Let's check on that...
2909 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002910 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002911 // This package had originally been installed as the
2912 // original name, and we have already taken care of
2913 // transitioning to the new one. Just update the new
2914 // one to continue using the old name.
2915 realName = pkg.mRealPackage;
2916 if (!pkg.packageName.equals(renamed)) {
2917 // Callers into this function may have already taken
2918 // care of renaming the package; only do it here if
2919 // it is not already done.
2920 pkg.setPackageName(renamed);
2921 }
2922
Dianne Hackbornc1552392010-03-03 16:19:01 -08002923 } else {
2924 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2925 if ((origPackage=mSettings.peekPackageLP(
2926 pkg.mOriginalPackages.get(i))) != null) {
2927 // We do have the package already installed under its
2928 // original name... should we use it?
2929 if (!verifyPackageUpdate(origPackage, pkg)) {
2930 // New package is not compatible with original.
2931 origPackage = null;
2932 continue;
2933 } else if (origPackage.sharedUser != null) {
2934 // Make sure uid is compatible between packages.
2935 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002936 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002937 + " to " + pkg.packageName + ": old uid "
2938 + origPackage.sharedUser.name
2939 + " differs from " + pkg.mSharedUserId);
2940 origPackage = null;
2941 continue;
2942 }
2943 } else {
2944 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2945 + pkg.packageName + " to old name " + origPackage.name);
2946 }
2947 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002948 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002949 }
2950 }
2951 }
2952
2953 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002954 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002955 + " was transferred to another, but its .apk remains");
2956 }
2957
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002958 // Just create the setting, don't add it yet. For already existing packages
2959 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002960 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 destResourceFile, pkg.applicationInfo.flags, true, false);
2962 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002963 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2965 return null;
2966 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002967
2968 if (pkgSetting.origPackage != null) {
2969 // If we are first transitioning from an original package,
2970 // fix up the new package's name now. We need to do this after
2971 // looking up the package under its new name, so getPackageLP
2972 // can take care of fiddling things correctly.
2973 pkg.setPackageName(origPackage.name);
2974
2975 // File a report about this.
2976 String msg = "New package " + pkgSetting.realName
2977 + " renamed to replace old package " + pkgSetting.name;
2978 reportSettingsProblem(Log.WARN, msg);
2979
2980 // Make a note of it.
2981 mTransferedPackages.add(origPackage.name);
2982
2983 // No longer need to retain this.
2984 pkgSetting.origPackage = null;
2985 }
2986
2987 if (realName != null) {
2988 // Make a note of it.
2989 mTransferedPackages.add(pkg.packageName);
2990 }
2991
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002992 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2994 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 pkg.applicationInfo.uid = pkgSetting.userId;
2997 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002998
2999 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003001 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
3003 return null;
3004 }
3005 // The signature has changed, but this package is in the system
3006 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003007 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 // However... if this package is part of a shared user, but it
3009 // doesn't match the signature of the shared user, let's fail.
3010 // What this means is that you can't change the signatures
3011 // associated with an overall shared user, which doesn't seem all
3012 // that unreasonable.
3013 if (pkgSetting.sharedUser != null) {
3014 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
3015 pkg.mSignatures, false)) {
3016 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3017 return null;
3018 }
3019 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003020 // File a report about this.
3021 String msg = "System package " + pkg.packageName
3022 + " signature changed; retaining data.";
3023 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003025
The Android Open Source Project10592532009-03-18 17:39:46 -07003026 // Verify that this new package doesn't have any content providers
3027 // that conflict with existing packages. Only do this if the
3028 // package isn't already installed, since we don't want to break
3029 // things that are installed.
3030 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3031 int N = pkg.providers.size();
3032 int i;
3033 for (i=0; i<N; i++) {
3034 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003035 if (p.info.authority != null) {
3036 String names[] = p.info.authority.split(";");
3037 for (int j = 0; j < names.length; j++) {
3038 if (mProviders.containsKey(names[j])) {
3039 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003040 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003041 " (in package " + pkg.applicationInfo.packageName +
3042 ") is already used by "
3043 + ((other != null && other.getComponentName() != null)
3044 ? other.getComponentName().getPackageName() : "?"));
3045 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3046 return null;
3047 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003048 }
3049 }
3050 }
3051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 }
3053
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003054 final String pkgName = pkg.packageName;
3055
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003056 if (pkg.mAdoptPermissions != null) {
3057 // This package wants to adopt ownership of permissions from
3058 // another package.
3059 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3060 String origName = pkg.mAdoptPermissions.get(i);
3061 PackageSetting orig = mSettings.peekPackageLP(origName);
3062 if (orig != null) {
3063 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003064 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003065 + origName + " to " + pkg.packageName);
3066 mSettings.transferPermissions(origName, pkg.packageName);
3067 }
3068 }
3069 }
3070 }
3071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003072 long scanFileTime = scanFile.lastModified();
3073 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3074 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3075 pkg.applicationInfo.processName = fixProcessName(
3076 pkg.applicationInfo.packageName,
3077 pkg.applicationInfo.processName,
3078 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079
3080 File dataPath;
3081 if (mPlatformPackage == pkg) {
3082 // The system package is special.
3083 dataPath = new File (Environment.getDataDirectory(), "system");
3084 pkg.applicationInfo.dataDir = dataPath.getPath();
3085 } else {
3086 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003087 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003088 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003089
3090 boolean uidError = false;
3091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 if (dataPath.exists()) {
3093 mOutPermissions[1] = 0;
3094 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3095 if (mOutPermissions[1] == pkg.applicationInfo.uid
3096 || !Process.supportsProcesses()) {
3097 pkg.applicationInfo.dataDir = dataPath.getPath();
3098 } else {
3099 boolean recovered = false;
3100 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3101 // If this is a system app, we can at least delete its
3102 // current data so the application will still work.
3103 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003104 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003105 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106 // Old data gone!
3107 String msg = "System package " + pkg.packageName
3108 + " has changed from uid: "
3109 + mOutPermissions[1] + " to "
3110 + pkg.applicationInfo.uid + "; old data erased";
3111 reportSettingsProblem(Log.WARN, msg);
3112 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003114 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003115 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 pkg.applicationInfo.uid);
3117 if (ret == -1) {
3118 // Ack should not happen!
3119 msg = "System package " + pkg.packageName
3120 + " could not have data directory re-created after delete.";
3121 reportSettingsProblem(Log.WARN, msg);
3122 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3123 return null;
3124 }
3125 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 if (!recovered) {
3128 mHasSystemUidErrors = true;
3129 }
3130 }
3131 if (!recovered) {
3132 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3133 + pkg.applicationInfo.uid + "/fs_"
3134 + mOutPermissions[1];
3135 String msg = "Package " + pkg.packageName
3136 + " has mismatched uid: "
3137 + mOutPermissions[1] + " on disk, "
3138 + pkg.applicationInfo.uid + " in settings";
3139 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003140 mSettings.mReadMessages.append(msg);
3141 mSettings.mReadMessages.append('\n');
3142 uidError = true;
3143 if (!pkgSetting.uidError) {
3144 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 }
3147 }
3148 }
3149 pkg.applicationInfo.dataDir = dataPath.getPath();
3150 } else {
3151 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3152 Log.v(TAG, "Want this data dir: " + dataPath);
3153 //invoke installer to do the actual installation
3154 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003155 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 pkg.applicationInfo.uid);
3157 if(ret < 0) {
3158 // Error from installer
3159 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3160 return null;
3161 }
3162 } else {
3163 dataPath.mkdirs();
3164 if (dataPath.exists()) {
3165 FileUtils.setPermissions(
3166 dataPath.toString(),
3167 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3168 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3169 }
3170 }
3171 if (dataPath.exists()) {
3172 pkg.applicationInfo.dataDir = dataPath.getPath();
3173 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003174 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 pkg.applicationInfo.dataDir = null;
3176 }
3177 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003178
3179 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 }
3181
3182 // Perform shared library installation and dex validation and
3183 // optimization, if this is not a system app.
3184 if (mInstaller != null) {
3185 String path = scanFile.getPath();
3186 if (scanFileNewer) {
3187 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003188 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3189 if (err != PackageManager.INSTALL_SUCCEEDED) {
3190 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 return null;
3192 }
3193 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003194 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003195
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003196 if ((scanMode&SCAN_NO_DEX) == 0) {
3197 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3199 return null;
3200 }
3201 }
3202 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 if (mFactoryTest && pkg.requestedPermissions.contains(
3205 android.Manifest.permission.FACTORY_TEST)) {
3206 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3207 }
3208
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003209 // Request the ActivityManager to kill the process(only for existing packages)
3210 // so that we do not end up in a confused state while the user is still using the older
3211 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003212 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003213 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003214 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003215 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003218 // We don't expect installation to fail beyond this point,
3219 if ((scanMode&SCAN_MONITOR) != 0) {
3220 mAppDirs.put(pkg.mPath, pkg);
3221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003223 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003225 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003226 // Make sure we don't accidentally delete its data.
3227 mSettings.mPackagesToBeCleaned.remove(pkgName);
3228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 int N = pkg.providers.size();
3230 StringBuilder r = null;
3231 int i;
3232 for (i=0; i<N; i++) {
3233 PackageParser.Provider p = pkg.providers.get(i);
3234 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3235 p.info.processName, pkg.applicationInfo.uid);
3236 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3237 p.info.name), p);
3238 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003239 if (p.info.authority != null) {
3240 String names[] = p.info.authority.split(";");
3241 p.info.authority = null;
3242 for (int j = 0; j < names.length; j++) {
3243 if (j == 1 && p.syncable) {
3244 // We only want the first authority for a provider to possibly be
3245 // syncable, so if we already added this provider using a different
3246 // authority clear the syncable flag. We copy the provider before
3247 // changing it because the mProviders object contains a reference
3248 // to a provider that we don't want to change.
3249 // Only do this for the second authority since the resulting provider
3250 // object can be the same for all future authorities for this provider.
3251 p = new PackageParser.Provider(p);
3252 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003254 if (!mProviders.containsKey(names[j])) {
3255 mProviders.put(names[j], p);
3256 if (p.info.authority == null) {
3257 p.info.authority = names[j];
3258 } else {
3259 p.info.authority = p.info.authority + ";" + names[j];
3260 }
3261 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3262 Log.d(TAG, "Registered content provider: " + names[j] +
3263 ", className = " + p.info.name +
3264 ", isSyncable = " + p.info.isSyncable);
3265 } else {
3266 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003267 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003268 " (in package " + pkg.applicationInfo.packageName +
3269 "): name already used by "
3270 + ((other != null && other.getComponentName() != null)
3271 ? other.getComponentName().getPackageName() : "?"));
3272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 }
3274 }
3275 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3276 if (r == null) {
3277 r = new StringBuilder(256);
3278 } else {
3279 r.append(' ');
3280 }
3281 r.append(p.info.name);
3282 }
3283 }
3284 if (r != null) {
3285 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3286 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 N = pkg.services.size();
3289 r = null;
3290 for (i=0; i<N; i++) {
3291 PackageParser.Service s = pkg.services.get(i);
3292 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3293 s.info.processName, pkg.applicationInfo.uid);
3294 mServices.addService(s);
3295 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3296 if (r == null) {
3297 r = new StringBuilder(256);
3298 } else {
3299 r.append(' ');
3300 }
3301 r.append(s.info.name);
3302 }
3303 }
3304 if (r != null) {
3305 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3306 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 N = pkg.receivers.size();
3309 r = null;
3310 for (i=0; i<N; i++) {
3311 PackageParser.Activity a = pkg.receivers.get(i);
3312 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3313 a.info.processName, pkg.applicationInfo.uid);
3314 mReceivers.addActivity(a, "receiver");
3315 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3316 if (r == null) {
3317 r = new StringBuilder(256);
3318 } else {
3319 r.append(' ');
3320 }
3321 r.append(a.info.name);
3322 }
3323 }
3324 if (r != null) {
3325 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3326 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 N = pkg.activities.size();
3329 r = null;
3330 for (i=0; i<N; i++) {
3331 PackageParser.Activity a = pkg.activities.get(i);
3332 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3333 a.info.processName, pkg.applicationInfo.uid);
3334 mActivities.addActivity(a, "activity");
3335 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3336 if (r == null) {
3337 r = new StringBuilder(256);
3338 } else {
3339 r.append(' ');
3340 }
3341 r.append(a.info.name);
3342 }
3343 }
3344 if (r != null) {
3345 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3346 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 N = pkg.permissionGroups.size();
3349 r = null;
3350 for (i=0; i<N; i++) {
3351 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3352 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3353 if (cur == null) {
3354 mPermissionGroups.put(pg.info.name, pg);
3355 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3356 if (r == null) {
3357 r = new StringBuilder(256);
3358 } else {
3359 r.append(' ');
3360 }
3361 r.append(pg.info.name);
3362 }
3363 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003364 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 + pg.info.packageName + " ignored: original from "
3366 + cur.info.packageName);
3367 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3368 if (r == null) {
3369 r = new StringBuilder(256);
3370 } else {
3371 r.append(' ');
3372 }
3373 r.append("DUP:");
3374 r.append(pg.info.name);
3375 }
3376 }
3377 }
3378 if (r != null) {
3379 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3380 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 N = pkg.permissions.size();
3383 r = null;
3384 for (i=0; i<N; i++) {
3385 PackageParser.Permission p = pkg.permissions.get(i);
3386 HashMap<String, BasePermission> permissionMap =
3387 p.tree ? mSettings.mPermissionTrees
3388 : mSettings.mPermissions;
3389 p.group = mPermissionGroups.get(p.info.group);
3390 if (p.info.group == null || p.group != null) {
3391 BasePermission bp = permissionMap.get(p.info.name);
3392 if (bp == null) {
3393 bp = new BasePermission(p.info.name, p.info.packageName,
3394 BasePermission.TYPE_NORMAL);
3395 permissionMap.put(p.info.name, bp);
3396 }
3397 if (bp.perm == null) {
3398 if (bp.sourcePackage == null
3399 || bp.sourcePackage.equals(p.info.packageName)) {
3400 BasePermission tree = findPermissionTreeLP(p.info.name);
3401 if (tree == null
3402 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003403 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 bp.perm = p;
3405 bp.uid = pkg.applicationInfo.uid;
3406 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3407 if (r == null) {
3408 r = new StringBuilder(256);
3409 } else {
3410 r.append(' ');
3411 }
3412 r.append(p.info.name);
3413 }
3414 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003415 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 + p.info.packageName + " ignored: base tree "
3417 + tree.name + " is from package "
3418 + tree.sourcePackage);
3419 }
3420 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003421 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 + p.info.packageName + " ignored: original from "
3423 + bp.sourcePackage);
3424 }
3425 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3426 if (r == null) {
3427 r = new StringBuilder(256);
3428 } else {
3429 r.append(' ');
3430 }
3431 r.append("DUP:");
3432 r.append(p.info.name);
3433 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003434 if (bp.perm == p) {
3435 bp.protectionLevel = p.info.protectionLevel;
3436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003438 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 + p.info.packageName + " ignored: no group "
3440 + p.group);
3441 }
3442 }
3443 if (r != null) {
3444 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 N = pkg.instrumentation.size();
3448 r = null;
3449 for (i=0; i<N; i++) {
3450 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3451 a.info.packageName = pkg.applicationInfo.packageName;
3452 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3453 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3454 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003455 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003456 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3457 if (r == null) {
3458 r = new StringBuilder(256);
3459 } else {
3460 r.append(' ');
3461 }
3462 r.append(a.info.name);
3463 }
3464 }
3465 if (r != null) {
3466 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003468
Dianne Hackborn854060af2009-07-09 18:14:31 -07003469 if (pkg.protectedBroadcasts != null) {
3470 N = pkg.protectedBroadcasts.size();
3471 for (i=0; i<N; i++) {
3472 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3473 }
3474 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 pkgSetting.setTimeStamp(scanFileTime);
3477 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 return pkg;
3480 }
3481
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003482 private void killApplication(String pkgName, int uid) {
3483 // Request the ActivityManager to kill the process(only for existing packages)
3484 // so that we do not end up in a confused state while the user is still using the older
3485 // version of the application while the new one gets installed.
3486 IActivityManager am = ActivityManagerNative.getDefault();
3487 if (am != null) {
3488 try {
3489 am.killApplicationWithUid(pkgName, uid);
3490 } catch (RemoteException e) {
3491 }
3492 }
3493 }
3494
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003495 // The following constants are returned by cachePackageSharedLibsForAbiLI
3496 // to indicate if native shared libraries were found in the package.
3497 // Values are:
3498 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3499 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3500 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3501 // in package (and not installed)
3502 //
3503 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3504 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3505 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003507 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3508 // and automatically copy them to /data/data/<appname>/lib if present.
3509 //
3510 // NOTE: this method may throw an IOException if the library cannot
3511 // be copied to its final destination, e.g. if there isn't enough
3512 // room left on the data partition, or a ZipException if the package
3513 // file is malformed.
3514 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003515 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3516 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003517 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3518 final String apkLib = "lib/";
3519 final int apkLibLen = apkLib.length();
3520 final int cpuAbiLen = cpuAbi.length();
3521 final String libPrefix = "lib";
3522 final int libPrefixLen = libPrefix.length();
3523 final String libSuffix = ".so";
3524 final int libSuffixLen = libSuffix.length();
3525 boolean hasNativeLibraries = false;
3526 boolean installedNativeLibraries = false;
3527
3528 // the minimum length of a valid native shared library of the form
3529 // lib/<something>/lib<name>.so.
3530 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3531
3532 ZipFile zipFile = new ZipFile(scanFile);
3533 Enumeration<ZipEntry> entries =
3534 (Enumeration<ZipEntry>) zipFile.entries();
3535
3536 while (entries.hasMoreElements()) {
3537 ZipEntry entry = entries.nextElement();
3538 // skip directories
3539 if (entry.isDirectory()) {
3540 continue;
3541 }
3542 String entryName = entry.getName();
3543
3544 // check that the entry looks like lib/<something>/lib<name>.so
3545 // here, but don't check the ABI just yet.
3546 //
3547 // - must be sufficiently long
3548 // - must end with libSuffix, i.e. ".so"
3549 // - must start with apkLib, i.e. "lib/"
3550 if (entryName.length() < minEntryLen ||
3551 !entryName.endsWith(libSuffix) ||
3552 !entryName.startsWith(apkLib) ) {
3553 continue;
3554 }
3555
3556 // file name must start with libPrefix, i.e. "lib"
3557 int lastSlash = entryName.lastIndexOf('/');
3558
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003559 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003560 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3561 continue;
3562 }
3563
3564 hasNativeLibraries = true;
3565
3566 // check the cpuAbi now, between lib/ and /lib<name>.so
3567 //
3568 if (lastSlash != apkLibLen + cpuAbiLen ||
3569 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3570 continue;
3571
3572 // extract the library file name, ensure it doesn't contain
3573 // weird characters. we're guaranteed here that it doesn't contain
3574 // a directory separator though.
3575 String libFileName = entryName.substring(lastSlash+1);
3576 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3577 continue;
3578 }
3579
3580 installedNativeLibraries = true;
3581
3582 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3583 File.separator + libFileName;
3584 File sharedLibraryFile = new File(sharedLibraryFilePath);
3585 if (! sharedLibraryFile.exists() ||
3586 sharedLibraryFile.length() != entry.getSize() ||
3587 sharedLibraryFile.lastModified() != entry.getTime()) {
3588 if (Config.LOGD) {
3589 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003590 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003591 if (mInstaller == null) {
3592 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003593 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003594 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003595 sharedLibraryFile);
3596 }
3597 }
3598 if (!hasNativeLibraries)
3599 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3600
3601 if (!installedNativeLibraries)
3602 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3603
3604 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3605 }
3606
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003607 // Find the gdbserver executable program in a package at
3608 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3609 //
3610 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3611 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3612 //
3613 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3614 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3615 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3616 final String GDBSERVER = "gdbserver";
3617 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3618
3619 ZipFile zipFile = new ZipFile(scanFile);
3620 Enumeration<ZipEntry> entries =
3621 (Enumeration<ZipEntry>) zipFile.entries();
3622
3623 while (entries.hasMoreElements()) {
3624 ZipEntry entry = entries.nextElement();
3625 // skip directories
3626 if (entry.isDirectory()) {
3627 continue;
3628 }
3629 String entryName = entry.getName();
3630
3631 if (!entryName.equals(apkGdbServerPath)) {
3632 continue;
3633 }
3634
3635 String installGdbServerPath = installGdbServerDir.getPath() +
3636 "/" + GDBSERVER;
3637 File installGdbServerFile = new File(installGdbServerPath);
3638 if (! installGdbServerFile.exists() ||
3639 installGdbServerFile.length() != entry.getSize() ||
3640 installGdbServerFile.lastModified() != entry.getTime()) {
3641 if (Config.LOGD) {
3642 Log.d(TAG, "Caching gdbserver " + entry.getName());
3643 }
3644 if (mInstaller == null) {
3645 installGdbServerDir.mkdir();
3646 }
3647 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3648 installGdbServerFile);
3649 }
3650 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3651 }
3652 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3653 }
3654
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003655 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3656 // and copy them to /data/data/<appname>/lib.
3657 //
3658 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3659 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3660 // one if ro.product.cpu.abi2 is defined.
3661 //
3662 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3663 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003664 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003665 try {
3666 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3667
3668 // some architectures are capable of supporting several CPU ABIs
3669 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3670 // this is indicated by the definition of the ro.product.cpu.abi2
3671 // system property.
3672 //
3673 // only scan the package twice in case of ABI mismatch
3674 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003675 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003676 if (cpuAbi2 != null) {
3677 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003679
3680 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003681 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003682 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003684
3685 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3686 cpuAbi = cpuAbi2;
3687 }
3688 }
3689
3690 // for debuggable packages, also extract gdbserver from lib/<abi>
3691 // into /data/data/<appname>/lib too.
3692 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3693 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3694 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3695 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3696 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003699 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003700 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003701 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003703 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003704 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003706 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 }
3708
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003709 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003711 File binaryDir,
3712 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003713 InputStream inputStream = zipFile.getInputStream(entry);
3714 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003715 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003717 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 // now need to be left as world readable and owned by the system.
3719 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3720 ! tempFile.setLastModified(entry.getTime()) ||
3721 FileUtils.setPermissions(tempFilePath,
3722 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003723 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003725 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 // Failed to properly write file.
3727 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003728 throw new IOException("Couldn't create cached binary "
3729 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 }
3731 } finally {
3732 inputStream.close();
3733 }
3734 }
3735
3736 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3737 if (chatty && Config.LOGD) Log.d(
3738 TAG, "Removing package " + pkg.applicationInfo.packageName );
3739
3740 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 mPackages.remove(pkg.applicationInfo.packageName);
3744 if (pkg.mPath != null) {
3745 mAppDirs.remove(pkg.mPath);
3746 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 PackageSetting ps = (PackageSetting)pkg.mExtras;
3749 if (ps != null && ps.sharedUser != null) {
3750 // XXX don't do this until the data is removed.
3751 if (false) {
3752 ps.sharedUser.packages.remove(ps);
3753 if (ps.sharedUser.packages.size() == 0) {
3754 // Remove.
3755 }
3756 }
3757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 int N = pkg.providers.size();
3760 StringBuilder r = null;
3761 int i;
3762 for (i=0; i<N; i++) {
3763 PackageParser.Provider p = pkg.providers.get(i);
3764 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3765 p.info.name));
3766 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003768 /* The is another ContentProvider with this authority when
3769 * this app was installed so this authority is null,
3770 * Ignore it as we don't have to unregister the provider.
3771 */
3772 continue;
3773 }
3774 String names[] = p.info.authority.split(";");
3775 for (int j = 0; j < names.length; j++) {
3776 if (mProviders.get(names[j]) == p) {
3777 mProviders.remove(names[j]);
3778 if (chatty && Config.LOGD) Log.d(
3779 TAG, "Unregistered content provider: " + names[j] +
3780 ", className = " + p.info.name +
3781 ", isSyncable = " + p.info.isSyncable);
3782 }
3783 }
3784 if (chatty) {
3785 if (r == null) {
3786 r = new StringBuilder(256);
3787 } else {
3788 r.append(' ');
3789 }
3790 r.append(p.info.name);
3791 }
3792 }
3793 if (r != null) {
3794 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3795 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797 N = pkg.services.size();
3798 r = null;
3799 for (i=0; i<N; i++) {
3800 PackageParser.Service s = pkg.services.get(i);
3801 mServices.removeService(s);
3802 if (chatty) {
3803 if (r == null) {
3804 r = new StringBuilder(256);
3805 } else {
3806 r.append(' ');
3807 }
3808 r.append(s.info.name);
3809 }
3810 }
3811 if (r != null) {
3812 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3813 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 N = pkg.receivers.size();
3816 r = null;
3817 for (i=0; i<N; i++) {
3818 PackageParser.Activity a = pkg.receivers.get(i);
3819 mReceivers.removeActivity(a, "receiver");
3820 if (chatty) {
3821 if (r == null) {
3822 r = new StringBuilder(256);
3823 } else {
3824 r.append(' ');
3825 }
3826 r.append(a.info.name);
3827 }
3828 }
3829 if (r != null) {
3830 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 N = pkg.activities.size();
3834 r = null;
3835 for (i=0; i<N; i++) {
3836 PackageParser.Activity a = pkg.activities.get(i);
3837 mActivities.removeActivity(a, "activity");
3838 if (chatty) {
3839 if (r == null) {
3840 r = new StringBuilder(256);
3841 } else {
3842 r.append(' ');
3843 }
3844 r.append(a.info.name);
3845 }
3846 }
3847 if (r != null) {
3848 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3849 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 N = pkg.permissions.size();
3852 r = null;
3853 for (i=0; i<N; i++) {
3854 PackageParser.Permission p = pkg.permissions.get(i);
3855 boolean tree = false;
3856 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3857 if (bp == null) {
3858 tree = true;
3859 bp = mSettings.mPermissionTrees.get(p.info.name);
3860 }
3861 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003862 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 if (chatty) {
3864 if (r == null) {
3865 r = new StringBuilder(256);
3866 } else {
3867 r.append(' ');
3868 }
3869 r.append(p.info.name);
3870 }
3871 }
3872 }
3873 if (r != null) {
3874 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3875 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 N = pkg.instrumentation.size();
3878 r = null;
3879 for (i=0; i<N; i++) {
3880 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003881 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 if (chatty) {
3883 if (r == null) {
3884 r = new StringBuilder(256);
3885 } else {
3886 r.append(' ');
3887 }
3888 r.append(a.info.name);
3889 }
3890 }
3891 if (r != null) {
3892 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3893 }
3894 }
3895 }
3896
3897 private static final boolean isPackageFilename(String name) {
3898 return name != null && name.endsWith(".apk");
3899 }
3900
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003901 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3902 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3903 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3904 return true;
3905 }
3906 }
3907 return false;
3908 }
3909
3910 private void updatePermissionsLP(String changingPkg,
3911 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 // Make sure there are no dangling permission trees.
3913 Iterator<BasePermission> it = mSettings.mPermissionTrees
3914 .values().iterator();
3915 while (it.hasNext()) {
3916 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003917 if (bp.packageSetting == null) {
3918 // We may not yet have parsed the package, so just see if
3919 // we still know about its settings.
3920 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3921 }
3922 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003923 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 + " from package " + bp.sourcePackage);
3925 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003926 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3927 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3928 Slog.i(TAG, "Removing old permission tree: " + bp.name
3929 + " from package " + bp.sourcePackage);
3930 grantPermissions = true;
3931 it.remove();
3932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 }
3934 }
3935
3936 // Make sure all dynamic permissions have been assigned to a package,
3937 // and make sure there are no dangling permissions.
3938 it = mSettings.mPermissions.values().iterator();
3939 while (it.hasNext()) {
3940 BasePermission bp = it.next();
3941 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3942 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3943 + bp.name + " pkg=" + bp.sourcePackage
3944 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003945 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 BasePermission tree = findPermissionTreeLP(bp.name);
3947 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003948 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 bp.perm = new PackageParser.Permission(tree.perm.owner,
3950 new PermissionInfo(bp.pendingInfo));
3951 bp.perm.info.packageName = tree.perm.info.packageName;
3952 bp.perm.info.name = bp.name;
3953 bp.uid = tree.uid;
3954 }
3955 }
3956 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003957 if (bp.packageSetting == null) {
3958 // We may not yet have parsed the package, so just see if
3959 // we still know about its settings.
3960 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3961 }
3962 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003963 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 + " from package " + bp.sourcePackage);
3965 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003966 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3967 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3968 Slog.i(TAG, "Removing old permission: " + bp.name
3969 + " from package " + bp.sourcePackage);
3970 grantPermissions = true;
3971 it.remove();
3972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 }
3974 }
3975
3976 // Now update the permissions for all packages, in particular
3977 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003978 if (grantPermissions) {
3979 for (PackageParser.Package pkg : mPackages.values()) {
3980 if (pkg != pkgInfo) {
3981 grantPermissionsLP(pkg, false);
3982 }
3983 }
3984 }
3985
3986 if (pkgInfo != null) {
3987 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 }
3989 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3992 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3993 if (ps == null) {
3994 return;
3995 }
3996 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003997 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 if (replace) {
4000 ps.permissionsFixed = false;
4001 if (gp == ps) {
4002 gp.grantedPermissions.clear();
4003 gp.gids = mGlobalGids;
4004 }
4005 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 if (gp.gids == null) {
4008 gp.gids = mGlobalGids;
4009 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 final int N = pkg.requestedPermissions.size();
4012 for (int i=0; i<N; i++) {
4013 String name = pkg.requestedPermissions.get(i);
4014 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 if (false) {
4016 if (gp != ps) {
4017 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004018 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 }
4020 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004021 if (bp != null && bp.packageSetting != null) {
4022 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004024 boolean allowedSig = false;
4025 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4026 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 allowed = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004028 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4029 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4030 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004032 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004034 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4036 // For updated system applications, the signatureOrSystem permission
4037 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004038 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4040 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4041 if(sysPs.grantedPermissions.contains(perm)) {
4042 allowed = true;
4043 } else {
4044 allowed = false;
4045 }
4046 } else {
4047 allowed = true;
4048 }
4049 }
4050 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004051 if (allowed) {
4052 allowedSig = true;
4053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 } else {
4055 allowed = false;
4056 }
4057 if (false) {
4058 if (gp != ps) {
4059 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4060 }
4061 }
4062 if (allowed) {
4063 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4064 && ps.permissionsFixed) {
4065 // If this is an existing, non-system package, then
4066 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004067 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004069 // Except... if this is a permission that was added
4070 // to the platform (note: need to only do this when
4071 // updating the platform).
4072 final int NP = PackageParser.NEW_PERMISSIONS.length;
4073 for (int ip=0; ip<NP; ip++) {
4074 final PackageParser.NewPermissionInfo npi
4075 = PackageParser.NEW_PERMISSIONS[ip];
4076 if (npi.name.equals(perm)
4077 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4078 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004079 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004080 + pkg.packageName);
4081 break;
4082 }
4083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 }
4085 }
4086 if (allowed) {
4087 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004088 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 gp.grantedPermissions.add(perm);
4090 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004091 } else if (!ps.haveGids) {
4092 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 }
4094 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004095 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 + " to package " + pkg.packageName
4097 + " because it was previously installed without");
4098 }
4099 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004100 if (gp.grantedPermissions.remove(perm)) {
4101 changedPermission = true;
4102 gp.gids = removeInts(gp.gids, bp.gids);
4103 Slog.i(TAG, "Un-granting permission " + perm
4104 + " from package " + pkg.packageName
4105 + " (protectionLevel=" + bp.protectionLevel
4106 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4107 + ")");
4108 } else {
4109 Slog.w(TAG, "Not granting permission " + perm
4110 + " to package " + pkg.packageName
4111 + " (protectionLevel=" + bp.protectionLevel
4112 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4113 + ")");
4114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 }
4116 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004117 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 + " in package " + pkg.packageName);
4119 }
4120 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004121
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004122 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004123 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4124 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 // This is the first that we have heard about this package, so the
4126 // permissions we have now selected are fixed until explicitly
4127 // changed.
4128 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004130 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 private final class ActivityIntentResolver
4134 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004135 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004137 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 }
4139
Mihai Preda074edef2009-05-18 17:13:31 +02004140 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004142 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4144 }
4145
Mihai Predaeae850c2009-05-13 10:13:48 +02004146 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4147 ArrayList<PackageParser.Activity> packageActivities) {
4148 if (packageActivities == null) {
4149 return null;
4150 }
4151 mFlags = flags;
4152 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4153 int N = packageActivities.size();
4154 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4155 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004156
4157 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004158 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004159 intentFilters = packageActivities.get(i).intents;
4160 if (intentFilters != null && intentFilters.size() > 0) {
4161 listCut.add(intentFilters);
4162 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004163 }
4164 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4165 }
4166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004168 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 if (SHOW_INFO || Config.LOGV) Log.v(
4170 TAG, " " + type + " " +
4171 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4172 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4173 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004174 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4176 if (SHOW_INFO || Config.LOGV) {
4177 Log.v(TAG, " IntentFilter:");
4178 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4179 }
4180 if (!intent.debugCheck()) {
4181 Log.w(TAG, "==> For Activity " + a.info.name);
4182 }
4183 addFilter(intent);
4184 }
4185 }
4186
4187 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004188 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004189 if (SHOW_INFO || Config.LOGV) Log.v(
4190 TAG, " " + type + " " +
4191 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4192 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4193 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004194 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004195 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4196 if (SHOW_INFO || Config.LOGV) {
4197 Log.v(TAG, " IntentFilter:");
4198 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4199 }
4200 removeFilter(intent);
4201 }
4202 }
4203
4204 @Override
4205 protected boolean allowFilterResult(
4206 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4207 ActivityInfo filterAi = filter.activity.info;
4208 for (int i=dest.size()-1; i>=0; i--) {
4209 ActivityInfo destAi = dest.get(i).activityInfo;
4210 if (destAi.name == filterAi.name
4211 && destAi.packageName == filterAi.packageName) {
4212 return false;
4213 }
4214 }
4215 return true;
4216 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004219 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4220 return info.activity.owner.packageName;
4221 }
4222
4223 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4225 int match) {
4226 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4227 return null;
4228 }
4229 final PackageParser.Activity activity = info.activity;
4230 if (mSafeMode && (activity.info.applicationInfo.flags
4231 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4232 return null;
4233 }
4234 final ResolveInfo res = new ResolveInfo();
4235 res.activityInfo = PackageParser.generateActivityInfo(activity,
4236 mFlags);
4237 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4238 res.filter = info;
4239 }
4240 res.priority = info.getPriority();
4241 res.preferredOrder = activity.owner.mPreferredOrder;
4242 //System.out.println("Result: " + res.activityInfo.className +
4243 // " = " + res.priority);
4244 res.match = match;
4245 res.isDefault = info.hasDefault;
4246 res.labelRes = info.labelRes;
4247 res.nonLocalizedLabel = info.nonLocalizedLabel;
4248 res.icon = info.icon;
4249 return res;
4250 }
4251
4252 @Override
4253 protected void sortResults(List<ResolveInfo> results) {
4254 Collections.sort(results, mResolvePrioritySorter);
4255 }
4256
4257 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004258 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004260 out.print(prefix); out.print(
4261 Integer.toHexString(System.identityHashCode(filter.activity)));
4262 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004263 out.print(filter.activity.getComponentShortName());
4264 out.print(" filter ");
4265 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 }
4267
4268// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4269// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4270// final List<ResolveInfo> retList = Lists.newArrayList();
4271// while (i.hasNext()) {
4272// final ResolveInfo resolveInfo = i.next();
4273// if (isEnabledLP(resolveInfo.activityInfo)) {
4274// retList.add(resolveInfo);
4275// }
4276// }
4277// return retList;
4278// }
4279
4280 // Keys are String (activity class name), values are Activity.
4281 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4282 = new HashMap<ComponentName, PackageParser.Activity>();
4283 private int mFlags;
4284 }
4285
4286 private final class ServiceIntentResolver
4287 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004288 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004290 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 }
4292
Mihai Preda074edef2009-05-18 17:13:31 +02004293 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004295 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4297 }
4298
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004299 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4300 ArrayList<PackageParser.Service> packageServices) {
4301 if (packageServices == null) {
4302 return null;
4303 }
4304 mFlags = flags;
4305 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4306 int N = packageServices.size();
4307 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4308 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4309
4310 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4311 for (int i = 0; i < N; ++i) {
4312 intentFilters = packageServices.get(i).intents;
4313 if (intentFilters != null && intentFilters.size() > 0) {
4314 listCut.add(intentFilters);
4315 }
4316 }
4317 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4318 }
4319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004320 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004321 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 if (SHOW_INFO || Config.LOGV) Log.v(
4323 TAG, " " + (s.info.nonLocalizedLabel != null
4324 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4325 if (SHOW_INFO || Config.LOGV) Log.v(
4326 TAG, " Class=" + s.info.name);
4327 int NI = s.intents.size();
4328 int j;
4329 for (j=0; j<NI; j++) {
4330 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4331 if (SHOW_INFO || Config.LOGV) {
4332 Log.v(TAG, " IntentFilter:");
4333 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4334 }
4335 if (!intent.debugCheck()) {
4336 Log.w(TAG, "==> For Service " + s.info.name);
4337 }
4338 addFilter(intent);
4339 }
4340 }
4341
4342 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004343 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004344 if (SHOW_INFO || Config.LOGV) Log.v(
4345 TAG, " " + (s.info.nonLocalizedLabel != null
4346 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4347 if (SHOW_INFO || Config.LOGV) Log.v(
4348 TAG, " Class=" + s.info.name);
4349 int NI = s.intents.size();
4350 int j;
4351 for (j=0; j<NI; j++) {
4352 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4353 if (SHOW_INFO || Config.LOGV) {
4354 Log.v(TAG, " IntentFilter:");
4355 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4356 }
4357 removeFilter(intent);
4358 }
4359 }
4360
4361 @Override
4362 protected boolean allowFilterResult(
4363 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4364 ServiceInfo filterSi = filter.service.info;
4365 for (int i=dest.size()-1; i>=0; i--) {
4366 ServiceInfo destAi = dest.get(i).serviceInfo;
4367 if (destAi.name == filterSi.name
4368 && destAi.packageName == filterSi.packageName) {
4369 return false;
4370 }
4371 }
4372 return true;
4373 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004375 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004376 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4377 return info.service.owner.packageName;
4378 }
4379
4380 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004381 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4382 int match) {
4383 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4384 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4385 return null;
4386 }
4387 final PackageParser.Service service = info.service;
4388 if (mSafeMode && (service.info.applicationInfo.flags
4389 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4390 return null;
4391 }
4392 final ResolveInfo res = new ResolveInfo();
4393 res.serviceInfo = PackageParser.generateServiceInfo(service,
4394 mFlags);
4395 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4396 res.filter = filter;
4397 }
4398 res.priority = info.getPriority();
4399 res.preferredOrder = service.owner.mPreferredOrder;
4400 //System.out.println("Result: " + res.activityInfo.className +
4401 // " = " + res.priority);
4402 res.match = match;
4403 res.isDefault = info.hasDefault;
4404 res.labelRes = info.labelRes;
4405 res.nonLocalizedLabel = info.nonLocalizedLabel;
4406 res.icon = info.icon;
4407 return res;
4408 }
4409
4410 @Override
4411 protected void sortResults(List<ResolveInfo> results) {
4412 Collections.sort(results, mResolvePrioritySorter);
4413 }
4414
4415 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004416 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004417 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004418 out.print(prefix); out.print(
4419 Integer.toHexString(System.identityHashCode(filter.service)));
4420 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004421 out.print(filter.service.getComponentShortName());
4422 out.print(" filter ");
4423 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004424 }
4425
4426// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4427// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4428// final List<ResolveInfo> retList = Lists.newArrayList();
4429// while (i.hasNext()) {
4430// final ResolveInfo resolveInfo = (ResolveInfo) i;
4431// if (isEnabledLP(resolveInfo.serviceInfo)) {
4432// retList.add(resolveInfo);
4433// }
4434// }
4435// return retList;
4436// }
4437
4438 // Keys are String (activity class name), values are Activity.
4439 private final HashMap<ComponentName, PackageParser.Service> mServices
4440 = new HashMap<ComponentName, PackageParser.Service>();
4441 private int mFlags;
4442 };
4443
4444 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4445 new Comparator<ResolveInfo>() {
4446 public int compare(ResolveInfo r1, ResolveInfo r2) {
4447 int v1 = r1.priority;
4448 int v2 = r2.priority;
4449 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4450 if (v1 != v2) {
4451 return (v1 > v2) ? -1 : 1;
4452 }
4453 v1 = r1.preferredOrder;
4454 v2 = r2.preferredOrder;
4455 if (v1 != v2) {
4456 return (v1 > v2) ? -1 : 1;
4457 }
4458 if (r1.isDefault != r2.isDefault) {
4459 return r1.isDefault ? -1 : 1;
4460 }
4461 v1 = r1.match;
4462 v2 = r2.match;
4463 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4464 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4465 }
4466 };
4467
4468 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4469 new Comparator<ProviderInfo>() {
4470 public int compare(ProviderInfo p1, ProviderInfo p2) {
4471 final int v1 = p1.initOrder;
4472 final int v2 = p2.initOrder;
4473 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4474 }
4475 };
4476
4477 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4478 IActivityManager am = ActivityManagerNative.getDefault();
4479 if (am != null) {
4480 try {
4481 final Intent intent = new Intent(action,
4482 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4483 if (extras != null) {
4484 intent.putExtras(extras);
4485 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004486 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 am.broadcastIntent(
4488 null, intent,
4489 null, null, 0, null, null, null, false, false);
4490 } catch (RemoteException ex) {
4491 }
4492 }
4493 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004494
4495 public String nextPackageToClean(String lastPackage) {
4496 synchronized (mPackages) {
4497 if (!mMediaMounted) {
4498 // If the external storage is no longer mounted at this point,
4499 // the caller may not have been able to delete all of this
4500 // packages files and can not delete any more. Bail.
4501 return null;
4502 }
4503 if (lastPackage != null) {
4504 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4505 }
4506 return mSettings.mPackagesToBeCleaned.size() > 0
4507 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4508 }
4509 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004511 void schedulePackageCleaning(String packageName) {
4512 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4513 }
4514
4515 void startCleaningPackages() {
4516 synchronized (mPackages) {
4517 if (!mMediaMounted) {
4518 return;
4519 }
4520 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4521 return;
4522 }
4523 }
4524 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4525 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4526 IActivityManager am = ActivityManagerNative.getDefault();
4527 if (am != null) {
4528 try {
4529 am.startService(null, intent, null);
4530 } catch (RemoteException e) {
4531 }
4532 }
4533 }
4534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 private final class AppDirObserver extends FileObserver {
4536 public AppDirObserver(String path, int mask, boolean isrom) {
4537 super(path, mask);
4538 mRootDir = path;
4539 mIsRom = isrom;
4540 }
4541
4542 public void onEvent(int event, String path) {
4543 String removedPackage = null;
4544 int removedUid = -1;
4545 String addedPackage = null;
4546 int addedUid = -1;
4547
4548 synchronized (mInstallLock) {
4549 String fullPathStr = null;
4550 File fullPath = null;
4551 if (path != null) {
4552 fullPath = new File(mRootDir, path);
4553 fullPathStr = fullPath.getPath();
4554 }
4555
4556 if (Config.LOGV) Log.v(
4557 TAG, "File " + fullPathStr + " changed: "
4558 + Integer.toHexString(event));
4559
4560 if (!isPackageFilename(path)) {
4561 if (Config.LOGV) Log.v(
4562 TAG, "Ignoring change of non-package file: " + fullPathStr);
4563 return;
4564 }
4565
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004566 // Ignore packages that are being installed or
4567 // have just been installed.
4568 if (ignoreCodePath(fullPathStr)) {
4569 return;
4570 }
4571 PackageParser.Package p = null;
4572 synchronized (mPackages) {
4573 p = mAppDirs.get(fullPathStr);
4574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004576 if (p != null) {
4577 removePackageLI(p, true);
4578 removedPackage = p.applicationInfo.packageName;
4579 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580 }
4581 }
4582
4583 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004584 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004585 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004586 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4587 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 PackageParser.PARSE_CHATTY |
4589 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004590 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004591 if (p != null) {
4592 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004593 updatePermissionsLP(p.packageName, p,
4594 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 }
4596 addedPackage = p.applicationInfo.packageName;
4597 addedUid = p.applicationInfo.uid;
4598 }
4599 }
4600 }
4601
4602 synchronized (mPackages) {
4603 mSettings.writeLP();
4604 }
4605 }
4606
4607 if (removedPackage != null) {
4608 Bundle extras = new Bundle(1);
4609 extras.putInt(Intent.EXTRA_UID, removedUid);
4610 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4611 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4612 }
4613 if (addedPackage != null) {
4614 Bundle extras = new Bundle(1);
4615 extras.putInt(Intent.EXTRA_UID, addedUid);
4616 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4617 }
4618 }
4619
4620 private final String mRootDir;
4621 private final boolean mIsRom;
4622 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004624 /* Called when a downloaded package installation has been confirmed by the user */
4625 public void installPackage(
4626 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004627 installPackage(packageURI, observer, flags, null);
4628 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004629
Jacek Surazski65e13172009-04-28 15:26:38 +02004630 /* Called when a downloaded package installation has been confirmed by the user */
4631 public void installPackage(
4632 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4633 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004634 mContext.enforceCallingOrSelfPermission(
4635 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004636
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004637 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004638 msg.obj = new InstallParams(packageURI, observer, flags,
4639 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004640 mHandler.sendMessage(msg);
4641 }
4642
Christopher Tate1bb69062010-02-19 17:02:12 -08004643 public void finishPackageInstall(int token) {
4644 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4645 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4646 mHandler.sendMessage(msg);
4647 }
4648
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004649 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004650 // Queue up an async operation since the package installation may take a little while.
4651 mHandler.post(new Runnable() {
4652 public void run() {
4653 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004654 // Result object to be returned
4655 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004656 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004657 res.uid = -1;
4658 res.pkg = null;
4659 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004660 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004661 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004662 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004663 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004664 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004665 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004666 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004667
4668 // A restore should be performed at this point if (a) the install
4669 // succeeded, (b) the operation is not an update, and (c) the new
4670 // package has a backupAgent defined.
4671 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004672 boolean doRestore = (!update
4673 && res.pkg != null
4674 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004675
4676 // Set up the post-install work request bookkeeping. This will be used
4677 // and cleaned up by the post-install event handling regardless of whether
4678 // there's a restore pass performed. Token values are >= 1.
4679 int token;
4680 if (mNextInstallToken < 0) mNextInstallToken = 1;
4681 token = mNextInstallToken++;
4682
4683 PostInstallData data = new PostInstallData(args, res);
4684 mRunningInstalls.put(token, data);
4685 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4686
4687 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4688 // Pass responsibility to the Backup Manager. It will perform a
4689 // restore if appropriate, then pass responsibility back to the
4690 // Package Manager to run the post-install observer callbacks
4691 // and broadcasts.
4692 IBackupManager bm = IBackupManager.Stub.asInterface(
4693 ServiceManager.getService(Context.BACKUP_SERVICE));
4694 if (bm != null) {
4695 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4696 + " to BM for possible restore");
4697 try {
4698 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4699 } catch (RemoteException e) {
4700 // can't happen; the backup manager is local
4701 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004702 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004703 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004704 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004705 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004706 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004707 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004709 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004710
4711 if (!doRestore) {
4712 // No restore possible, or the Backup Manager was mysteriously not
4713 // available -- just fire the post-install work request directly.
4714 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4715 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4716 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004718 }
4719 });
4720 }
4721
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004722 abstract class HandlerParams {
4723 final static int MAX_RETRIES = 4;
4724 int retry = 0;
4725 final void startCopy() {
4726 try {
4727 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4728 retry++;
4729 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004730 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004731 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4732 handleServiceError();
4733 return;
4734 } else {
4735 handleStartCopy();
4736 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4737 mHandler.sendEmptyMessage(MCS_UNBIND);
4738 }
4739 } catch (RemoteException e) {
4740 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4741 mHandler.sendEmptyMessage(MCS_RECONNECT);
4742 }
4743 handleReturnCode();
4744 }
4745
4746 final void serviceError() {
4747 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4748 handleServiceError();
4749 handleReturnCode();
4750 }
4751 abstract void handleStartCopy() throws RemoteException;
4752 abstract void handleServiceError();
4753 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004754 }
4755
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004756 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004757 final IPackageInstallObserver observer;
4758 int flags;
4759 final Uri packageURI;
4760 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004761 private InstallArgs mArgs;
4762 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004763 InstallParams(Uri packageURI,
4764 IPackageInstallObserver observer, int flags,
4765 String installerPackageName) {
4766 this.packageURI = packageURI;
4767 this.flags = flags;
4768 this.observer = observer;
4769 this.installerPackageName = installerPackageName;
4770 }
4771
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004772 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4773 String packageName = pkgLite.packageName;
4774 int installLocation = pkgLite.installLocation;
4775 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4776 synchronized (mPackages) {
4777 PackageParser.Package pkg = mPackages.get(packageName);
4778 if (pkg != null) {
4779 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4780 // Check for updated system application.
4781 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4782 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004783 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004784 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4785 }
4786 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4787 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004788 if (onSd) {
4789 // Install flag overrides everything.
4790 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4791 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004792 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004793 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4794 // Application explicitly specified internal.
4795 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4796 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4797 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004798 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004799 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004800 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4801 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4802 }
4803 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004804 }
4805 }
4806 } else {
4807 // Invalid install. Return error code
4808 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4809 }
4810 }
4811 }
4812 // All the special cases have been taken care of.
4813 // Return result based on recommended install location.
4814 if (onSd) {
4815 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4816 }
4817 return pkgLite.recommendedInstallLocation;
4818 }
4819
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004820 /*
4821 * Invoke remote method to get package information and install
4822 * location values. Override install location based on default
4823 * policy if needed and then create install arguments based
4824 * on the install location.
4825 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004826 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004827 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004828 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4829 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004830 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4831 if (onInt && onSd) {
4832 // Check if both bits are set.
4833 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4834 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4835 } else if (fwdLocked && onSd) {
4836 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004837 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004838 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004839 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004840 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004841 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004842 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004843 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4844 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4845 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4846 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4847 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004848 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4849 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4850 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004851 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4852 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004853 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004854 // Override with defaults if needed.
4855 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004856 if (!onSd && !onInt) {
4857 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4859 // Set the flag to install on external media.
4860 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004861 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004862 } else {
4863 // Make sure the flag for installing on external
4864 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004865 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004866 flags &= ~PackageManager.INSTALL_EXTERNAL;
4867 }
4868 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004869 }
4870 }
4871 // Create the file args now.
4872 mArgs = createInstallArgs(this);
4873 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4874 // Create copy only if we are not in an erroneous state.
4875 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004876 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004877 }
4878 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004879 }
4880
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004881 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004882 void handleReturnCode() {
4883 processPendingInstall(mArgs, mRet);
4884 }
4885
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004886 @Override
4887 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004888 mArgs = createInstallArgs(this);
4889 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004890 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004891 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004892
4893 /*
4894 * Utility class used in movePackage api.
4895 * srcArgs and targetArgs are not set for invalid flags and make
4896 * sure to do null checks when invoking methods on them.
4897 * We probably want to return ErrorPrams for both failed installs
4898 * and moves.
4899 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004900 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004901 final IPackageMoveObserver observer;
4902 final int flags;
4903 final String packageName;
4904 final InstallArgs srcArgs;
4905 final InstallArgs targetArgs;
4906 int mRet;
4907 MoveParams(InstallArgs srcArgs,
4908 IPackageMoveObserver observer,
4909 int flags, String packageName) {
4910 this.srcArgs = srcArgs;
4911 this.observer = observer;
4912 this.flags = flags;
4913 this.packageName = packageName;
4914 if (srcArgs != null) {
4915 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4916 targetArgs = createInstallArgs(packageUri, flags, packageName);
4917 } else {
4918 targetArgs = null;
4919 }
4920 }
4921
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004922 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004923 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4924 // Check for storage space on target medium
4925 if (!targetArgs.checkFreeStorage(mContainerService)) {
4926 Log.w(TAG, "Insufficient storage to install");
4927 return;
4928 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004929 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004930 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004931 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004932 if (DEBUG_SD_INSTALL) {
4933 StringBuilder builder = new StringBuilder();
4934 if (srcArgs != null) {
4935 builder.append("src: ");
4936 builder.append(srcArgs.getCodePath());
4937 }
4938 if (targetArgs != null) {
4939 builder.append(" target : ");
4940 builder.append(targetArgs.getCodePath());
4941 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004942 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004943 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004944 }
4945
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004946 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004947 void handleReturnCode() {
4948 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004949 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4950 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4951 currentStatus = PackageManager.MOVE_SUCCEEDED;
4952 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4953 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4954 }
4955 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004956 }
4957
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004958 @Override
4959 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004960 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004961 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004962 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004963
4964 private InstallArgs createInstallArgs(InstallParams params) {
4965 if (installOnSd(params.flags)) {
4966 return new SdInstallArgs(params);
4967 } else {
4968 return new FileInstallArgs(params);
4969 }
4970 }
4971
4972 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4973 if (installOnSd(flags)) {
4974 return new SdInstallArgs(fullCodePath, fullResourcePath);
4975 } else {
4976 return new FileInstallArgs(fullCodePath, fullResourcePath);
4977 }
4978 }
4979
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004980 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4981 if (installOnSd(flags)) {
4982 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4983 return new SdInstallArgs(packageURI, cid);
4984 } else {
4985 return new FileInstallArgs(packageURI, pkgName);
4986 }
4987 }
4988
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004989 static abstract class InstallArgs {
4990 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004991 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004992 final int flags;
4993 final Uri packageURI;
4994 final String installerPackageName;
4995
4996 InstallArgs(Uri packageURI,
4997 IPackageInstallObserver observer, int flags,
4998 String installerPackageName) {
4999 this.packageURI = packageURI;
5000 this.flags = flags;
5001 this.observer = observer;
5002 this.installerPackageName = installerPackageName;
5003 }
5004
5005 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005006 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005007 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005008 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005009 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005010 abstract String getCodePath();
5011 abstract String getResourcePath();
5012 // Need installer lock especially for dex file removal.
5013 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005014 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005015 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005016 }
5017
5018 class FileInstallArgs extends InstallArgs {
5019 File installDir;
5020 String codeFileName;
5021 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005022 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005023
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005024 FileInstallArgs(InstallParams params) {
5025 super(params.packageURI, params.observer,
5026 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005027 }
5028
5029 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5030 super(null, null, 0, null);
5031 File codeFile = new File(fullCodePath);
5032 installDir = codeFile.getParentFile();
5033 codeFileName = fullCodePath;
5034 resourceFileName = fullResourcePath;
5035 }
5036
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005037 FileInstallArgs(Uri packageURI, String pkgName) {
5038 super(packageURI, null, 0, null);
5039 boolean fwdLocked = isFwdLocked(flags);
5040 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5041 String apkName = getNextCodePath(null, pkgName, ".apk");
5042 codeFileName = new File(installDir, apkName + ".apk").getPath();
5043 resourceFileName = getResourcePathFromCodePath();
5044 }
5045
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005046 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5047 return imcs.checkFreeStorage(false, packageURI);
5048 }
5049
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005050 String getCodePath() {
5051 return codeFileName;
5052 }
5053
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005054 void createCopyFile() {
5055 boolean fwdLocked = isFwdLocked(flags);
5056 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5057 codeFileName = createTempPackageFile(installDir).getPath();
5058 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005059 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005060 }
5061
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005062 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005063 if (temp) {
5064 // Generate temp file name
5065 createCopyFile();
5066 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005067 // Get a ParcelFileDescriptor to write to the output file
5068 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005069 if (!created) {
5070 try {
5071 codeFile.createNewFile();
5072 // Set permissions
5073 if (!setPermissions()) {
5074 // Failed setting permissions.
5075 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5076 }
5077 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005078 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005079 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5080 }
5081 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005082 ParcelFileDescriptor out = null;
5083 try {
5084 out = ParcelFileDescriptor.open(codeFile,
5085 ParcelFileDescriptor.MODE_READ_WRITE);
5086 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005087 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005088 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5089 }
5090 // Copy the resource now
5091 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5092 try {
5093 if (imcs.copyResource(packageURI, out)) {
5094 ret = PackageManager.INSTALL_SUCCEEDED;
5095 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005096 } finally {
5097 try { if (out != null) out.close(); } catch (IOException e) {}
5098 }
5099 return ret;
5100 }
5101
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005102 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005103 if (status != PackageManager.INSTALL_SUCCEEDED) {
5104 cleanUp();
5105 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005106 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005107 }
5108
5109 boolean doRename(int status, final String pkgName, String oldCodePath) {
5110 if (status != PackageManager.INSTALL_SUCCEEDED) {
5111 cleanUp();
5112 return false;
5113 } else {
5114 // Rename based on packageName
5115 File codeFile = new File(getCodePath());
5116 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5117 File desFile = new File(installDir, apkName + ".apk");
5118 if (!codeFile.renameTo(desFile)) {
5119 return false;
5120 }
5121 // Reset paths since the file has been renamed.
5122 codeFileName = desFile.getPath();
5123 resourceFileName = getResourcePathFromCodePath();
5124 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005125 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005126 // Failed setting permissions.
5127 return false;
5128 }
5129 return true;
5130 }
5131 }
5132
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005133 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005134 if (status != PackageManager.INSTALL_SUCCEEDED) {
5135 cleanUp();
5136 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005137 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005138 }
5139
5140 String getResourcePath() {
5141 return resourceFileName;
5142 }
5143
5144 String getResourcePathFromCodePath() {
5145 String codePath = getCodePath();
5146 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5147 String apkNameOnly = getApkName(codePath);
5148 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5149 } else {
5150 return codePath;
5151 }
5152 }
5153
5154 private boolean cleanUp() {
5155 boolean ret = true;
5156 String sourceDir = getCodePath();
5157 String publicSourceDir = getResourcePath();
5158 if (sourceDir != null) {
5159 File sourceFile = new File(sourceDir);
5160 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005161 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005162 ret = false;
5163 }
5164 // Delete application's code and resources
5165 sourceFile.delete();
5166 }
5167 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5168 final File publicSourceFile = new File(publicSourceDir);
5169 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005170 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005171 }
5172 if (publicSourceFile.exists()) {
5173 publicSourceFile.delete();
5174 }
5175 }
5176 return ret;
5177 }
5178
5179 void cleanUpResourcesLI() {
5180 String sourceDir = getCodePath();
5181 if (cleanUp() && mInstaller != null) {
5182 int retCode = mInstaller.rmdex(sourceDir);
5183 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005184 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005185 + " at location "
5186 + sourceDir + ", retcode=" + retCode);
5187 // we don't consider this to be a failure of the core package deletion
5188 }
5189 }
5190 }
5191
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005192 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005193 // TODO Do this in a more elegant way later on. for now just a hack
5194 if (!isFwdLocked(flags)) {
5195 final int filePermissions =
5196 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5197 |FileUtils.S_IROTH;
5198 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5199 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005200 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005201 getCodePath()
5202 + ". The return code was: " + retCode);
5203 // TODO Define new internal error
5204 return false;
5205 }
5206 return true;
5207 }
5208 return true;
5209 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005210
5211 boolean doPostDeleteLI(boolean delete) {
5212 cleanUpResourcesLI();
5213 return true;
5214 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005215 }
5216
5217 class SdInstallArgs extends InstallArgs {
5218 String cid;
5219 String cachePath;
5220 static final String RES_FILE_NAME = "pkg.apk";
5221
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005222 SdInstallArgs(InstallParams params) {
5223 super(params.packageURI, params.observer,
5224 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005225 }
5226
5227 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005228 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005229 // Extract cid from fullCodePath
5230 int eidx = fullCodePath.lastIndexOf("/");
5231 String subStr1 = fullCodePath.substring(0, eidx);
5232 int sidx = subStr1.lastIndexOf("/");
5233 cid = subStr1.substring(sidx+1, eidx);
5234 cachePath = subStr1;
5235 }
5236
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005237 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005238 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5239 this.cid = cid;
5240 }
5241
5242 SdInstallArgs(Uri packageURI, String cid) {
5243 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005244 this.cid = cid;
5245 }
5246
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005247 void createCopyFile() {
5248 cid = getTempContainerId();
5249 }
5250
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005251 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5252 return imcs.checkFreeStorage(true, packageURI);
5253 }
5254
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005255 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005256 if (temp) {
5257 createCopyFile();
5258 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005259 cachePath = imcs.copyResourceToContainer(
5260 packageURI, cid,
5261 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005262 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5263 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005264 }
5265
5266 @Override
5267 String getCodePath() {
5268 return cachePath + "/" + RES_FILE_NAME;
5269 }
5270
5271 @Override
5272 String getResourcePath() {
5273 return cachePath + "/" + RES_FILE_NAME;
5274 }
5275
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005276 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005277 if (status != PackageManager.INSTALL_SUCCEEDED) {
5278 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005279 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005280 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005281 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005282 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005283 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005284 if (cachePath == null) {
5285 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5286 }
5287 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005288 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005289 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005290 }
5291
5292 boolean doRename(int status, final String pkgName,
5293 String oldCodePath) {
5294 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005295 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005296 if (PackageHelper.isContainerMounted(cid)) {
5297 // Unmount the container
5298 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005299 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005300 return false;
5301 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005302 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005303 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005304 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5305 " which might be stale. Will try to clean up.");
5306 // Clean up the stale container and proceed to recreate.
5307 if (!PackageHelper.destroySdDir(newCacheId)) {
5308 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5309 return false;
5310 }
5311 // Successfully cleaned up stale container. Try to rename again.
5312 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5313 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5314 + " inspite of cleaning it up.");
5315 return false;
5316 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005317 }
5318 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005319 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005320 newCachePath = PackageHelper.mountSdDir(newCacheId,
5321 getEncryptKey(), Process.SYSTEM_UID);
5322 } else {
5323 newCachePath = PackageHelper.getSdDir(newCacheId);
5324 }
5325 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005326 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005327 return false;
5328 }
5329 Log.i(TAG, "Succesfully renamed " + cid +
5330 " at path: " + cachePath + " to " + newCacheId +
5331 " at new path: " + newCachePath);
5332 cid = newCacheId;
5333 cachePath = newCachePath;
5334 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005335 }
5336
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005337 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005338 if (status != PackageManager.INSTALL_SUCCEEDED) {
5339 cleanUp();
5340 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005341 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005342 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005343 PackageHelper.mountSdDir(cid,
5344 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005345 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005346 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005347 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005348 }
5349
5350 private void cleanUp() {
5351 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005352 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005353 }
5354
5355 void cleanUpResourcesLI() {
5356 String sourceFile = getCodePath();
5357 // Remove dex file
5358 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005359 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005360 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005361 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005362 + " at location "
5363 + sourceFile.toString() + ", retcode=" + retCode);
5364 // we don't consider this to be a failure of the core package deletion
5365 }
5366 }
5367 cleanUp();
5368 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005369
5370 boolean matchContainer(String app) {
5371 if (cid.startsWith(app)) {
5372 return true;
5373 }
5374 return false;
5375 }
5376
5377 String getPackageName() {
5378 int idx = cid.lastIndexOf("-");
5379 if (idx == -1) {
5380 return cid;
5381 }
5382 return cid.substring(0, idx);
5383 }
5384
5385 boolean doPostDeleteLI(boolean delete) {
5386 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005387 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005388 if (mounted) {
5389 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005390 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005391 }
5392 if (ret && delete) {
5393 cleanUpResourcesLI();
5394 }
5395 return ret;
5396 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005397 };
5398
5399 // Utility method used to create code paths based on package name and available index.
5400 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5401 String idxStr = "";
5402 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005403 // Fall back to default value of idx=1 if prefix is not
5404 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005405 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005406 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005407 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005408 if (subStr.endsWith(suffix)) {
5409 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005410 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005411 // If oldCodePath already contains prefix find out the
5412 // ending index to either increment or decrement.
5413 int sidx = subStr.lastIndexOf(prefix);
5414 if (sidx != -1) {
5415 subStr = subStr.substring(sidx + prefix.length());
5416 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005417 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5418 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005419 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005420 try {
5421 idx = Integer.parseInt(subStr);
5422 if (idx <= 1) {
5423 idx++;
5424 } else {
5425 idx--;
5426 }
5427 } catch(NumberFormatException e) {
5428 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005429 }
5430 }
5431 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005432 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005433 return prefix + idxStr;
5434 }
5435
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005436 // Utility method used to ignore ADD/REMOVE events
5437 // by directory observer.
5438 private static boolean ignoreCodePath(String fullPathStr) {
5439 String apkName = getApkName(fullPathStr);
5440 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5441 if (idx != -1 && ((idx+1) < apkName.length())) {
5442 // Make sure the package ends with a numeral
5443 String version = apkName.substring(idx+1);
5444 try {
5445 Integer.parseInt(version);
5446 return true;
5447 } catch (NumberFormatException e) {}
5448 }
5449 return false;
5450 }
5451
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005452 // Utility method that returns the relative package path with respect
5453 // to the installation directory. Like say for /data/data/com.test-1.apk
5454 // string com.test-1 is returned.
5455 static String getApkName(String codePath) {
5456 if (codePath == null) {
5457 return null;
5458 }
5459 int sidx = codePath.lastIndexOf("/");
5460 int eidx = codePath.lastIndexOf(".");
5461 if (eidx == -1) {
5462 eidx = codePath.length();
5463 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005464 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005465 return null;
5466 }
5467 return codePath.substring(sidx+1, eidx);
5468 }
5469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 class PackageInstalledInfo {
5471 String name;
5472 int uid;
5473 PackageParser.Package pkg;
5474 int returnCode;
5475 PackageRemovedInfo removedInfo;
5476 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 /*
5479 * Install a non-existing package.
5480 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005481 private void installNewPackageLI(PackageParser.Package pkg,
5482 int parseFlags,
5483 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005484 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005485 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005486 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005487
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005488 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 res.name = pkgName;
5490 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005491 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005492 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005493 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005494 + " without first uninstalling.");
5495 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5496 return;
5497 }
5498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005500 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005502 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005503 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5504 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5505 }
5506 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005507 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005508 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 res);
5510 // delete the partially installed application. the data directory will have to be
5511 // restored if it was already existing
5512 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5513 // remove package from internal structures. Note that we want deletePackageX to
5514 // delete the package data and cache directories that it created in
5515 // scanPackageLocked, unless those directories existed before we even tried to
5516 // install.
5517 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005518 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5520 res.removedInfo);
5521 }
5522 }
5523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005524
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005525 private void replacePackageLI(PackageParser.Package pkg,
5526 int parseFlags,
5527 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005528 String installerPackageName, PackageInstalledInfo res) {
5529
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005530 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005531 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 // First find the old package info and check signatures
5533 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005534 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005535 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005536 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005537 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5538 return;
5539 }
5540 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005541 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005542 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005543 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005545 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 }
5547 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005550 PackageParser.Package pkg,
5551 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005552 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 PackageParser.Package newPackage = null;
5554 String pkgName = deletedPackage.packageName;
5555 boolean deletedPkg = true;
5556 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005557
Jacek Surazski65e13172009-04-28 15:26:38 +02005558 String oldInstallerPackageName = null;
5559 synchronized (mPackages) {
5560 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5561 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005562
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005563 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005564 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005565 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 res.removedInfo)) {
5567 // If the existing package was'nt successfully deleted
5568 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5569 deletedPkg = false;
5570 } else {
5571 // Successfully deleted the old package. Now proceed with re-installation
5572 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005573 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005575 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005576 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5577 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005578 }
5579 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005580 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005581 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 res);
5583 updatedSettings = true;
5584 }
5585 }
5586
5587 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5588 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005589 // were keeping around in case we needed them (see below) can now be deleted.
5590 // This info will be set on the res.removedInfo to clean up later on as post
5591 // install action.
5592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005593 //update signature on the new package setting
5594 //this should always succeed, since we checked the
5595 //signature earlier.
5596 synchronized(mPackages) {
5597 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5598 parseFlags, true);
5599 }
5600 } else {
5601 // remove package from internal structures. Note that we want deletePackageX to
5602 // delete the package data and cache directories that it created in
5603 // scanPackageLocked, unless those directories existed before we even tried to
5604 // install.
5605 if(updatedSettings) {
5606 deletePackageLI(
5607 pkgName, true,
5608 PackageManager.DONT_DELETE_DATA,
5609 res.removedInfo);
5610 }
5611 // Since we failed to install the new package we need to restore the old
5612 // package that we deleted.
5613 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005614 File restoreFile = new File(deletedPackage.mPath);
5615 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005616 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005617 return;
5618 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005619 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5620 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005621 // Parse old package
5622 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5623 scanPackageLI(restoreFile, parseFlags, scanMode);
5624 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005625 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5626 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005627 mSettings.writeLP();
5628 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005629 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005630 Slog.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 }
5633 }
5634 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005636 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005637 PackageParser.Package pkg,
5638 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005639 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 PackageParser.Package newPackage = null;
5641 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005642 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 PackageParser.PARSE_IS_SYSTEM;
5644 String packageName = deletedPackage.packageName;
5645 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5646 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005647 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005648 return;
5649 }
5650 PackageParser.Package oldPkg;
5651 PackageSetting oldPkgSetting;
5652 synchronized (mPackages) {
5653 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005654 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5656 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005657 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 return;
5659 }
5660 }
5661 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5662 res.removedInfo.removedPackage = packageName;
5663 // Remove existing system package
5664 removePackageLI(oldPkg, true);
5665 synchronized (mPackages) {
5666 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5667 }
5668
5669 // Successfully disabled the old package. Now proceed with re-installation
5670 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5671 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005672 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005674 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5676 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5677 }
5678 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005679 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 updatedSettings = true;
5681 }
5682
5683 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5684 //update signature on the new package setting
5685 //this should always succeed, since we checked the
5686 //signature earlier.
5687 synchronized(mPackages) {
5688 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5689 parseFlags, true);
5690 }
5691 } else {
5692 // Re installation failed. Restore old information
5693 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005694 if (newPackage != null) {
5695 removePackageLI(newPackage, true);
5696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005698 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005700 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 // Restore the old system information in Settings
5702 synchronized(mPackages) {
5703 if(updatedSettings) {
5704 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005705 mSettings.setInstallerPackageName(packageName,
5706 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 }
5708 mSettings.writeLP();
5709 }
5710 }
5711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005712
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005713 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005714 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005715 int retCode;
5716 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5717 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5718 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005719 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005720 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5721 }
5722 }
5723 return PackageManager.INSTALL_SUCCEEDED;
5724 }
5725
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005726 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005727 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005728 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 synchronized (mPackages) {
5730 //write settings. the installStatus will be incomplete at this stage.
5731 //note that the new package setting would have already been
5732 //added to mPackages. It hasn't been persisted yet.
5733 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5734 mSettings.writeLP();
5735 }
5736
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005737 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005738 != PackageManager.INSTALL_SUCCEEDED) {
5739 // Discontinue if moving dex files failed.
5740 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005741 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005742 if((res.returnCode = setPermissionsLI(newPackage))
5743 != PackageManager.INSTALL_SUCCEEDED) {
5744 if (mInstaller != null) {
5745 mInstaller.rmdex(newPackage.mScanPath);
5746 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005747 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005749 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005752 updatePermissionsLP(newPackage.packageName, newPackage,
5753 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 res.name = pkgName;
5755 res.uid = newPackage.applicationInfo.uid;
5756 res.pkg = newPackage;
5757 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005758 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005759 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5760 //to update install status
5761 mSettings.writeLP();
5762 }
5763 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005764
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005765 private void installPackageLI(InstallArgs args,
5766 boolean newInstall, PackageInstalledInfo res) {
5767 int pFlags = args.flags;
5768 String installerPackageName = args.installerPackageName;
5769 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005770 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005771 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005772 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005773 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5774 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005775 // Result object to be returned
5776 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5777
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005778 // Retrieve PackageSettings and parse package
5779 int parseFlags = PackageParser.PARSE_CHATTY |
5780 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5781 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5782 parseFlags |= mDefParseFlags;
5783 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5784 pp.setSeparateProcesses(mSeparateProcesses);
5785 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5786 null, mMetrics, parseFlags);
5787 if (pkg == null) {
5788 res.returnCode = pp.getParseError();
5789 return;
5790 }
5791 String pkgName = res.name = pkg.packageName;
5792 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5793 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5794 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5795 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005796 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005797 }
5798 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5799 res.returnCode = pp.getParseError();
5800 return;
5801 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005802 // Get rid of all references to package scan path via parser.
5803 pp = null;
5804 String oldCodePath = null;
5805 boolean systemApp = false;
5806 synchronized (mPackages) {
5807 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005808 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5809 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005810 if (pkg.mOriginalPackages != null
5811 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005812 && mPackages.containsKey(oldName)) {
5813 // This package is derived from an original package,
5814 // and this device has been updating from that original
5815 // name. We must continue using the original name, so
5816 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005817 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005818 pkgName = pkg.packageName;
5819 replace = true;
5820 } else if (mPackages.containsKey(pkgName)) {
5821 // This package, under its official name, already exists
5822 // on the device; we should replace it.
5823 replace = true;
5824 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005825 }
5826 PackageSetting ps = mSettings.mPackages.get(pkgName);
5827 if (ps != null) {
5828 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5829 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5830 systemApp = (ps.pkg.applicationInfo.flags &
5831 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005832 }
5833 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005835
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005836 if (systemApp && onSd) {
5837 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005838 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005839 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5840 return;
5841 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005842
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005843 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5844 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5845 return;
5846 }
5847 // Set application objects path explicitly after the rename
5848 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005849 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005850 replacePackageLI(pkg, parseFlags, scanMode,
5851 installerPackageName, res);
5852 } else {
5853 installNewPackageLI(pkg, parseFlags, scanMode,
5854 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855 }
5856 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005857
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005858 private int setPermissionsLI(PackageParser.Package newPackage) {
5859 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005860 int retCode = 0;
5861 // TODO Gross hack but fix later. Ideally move this to be a post installation
5862 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005863 if ((newPackage.applicationInfo.flags
5864 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5865 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 try {
5867 extractPublicFiles(newPackage, destResourceFile);
5868 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005869 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 -08005870 " forward-locked app.");
5871 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5872 } finally {
5873 //TODO clean up the extracted public files
5874 }
5875 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005876 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 newPackage.applicationInfo.uid);
5878 } else {
5879 final int filePermissions =
5880 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005881 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005882 newPackage.applicationInfo.uid);
5883 }
5884 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005885 // The permissions on the resource file was set when it was copied for
5886 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005889 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005890 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005891 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005892 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005893 // TODO Define new internal error
5894 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005895 }
5896 return PackageManager.INSTALL_SUCCEEDED;
5897 }
5898
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005899 private boolean isForwardLocked(PackageParser.Package pkg) {
5900 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005901 }
5902
5903 private void extractPublicFiles(PackageParser.Package newPackage,
5904 File publicZipFile) throws IOException {
5905 final ZipOutputStream publicZipOutStream =
5906 new ZipOutputStream(new FileOutputStream(publicZipFile));
5907 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5908
5909 // Copy manifest, resources.arsc and res directory to public zip
5910
5911 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5912 while (privateZipEntries.hasMoreElements()) {
5913 final ZipEntry zipEntry = privateZipEntries.nextElement();
5914 final String zipEntryName = zipEntry.getName();
5915 if ("AndroidManifest.xml".equals(zipEntryName)
5916 || "resources.arsc".equals(zipEntryName)
5917 || zipEntryName.startsWith("res/")) {
5918 try {
5919 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5920 } catch (IOException e) {
5921 try {
5922 publicZipOutStream.close();
5923 throw e;
5924 } finally {
5925 publicZipFile.delete();
5926 }
5927 }
5928 }
5929 }
5930
5931 publicZipOutStream.close();
5932 FileUtils.setPermissions(
5933 publicZipFile.getAbsolutePath(),
5934 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5935 -1, -1);
5936 }
5937
5938 private static void copyZipEntry(ZipEntry zipEntry,
5939 ZipFile inZipFile,
5940 ZipOutputStream outZipStream) throws IOException {
5941 byte[] buffer = new byte[4096];
5942 int num;
5943
5944 ZipEntry newEntry;
5945 if (zipEntry.getMethod() == ZipEntry.STORED) {
5946 // Preserve the STORED method of the input entry.
5947 newEntry = new ZipEntry(zipEntry);
5948 } else {
5949 // Create a new entry so that the compressed len is recomputed.
5950 newEntry = new ZipEntry(zipEntry.getName());
5951 }
5952 outZipStream.putNextEntry(newEntry);
5953
5954 InputStream data = inZipFile.getInputStream(zipEntry);
5955 while ((num = data.read(buffer)) > 0) {
5956 outZipStream.write(buffer, 0, num);
5957 }
5958 outZipStream.flush();
5959 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 private void deleteTempPackageFiles() {
5962 FilenameFilter filter = new FilenameFilter() {
5963 public boolean accept(File dir, String name) {
5964 return name.startsWith("vmdl") && name.endsWith(".tmp");
5965 }
5966 };
5967 String tmpFilesList[] = mAppInstallDir.list(filter);
5968 if(tmpFilesList == null) {
5969 return;
5970 }
5971 for(int i = 0; i < tmpFilesList.length; i++) {
5972 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5973 tmpFile.delete();
5974 }
5975 }
5976
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005977 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 File tmpPackageFile;
5979 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005980 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005982 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 return null;
5984 }
5985 try {
5986 FileUtils.setPermissions(
5987 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5988 -1, -1);
5989 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005990 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 return null;
5992 }
5993 return tmpPackageFile;
5994 }
5995
5996 public void deletePackage(final String packageName,
5997 final IPackageDeleteObserver observer,
5998 final int flags) {
5999 mContext.enforceCallingOrSelfPermission(
6000 android.Manifest.permission.DELETE_PACKAGES, null);
6001 // Queue up an async operation since the package deletion may take a little while.
6002 mHandler.post(new Runnable() {
6003 public void run() {
6004 mHandler.removeCallbacks(this);
6005 final boolean succeded = deletePackageX(packageName, true, true, flags);
6006 if (observer != null) {
6007 try {
6008 observer.packageDeleted(succeded);
6009 } catch (RemoteException e) {
6010 Log.i(TAG, "Observer no longer exists.");
6011 } //end catch
6012 } //end if
6013 } //end run
6014 });
6015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006017 /**
6018 * This method is an internal method that could be get invoked either
6019 * to delete an installed package or to clean up a failed installation.
6020 * After deleting an installed package, a broadcast is sent to notify any
6021 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006022 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006023 * installation wouldn't have sent the initial broadcast either
6024 * The key steps in deleting a package are
6025 * deleting the package information in internal structures like mPackages,
6026 * deleting the packages base directories through installd
6027 * updating mSettings to reflect current status
6028 * persisting settings for later use
6029 * sending a broadcast if necessary
6030 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6032 boolean deleteCodeAndResources, int flags) {
6033 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006034 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006036 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6037 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6038 try {
6039 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006040 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006041 return false;
6042 }
6043 } catch (RemoteException e) {
6044 }
6045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 synchronized (mInstallLock) {
6047 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
6048 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006051 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
6052 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
6053
6054 // If the removed package was a system update, the old system packaged
6055 // was re-enabled; we need to broadcast this information
6056 if (systemUpdate) {
6057 Bundle extras = new Bundle(1);
6058 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6059 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6060
6061 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
6062 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
6063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08006065 // Force a gc here.
6066 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006067 // Delete the resources here after sending the broadcast to let
6068 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006069 if (info.args != null) {
6070 synchronized (mInstallLock) {
6071 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006072 }
6073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006074 return res;
6075 }
6076
6077 static class PackageRemovedInfo {
6078 String removedPackage;
6079 int uid = -1;
6080 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006081 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006082 // Clean up resources deleted packages.
6083 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 void sendBroadcast(boolean fullRemove, boolean replacing) {
6086 Bundle extras = new Bundle(1);
6087 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6088 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6089 if (replacing) {
6090 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6091 }
6092 if (removedPackage != null) {
6093 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
6094 }
6095 if (removedUid >= 0) {
6096 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
6097 }
6098 }
6099 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006101 /*
6102 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6103 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006104 * 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 -08006105 * delete a partially installed application.
6106 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006107 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006108 int flags) {
6109 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006110 if (outInfo != null) {
6111 outInfo.removedPackage = packageName;
6112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 removePackageLI(p, true);
6114 // Retrieve object to delete permissions for shared user later on
6115 PackageSetting deletedPs;
6116 synchronized (mPackages) {
6117 deletedPs = mSettings.mPackages.get(packageName);
6118 }
6119 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006120 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006122 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006124 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 + packageName + ", retcode=" + retCode);
6126 // we don't consider this to be a failure of the core package deletion
6127 }
6128 } else {
6129 //for emulator
6130 PackageParser.Package pkg = mPackages.get(packageName);
6131 File dataDir = new File(pkg.applicationInfo.dataDir);
6132 dataDir.delete();
6133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006134 }
6135 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006136 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006137 schedulePackageCleaning(packageName);
6138
6139 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6140 if (outInfo != null) {
6141 outInfo.removedUid = mSettings.removePackageLP(packageName);
6142 }
6143 if (deletedPs != null) {
6144 updatePermissionsLP(deletedPs.name, null, false, false);
6145 if (deletedPs.sharedUser != null) {
6146 // remove permissions associated with package
6147 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6148 }
6149 }
6150 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006151 // remove from preferred activities.
6152 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6153 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6154 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6155 removed.add(pa);
6156 }
6157 }
6158 for (PreferredActivity pa : removed) {
6159 mSettings.mPreferredActivities.removeFilter(pa);
6160 }
6161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006163 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 }
6165 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 /*
6168 * Tries to delete system package.
6169 */
6170 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006171 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006172 ApplicationInfo applicationInfo = p.applicationInfo;
6173 //applicable for non-partially installed applications only
6174 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006175 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006176 return false;
6177 }
6178 PackageSetting ps = null;
6179 // Confirm if the system package has been updated
6180 // An updated system app can be deleted. This will also have to restore
6181 // the system pkg from system partition
6182 synchronized (mPackages) {
6183 ps = mSettings.getDisabledSystemPkg(p.packageName);
6184 }
6185 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006186 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 return false;
6188 } else {
6189 Log.i(TAG, "Deleting system pkg from data partition");
6190 }
6191 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006192 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006193 boolean deleteCodeAndResources = false;
6194 if (ps.versionCode < p.mVersionCode) {
6195 // Delete code and resources for downgrades
6196 deleteCodeAndResources = true;
6197 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6198 flags &= ~PackageManager.DONT_DELETE_DATA;
6199 }
6200 } else {
6201 // Preserve data by setting flag
6202 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6203 flags |= PackageManager.DONT_DELETE_DATA;
6204 }
6205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6207 if (!ret) {
6208 return false;
6209 }
6210 synchronized (mPackages) {
6211 // Reinstate the old system package
6212 mSettings.enableSystemPackageLP(p.packageName);
6213 }
6214 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006215 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006217 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006219 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006220 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006221 return false;
6222 }
6223 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006224 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 mSettings.writeLP();
6226 }
6227 return true;
6228 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6231 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6232 ApplicationInfo applicationInfo = p.applicationInfo;
6233 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006234 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 return false;
6236 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006237 if (outInfo != null) {
6238 outInfo.uid = applicationInfo.uid;
6239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006240
6241 // Delete package data from internal structures and also remove data if flag is set
6242 removePackageDataLI(p, outInfo, flags);
6243
6244 // Delete application code and resources
6245 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006246 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006247 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006248 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006249 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6250 PackageManager.INSTALL_FORWARD_LOCK : 0;
6251 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006252 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 }
6254 return true;
6255 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 /*
6258 * This method handles package deletion in general
6259 */
6260 private boolean deletePackageLI(String packageName,
6261 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6262 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006263 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 return false;
6265 }
6266 PackageParser.Package p;
6267 boolean dataOnly = false;
6268 synchronized (mPackages) {
6269 p = mPackages.get(packageName);
6270 if (p == null) {
6271 //this retrieves partially installed apps
6272 dataOnly = true;
6273 PackageSetting ps = mSettings.mPackages.get(packageName);
6274 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006275 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 return false;
6277 }
6278 p = ps.pkg;
6279 }
6280 }
6281 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006282 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 return false;
6284 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 if (dataOnly) {
6287 // Delete application data first
6288 removePackageDataLI(p, outInfo, flags);
6289 return true;
6290 }
6291 // At this point the package should have ApplicationInfo associated with it
6292 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006293 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 return false;
6295 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006296 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6298 Log.i(TAG, "Removing system package:"+p.packageName);
6299 // When an updated system application is deleted we delete the existing resources as well and
6300 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006301 ret = deleteSystemPackageLI(p, flags, outInfo);
6302 } else {
6303 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006304 // Kill application pre-emptively especially for apps on sd.
6305 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006306 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006308 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 public void clearApplicationUserData(final String packageName,
6312 final IPackageDataObserver observer) {
6313 mContext.enforceCallingOrSelfPermission(
6314 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6315 // Queue up an async operation since the package deletion may take a little while.
6316 mHandler.post(new Runnable() {
6317 public void run() {
6318 mHandler.removeCallbacks(this);
6319 final boolean succeeded;
6320 synchronized (mInstallLock) {
6321 succeeded = clearApplicationUserDataLI(packageName);
6322 }
6323 if (succeeded) {
6324 // invoke DeviceStorageMonitor's update method to clear any notifications
6325 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6326 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6327 if (dsm != null) {
6328 dsm.updateMemory();
6329 }
6330 }
6331 if(observer != null) {
6332 try {
6333 observer.onRemoveCompleted(packageName, succeeded);
6334 } catch (RemoteException e) {
6335 Log.i(TAG, "Observer no longer exists.");
6336 }
6337 } //end if observer
6338 } //end run
6339 });
6340 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 private boolean clearApplicationUserDataLI(String packageName) {
6343 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006344 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 return false;
6346 }
6347 PackageParser.Package p;
6348 boolean dataOnly = false;
6349 synchronized (mPackages) {
6350 p = mPackages.get(packageName);
6351 if(p == null) {
6352 dataOnly = true;
6353 PackageSetting ps = mSettings.mPackages.get(packageName);
6354 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006355 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006356 return false;
6357 }
6358 p = ps.pkg;
6359 }
6360 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006361 boolean useEncryptedFSDir = false;
6362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 if(!dataOnly) {
6364 //need to check this only for fully installed applications
6365 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006366 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 return false;
6368 }
6369 final ApplicationInfo applicationInfo = p.applicationInfo;
6370 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006371 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 return false;
6373 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006374 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 }
6376 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006377 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006379 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 + packageName);
6381 return false;
6382 }
6383 }
6384 return true;
6385 }
6386
6387 public void deleteApplicationCacheFiles(final String packageName,
6388 final IPackageDataObserver observer) {
6389 mContext.enforceCallingOrSelfPermission(
6390 android.Manifest.permission.DELETE_CACHE_FILES, null);
6391 // Queue up an async operation since the package deletion may take a little while.
6392 mHandler.post(new Runnable() {
6393 public void run() {
6394 mHandler.removeCallbacks(this);
6395 final boolean succeded;
6396 synchronized (mInstallLock) {
6397 succeded = deleteApplicationCacheFilesLI(packageName);
6398 }
6399 if(observer != null) {
6400 try {
6401 observer.onRemoveCompleted(packageName, succeded);
6402 } catch (RemoteException e) {
6403 Log.i(TAG, "Observer no longer exists.");
6404 }
6405 } //end if observer
6406 } //end run
6407 });
6408 }
6409
6410 private boolean deleteApplicationCacheFilesLI(String packageName) {
6411 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006412 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 return false;
6414 }
6415 PackageParser.Package p;
6416 synchronized (mPackages) {
6417 p = mPackages.get(packageName);
6418 }
6419 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006420 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 return false;
6422 }
6423 final ApplicationInfo applicationInfo = p.applicationInfo;
6424 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006425 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 return false;
6427 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006428 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006429 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006430 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006432 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 + packageName);
6434 return false;
6435 }
6436 }
6437 return true;
6438 }
6439
6440 public void getPackageSizeInfo(final String packageName,
6441 final IPackageStatsObserver observer) {
6442 mContext.enforceCallingOrSelfPermission(
6443 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6444 // Queue up an async operation since the package deletion may take a little while.
6445 mHandler.post(new Runnable() {
6446 public void run() {
6447 mHandler.removeCallbacks(this);
6448 PackageStats lStats = new PackageStats(packageName);
6449 final boolean succeded;
6450 synchronized (mInstallLock) {
6451 succeded = getPackageSizeInfoLI(packageName, lStats);
6452 }
6453 if(observer != null) {
6454 try {
6455 observer.onGetStatsCompleted(lStats, succeded);
6456 } catch (RemoteException e) {
6457 Log.i(TAG, "Observer no longer exists.");
6458 }
6459 } //end if observer
6460 } //end run
6461 });
6462 }
6463
6464 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6465 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006466 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 return false;
6468 }
6469 PackageParser.Package p;
6470 boolean dataOnly = false;
6471 synchronized (mPackages) {
6472 p = mPackages.get(packageName);
6473 if(p == null) {
6474 dataOnly = true;
6475 PackageSetting ps = mSettings.mPackages.get(packageName);
6476 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006477 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 return false;
6479 }
6480 p = ps.pkg;
6481 }
6482 }
6483 String publicSrcDir = null;
6484 if(!dataOnly) {
6485 final ApplicationInfo applicationInfo = p.applicationInfo;
6486 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006487 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 return false;
6489 }
6490 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6491 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006492 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 if (mInstaller != null) {
6494 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006495 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 if (res < 0) {
6497 return false;
6498 } else {
6499 return true;
6500 }
6501 }
6502 return true;
6503 }
6504
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 public void addPackageToPreferred(String packageName) {
6507 mContext.enforceCallingOrSelfPermission(
6508 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006509 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006510 }
6511
6512 public void removePackageFromPreferred(String packageName) {
6513 mContext.enforceCallingOrSelfPermission(
6514 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006515 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516 }
6517
6518 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006519 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 }
6521
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006522 int getUidTargetSdkVersionLockedLP(int uid) {
6523 Object obj = mSettings.getUserIdLP(uid);
6524 if (obj instanceof SharedUserSetting) {
6525 SharedUserSetting sus = (SharedUserSetting)obj;
6526 final int N = sus.packages.size();
6527 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6528 Iterator<PackageSetting> it = sus.packages.iterator();
6529 int i=0;
6530 while (it.hasNext()) {
6531 PackageSetting ps = it.next();
6532 if (ps.pkg != null) {
6533 int v = ps.pkg.applicationInfo.targetSdkVersion;
6534 if (v < vers) vers = v;
6535 }
6536 }
6537 return vers;
6538 } else if (obj instanceof PackageSetting) {
6539 PackageSetting ps = (PackageSetting)obj;
6540 if (ps.pkg != null) {
6541 return ps.pkg.applicationInfo.targetSdkVersion;
6542 }
6543 }
6544 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6545 }
6546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006547 public void addPreferredActivity(IntentFilter filter, int match,
6548 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006550 if (mContext.checkCallingOrSelfPermission(
6551 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6552 != PackageManager.PERMISSION_GRANTED) {
6553 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6554 < Build.VERSION_CODES.FROYO) {
6555 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6556 + Binder.getCallingUid());
6557 return;
6558 }
6559 mContext.enforceCallingOrSelfPermission(
6560 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6561 }
6562
6563 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006564 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6565 mSettings.mPreferredActivities.addFilter(
6566 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006567 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 }
6569 }
6570
Satish Sampath8dbe6122009-06-02 23:35:54 +01006571 public void replacePreferredActivity(IntentFilter filter, int match,
6572 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006573 if (filter.countActions() != 1) {
6574 throw new IllegalArgumentException(
6575 "replacePreferredActivity expects filter to have only 1 action.");
6576 }
6577 if (filter.countCategories() != 1) {
6578 throw new IllegalArgumentException(
6579 "replacePreferredActivity expects filter to have only 1 category.");
6580 }
6581 if (filter.countDataAuthorities() != 0
6582 || filter.countDataPaths() != 0
6583 || filter.countDataSchemes() != 0
6584 || filter.countDataTypes() != 0) {
6585 throw new IllegalArgumentException(
6586 "replacePreferredActivity expects filter to have no data authorities, " +
6587 "paths, schemes or types.");
6588 }
6589 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006590 if (mContext.checkCallingOrSelfPermission(
6591 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6592 != PackageManager.PERMISSION_GRANTED) {
6593 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6594 < Build.VERSION_CODES.FROYO) {
6595 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6596 + Binder.getCallingUid());
6597 return;
6598 }
6599 mContext.enforceCallingOrSelfPermission(
6600 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6601 }
6602
Satish Sampath8dbe6122009-06-02 23:35:54 +01006603 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6604 String action = filter.getAction(0);
6605 String category = filter.getCategory(0);
6606 while (it.hasNext()) {
6607 PreferredActivity pa = it.next();
6608 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6609 it.remove();
6610 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6611 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6612 }
6613 }
6614 addPreferredActivity(filter, match, set, activity);
6615 }
6616 }
6617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006619 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006620 int uid = Binder.getCallingUid();
6621 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006622 if (pkg == null || pkg.applicationInfo.uid != uid) {
6623 if (mContext.checkCallingOrSelfPermission(
6624 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6625 != PackageManager.PERMISSION_GRANTED) {
6626 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6627 < Build.VERSION_CODES.FROYO) {
6628 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6629 + Binder.getCallingUid());
6630 return;
6631 }
6632 mContext.enforceCallingOrSelfPermission(
6633 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6634 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006635 }
6636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006638 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 }
6640 }
6641 }
6642
6643 boolean clearPackagePreferredActivitiesLP(String packageName) {
6644 boolean changed = false;
6645 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6646 while (it.hasNext()) {
6647 PreferredActivity pa = it.next();
6648 if (pa.mActivity.getPackageName().equals(packageName)) {
6649 it.remove();
6650 changed = true;
6651 }
6652 }
6653 return changed;
6654 }
6655
6656 public int getPreferredActivities(List<IntentFilter> outFilters,
6657 List<ComponentName> outActivities, String packageName) {
6658
6659 int num = 0;
6660 synchronized (mPackages) {
6661 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6662 while (it.hasNext()) {
6663 PreferredActivity pa = it.next();
6664 if (packageName == null
6665 || pa.mActivity.getPackageName().equals(packageName)) {
6666 if (outFilters != null) {
6667 outFilters.add(new IntentFilter(pa));
6668 }
6669 if (outActivities != null) {
6670 outActivities.add(pa.mActivity);
6671 }
6672 }
6673 }
6674 }
6675
6676 return num;
6677 }
6678
6679 public void setApplicationEnabledSetting(String appPackageName,
6680 int newState, int flags) {
6681 setEnabledSetting(appPackageName, null, newState, flags);
6682 }
6683
6684 public void setComponentEnabledSetting(ComponentName componentName,
6685 int newState, int flags) {
6686 setEnabledSetting(componentName.getPackageName(),
6687 componentName.getClassName(), newState, flags);
6688 }
6689
6690 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006691 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6693 || newState == COMPONENT_ENABLED_STATE_ENABLED
6694 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6695 throw new IllegalArgumentException("Invalid new component state: "
6696 + newState);
6697 }
6698 PackageSetting pkgSetting;
6699 final int uid = Binder.getCallingUid();
6700 final int permission = mContext.checkCallingPermission(
6701 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6702 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006703 boolean sendNow = false;
6704 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006705 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006707 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006709 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006711 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006713 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006714 }
6715 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006716 "Unknown component: " + packageName
6717 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 }
6719 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6720 throw new SecurityException(
6721 "Permission Denial: attempt to change component state from pid="
6722 + Binder.getCallingPid()
6723 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6724 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006725 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006726 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006727 if (pkgSetting.enabled == newState) {
6728 // Nothing to do
6729 return;
6730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 pkgSetting.enabled = newState;
6732 } else {
6733 // We're dealing with a component level state change
6734 switch (newState) {
6735 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006736 if (!pkgSetting.enableComponentLP(className)) {
6737 return;
6738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006739 break;
6740 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006741 if (!pkgSetting.disableComponentLP(className)) {
6742 return;
6743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006744 break;
6745 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006746 if (!pkgSetting.restoreComponentLP(className)) {
6747 return;
6748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006749 break;
6750 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006751 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006752 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006753 }
6754 }
6755 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006756 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006757 components = mPendingBroadcasts.get(packageName);
6758 boolean newPackage = components == null;
6759 if (newPackage) {
6760 components = new ArrayList<String>();
6761 }
6762 if (!components.contains(componentName)) {
6763 components.add(componentName);
6764 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006765 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6766 sendNow = true;
6767 // Purge entry from pending broadcast list if another one exists already
6768 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006769 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006770 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006771 if (newPackage) {
6772 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006773 }
6774 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6775 // Schedule a message
6776 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6777 }
6778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006779 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 long callingId = Binder.clearCallingIdentity();
6782 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006783 if (sendNow) {
6784 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006785 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 } finally {
6788 Binder.restoreCallingIdentity(callingId);
6789 }
6790 }
6791
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006792 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006793 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6794 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6795 + " components=" + componentNames);
6796 Bundle extras = new Bundle(4);
6797 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6798 String nameList[] = new String[componentNames.size()];
6799 componentNames.toArray(nameList);
6800 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006801 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6802 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006803 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006804 }
6805
Jacek Surazski65e13172009-04-28 15:26:38 +02006806 public String getInstallerPackageName(String packageName) {
6807 synchronized (mPackages) {
6808 PackageSetting pkg = mSettings.mPackages.get(packageName);
6809 if (pkg == null) {
6810 throw new IllegalArgumentException("Unknown package: " + packageName);
6811 }
6812 return pkg.installerPackageName;
6813 }
6814 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006816 public int getApplicationEnabledSetting(String appPackageName) {
6817 synchronized (mPackages) {
6818 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6819 if (pkg == null) {
6820 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6821 }
6822 return pkg.enabled;
6823 }
6824 }
6825
6826 public int getComponentEnabledSetting(ComponentName componentName) {
6827 synchronized (mPackages) {
6828 final String packageNameStr = componentName.getPackageName();
6829 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6830 if (pkg == null) {
6831 throw new IllegalArgumentException("Unknown component: " + componentName);
6832 }
6833 final String classNameStr = componentName.getClassName();
6834 return pkg.currentEnabledStateLP(classNameStr);
6835 }
6836 }
6837
6838 public void enterSafeMode() {
6839 if (!mSystemReady) {
6840 mSafeMode = true;
6841 }
6842 }
6843
6844 public void systemReady() {
6845 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006846
6847 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006848 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006849 mContext.getContentResolver(),
6850 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006851 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006852 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006853 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006855 }
6856
6857 public boolean isSafeMode() {
6858 return mSafeMode;
6859 }
6860
6861 public boolean hasSystemUidErrors() {
6862 return mHasSystemUidErrors;
6863 }
6864
6865 static String arrayToString(int[] array) {
6866 StringBuffer buf = new StringBuffer(128);
6867 buf.append('[');
6868 if (array != null) {
6869 for (int i=0; i<array.length; i++) {
6870 if (i > 0) buf.append(", ");
6871 buf.append(array[i]);
6872 }
6873 }
6874 buf.append(']');
6875 return buf.toString();
6876 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006878 @Override
6879 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6880 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6881 != PackageManager.PERMISSION_GRANTED) {
6882 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6883 + Binder.getCallingPid()
6884 + ", uid=" + Binder.getCallingUid()
6885 + " without permission "
6886 + android.Manifest.permission.DUMP);
6887 return;
6888 }
6889
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006890 String packageName = null;
6891
6892 int opti = 0;
6893 while (opti < args.length) {
6894 String opt = args[opti];
6895 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6896 break;
6897 }
6898 opti++;
6899 if ("-a".equals(opt)) {
6900 // Right now we only know how to print all.
6901 } else if ("-h".equals(opt)) {
6902 pw.println("Package manager dump options:");
6903 pw.println(" [-h] [cmd] ...");
6904 pw.println(" cmd may be one of:");
6905 pw.println(" [package.name]: info about given package");
6906 return;
6907 } else {
6908 pw.println("Unknown argument: " + opt + "; use -h for help");
6909 }
6910 }
6911
6912 // Is the caller requesting to dump a particular piece of data?
6913 if (opti < args.length) {
6914 String cmd = args[opti];
6915 opti++;
6916 // Is this a package name?
6917 if ("android".equals(cmd) || cmd.contains(".")) {
6918 packageName = cmd;
6919 }
6920 }
6921
6922 boolean printedTitle = false;
6923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006924 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006925 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6926 printedTitle = true;
6927 }
6928 if (mReceivers.dump(pw, printedTitle
6929 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6930 " ", packageName)) {
6931 printedTitle = true;
6932 }
6933 if (mServices.dump(pw, printedTitle
6934 ? "\nService Resolver Table:" : "Service Resolver Table:",
6935 " ", packageName)) {
6936 printedTitle = true;
6937 }
6938 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6939 ? "\nPreferred Activities:" : "Preferred Activities:",
6940 " ", packageName)) {
6941 printedTitle = true;
6942 }
6943 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006944 {
6945 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006946 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6947 continue;
6948 }
6949 if (!printedSomething) {
6950 if (printedTitle) pw.println(" ");
6951 pw.println("Permissions:");
6952 printedSomething = true;
6953 printedTitle = true;
6954 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006955 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6956 pw.print(Integer.toHexString(System.identityHashCode(p)));
6957 pw.println("):");
6958 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6959 pw.print(" uid="); pw.print(p.uid);
6960 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006961 pw.print(" type="); pw.print(p.type);
6962 pw.print(" prot="); pw.println(p.protectionLevel);
6963 if (p.packageSetting != null) {
6964 pw.print(" packageSetting="); pw.println(p.packageSetting);
6965 }
6966 if (p.perm != null) {
6967 pw.print(" perm="); pw.println(p.perm);
6968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 }
6970 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006971 printedSomething = false;
6972 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006973 {
6974 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006975 if (packageName != null && !packageName.equals(ps.realName)
6976 && !packageName.equals(ps.name)) {
6977 continue;
6978 }
6979 if (!printedSomething) {
6980 if (printedTitle) pw.println(" ");
6981 pw.println("Packages:");
6982 printedSomething = true;
6983 printedTitle = true;
6984 }
6985 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006986 pw.print(" Package [");
6987 pw.print(ps.realName != null ? ps.realName : ps.name);
6988 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006989 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6990 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006991 if (ps.realName != null) {
6992 pw.print(" compat name="); pw.println(ps.name);
6993 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006994 pw.print(" userId="); pw.print(ps.userId);
6995 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6996 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6997 pw.print(" pkg="); pw.println(ps.pkg);
6998 pw.print(" codePath="); pw.println(ps.codePathString);
6999 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007000 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007001 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007002 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007003 pw.print(" supportsScreens=[");
7004 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007005 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007006 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007007 if (!first) pw.print(", ");
7008 first = false;
7009 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007011 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007012 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007013 if (!first) pw.print(", ");
7014 first = false;
7015 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007016 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007017 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007018 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007019 if (!first) pw.print(", ");
7020 first = false;
7021 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007022 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007023 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007024 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007025 if (!first) pw.print(", ");
7026 first = false;
7027 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007028 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007029 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007030 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7031 if (!first) pw.print(", ");
7032 first = false;
7033 pw.print("anyDensity");
7034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007036 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007037 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7038 pw.print(" signatures="); pw.println(ps.signatures);
7039 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007040 pw.print(" haveGids="); pw.println(ps.haveGids);
7041 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007042 pw.print(" installStatus="); pw.print(ps.installStatus);
7043 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 if (ps.disabledComponents.size() > 0) {
7045 pw.println(" disabledComponents:");
7046 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007047 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007048 }
7049 }
7050 if (ps.enabledComponents.size() > 0) {
7051 pw.println(" enabledComponents:");
7052 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007053 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007054 }
7055 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007056 if (ps.grantedPermissions.size() > 0) {
7057 pw.println(" grantedPermissions:");
7058 for (String s : ps.grantedPermissions) {
7059 pw.print(" "); pw.println(s);
7060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007062 }
7063 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007064 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007065 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007066 for (HashMap.Entry<String, String> e
7067 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007068 if (packageName != null && !packageName.equals(e.getKey())
7069 && !packageName.equals(e.getValue())) {
7070 continue;
7071 }
7072 if (!printedSomething) {
7073 if (printedTitle) pw.println(" ");
7074 pw.println("Renamed packages:");
7075 printedSomething = true;
7076 printedTitle = true;
7077 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007078 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7079 pw.println(e.getValue());
7080 }
7081 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007082 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007083 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007084 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007085 if (packageName != null && !packageName.equals(ps.realName)
7086 && !packageName.equals(ps.name)) {
7087 continue;
7088 }
7089 if (!printedSomething) {
7090 if (printedTitle) pw.println(" ");
7091 pw.println("Hidden system packages:");
7092 printedSomething = true;
7093 printedTitle = true;
7094 }
7095 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007096 pw.print(ps.realName != null ? ps.realName : ps.name);
7097 pw.print("] (");
7098 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7099 pw.println("):");
7100 if (ps.realName != null) {
7101 pw.print(" compat name="); pw.println(ps.name);
7102 }
7103 pw.print(" userId="); pw.println(ps.userId);
7104 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7105 pw.print(" codePath="); pw.println(ps.codePathString);
7106 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7107 }
7108 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007109 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007110 {
7111 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007112 if (packageName != null && su != packageSharedUser) {
7113 continue;
7114 }
7115 if (!printedSomething) {
7116 if (printedTitle) pw.println(" ");
7117 pw.println("Shared users:");
7118 printedSomething = true;
7119 printedTitle = true;
7120 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007121 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7122 pw.print(Integer.toHexString(System.identityHashCode(su)));
7123 pw.println("):");
7124 pw.print(" userId="); pw.print(su.userId);
7125 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007126 pw.println(" grantedPermissions:");
7127 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007128 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007130 }
7131 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007132
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007133 if (packageName == null) {
7134 if (printedTitle) pw.println(" ");
7135 printedTitle = true;
7136 pw.println("Settings parse messages:");
7137 pw.println(mSettings.mReadMessages.toString());
7138
7139 pw.println(" ");
7140 pw.println("Package warning messages:");
7141 File fname = getSettingsProblemFile();
7142 FileInputStream in;
7143 try {
7144 in = new FileInputStream(fname);
7145 int avail = in.available();
7146 byte[] data = new byte[avail];
7147 in.read(data);
7148 pw.println(new String(data));
7149 } catch (FileNotFoundException e) {
7150 } catch (IOException e) {
7151 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007153 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007154
7155 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007156 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007157 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007158 if (packageName != null && !packageName.equals(p.info.packageName)) {
7159 continue;
7160 }
7161 if (!printedSomething) {
7162 if (printedTitle) pw.println(" ");
7163 pw.println("Registered ContentProviders:");
7164 printedSomething = true;
7165 printedTitle = true;
7166 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007167 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007168 pw.println(p.toString());
7169 }
7170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007171 }
7172
7173 static final class BasePermission {
7174 final static int TYPE_NORMAL = 0;
7175 final static int TYPE_BUILTIN = 1;
7176 final static int TYPE_DYNAMIC = 2;
7177
7178 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007179 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007180 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007181 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007182 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007183 PackageParser.Permission perm;
7184 PermissionInfo pendingInfo;
7185 int uid;
7186 int[] gids;
7187
7188 BasePermission(String _name, String _sourcePackage, int _type) {
7189 name = _name;
7190 sourcePackage = _sourcePackage;
7191 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007192 // Default to most conservative protection level.
7193 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7194 }
7195
7196 public String toString() {
7197 return "BasePermission{"
7198 + Integer.toHexString(System.identityHashCode(this))
7199 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007200 }
7201 }
7202
7203 static class PackageSignatures {
7204 private Signature[] mSignatures;
7205
7206 PackageSignatures(Signature[] sigs) {
7207 assignSignatures(sigs);
7208 }
7209
7210 PackageSignatures() {
7211 }
7212
7213 void writeXml(XmlSerializer serializer, String tagName,
7214 ArrayList<Signature> pastSignatures) throws IOException {
7215 if (mSignatures == null) {
7216 return;
7217 }
7218 serializer.startTag(null, tagName);
7219 serializer.attribute(null, "count",
7220 Integer.toString(mSignatures.length));
7221 for (int i=0; i<mSignatures.length; i++) {
7222 serializer.startTag(null, "cert");
7223 final Signature sig = mSignatures[i];
7224 final int sigHash = sig.hashCode();
7225 final int numPast = pastSignatures.size();
7226 int j;
7227 for (j=0; j<numPast; j++) {
7228 Signature pastSig = pastSignatures.get(j);
7229 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7230 serializer.attribute(null, "index", Integer.toString(j));
7231 break;
7232 }
7233 }
7234 if (j >= numPast) {
7235 pastSignatures.add(sig);
7236 serializer.attribute(null, "index", Integer.toString(numPast));
7237 serializer.attribute(null, "key", sig.toCharsString());
7238 }
7239 serializer.endTag(null, "cert");
7240 }
7241 serializer.endTag(null, tagName);
7242 }
7243
7244 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7245 throws IOException, XmlPullParserException {
7246 String countStr = parser.getAttributeValue(null, "count");
7247 if (countStr == null) {
7248 reportSettingsProblem(Log.WARN,
7249 "Error in package manager settings: <signatures> has"
7250 + " no count at " + parser.getPositionDescription());
7251 XmlUtils.skipCurrentTag(parser);
7252 }
7253 final int count = Integer.parseInt(countStr);
7254 mSignatures = new Signature[count];
7255 int pos = 0;
7256
7257 int outerDepth = parser.getDepth();
7258 int type;
7259 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7260 && (type != XmlPullParser.END_TAG
7261 || parser.getDepth() > outerDepth)) {
7262 if (type == XmlPullParser.END_TAG
7263 || type == XmlPullParser.TEXT) {
7264 continue;
7265 }
7266
7267 String tagName = parser.getName();
7268 if (tagName.equals("cert")) {
7269 if (pos < count) {
7270 String index = parser.getAttributeValue(null, "index");
7271 if (index != null) {
7272 try {
7273 int idx = Integer.parseInt(index);
7274 String key = parser.getAttributeValue(null, "key");
7275 if (key == null) {
7276 if (idx >= 0 && idx < pastSignatures.size()) {
7277 Signature sig = pastSignatures.get(idx);
7278 if (sig != null) {
7279 mSignatures[pos] = pastSignatures.get(idx);
7280 pos++;
7281 } else {
7282 reportSettingsProblem(Log.WARN,
7283 "Error in package manager settings: <cert> "
7284 + "index " + index + " is not defined at "
7285 + parser.getPositionDescription());
7286 }
7287 } else {
7288 reportSettingsProblem(Log.WARN,
7289 "Error in package manager settings: <cert> "
7290 + "index " + index + " is out of bounds at "
7291 + parser.getPositionDescription());
7292 }
7293 } else {
7294 while (pastSignatures.size() <= idx) {
7295 pastSignatures.add(null);
7296 }
7297 Signature sig = new Signature(key);
7298 pastSignatures.set(idx, sig);
7299 mSignatures[pos] = sig;
7300 pos++;
7301 }
7302 } catch (NumberFormatException e) {
7303 reportSettingsProblem(Log.WARN,
7304 "Error in package manager settings: <cert> "
7305 + "index " + index + " is not a number at "
7306 + parser.getPositionDescription());
7307 }
7308 } else {
7309 reportSettingsProblem(Log.WARN,
7310 "Error in package manager settings: <cert> has"
7311 + " no index at " + parser.getPositionDescription());
7312 }
7313 } else {
7314 reportSettingsProblem(Log.WARN,
7315 "Error in package manager settings: too "
7316 + "many <cert> tags, expected " + count
7317 + " at " + parser.getPositionDescription());
7318 }
7319 } else {
7320 reportSettingsProblem(Log.WARN,
7321 "Unknown element under <cert>: "
7322 + parser.getName());
7323 }
7324 XmlUtils.skipCurrentTag(parser);
7325 }
7326
7327 if (pos < count) {
7328 // Should never happen -- there is an error in the written
7329 // settings -- but if it does we don't want to generate
7330 // a bad array.
7331 Signature[] newSigs = new Signature[pos];
7332 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7333 mSignatures = newSigs;
7334 }
7335 }
7336
7337 /**
7338 * If any of the given 'sigs' is contained in the existing signatures,
7339 * then completely replace the current signatures with the ones in
7340 * 'sigs'. This is used for updating an existing package to a newly
7341 * installed version.
7342 */
7343 boolean updateSignatures(Signature[] sigs, boolean update) {
7344 if (mSignatures == null) {
7345 if (update) {
7346 assignSignatures(sigs);
7347 }
7348 return true;
7349 }
7350 if (sigs == null) {
7351 return false;
7352 }
7353
7354 for (int i=0; i<sigs.length; i++) {
7355 Signature sig = sigs[i];
7356 for (int j=0; j<mSignatures.length; j++) {
7357 if (mSignatures[j].equals(sig)) {
7358 if (update) {
7359 assignSignatures(sigs);
7360 }
7361 return true;
7362 }
7363 }
7364 }
7365 return false;
7366 }
7367
7368 /**
7369 * If any of the given 'sigs' is contained in the existing signatures,
7370 * then add in any new signatures found in 'sigs'. This is used for
7371 * including a new package into an existing shared user id.
7372 */
7373 boolean mergeSignatures(Signature[] sigs, boolean update) {
7374 if (mSignatures == null) {
7375 if (update) {
7376 assignSignatures(sigs);
7377 }
7378 return true;
7379 }
7380 if (sigs == null) {
7381 return false;
7382 }
7383
7384 Signature[] added = null;
7385 int addedCount = 0;
7386 boolean haveMatch = false;
7387 for (int i=0; i<sigs.length; i++) {
7388 Signature sig = sigs[i];
7389 boolean found = false;
7390 for (int j=0; j<mSignatures.length; j++) {
7391 if (mSignatures[j].equals(sig)) {
7392 found = true;
7393 haveMatch = true;
7394 break;
7395 }
7396 }
7397
7398 if (!found) {
7399 if (added == null) {
7400 added = new Signature[sigs.length];
7401 }
7402 added[i] = sig;
7403 addedCount++;
7404 }
7405 }
7406
7407 if (!haveMatch) {
7408 // Nothing matched -- reject the new signatures.
7409 return false;
7410 }
7411 if (added == null) {
7412 // Completely matched -- nothing else to do.
7413 return true;
7414 }
7415
7416 // Add additional signatures in.
7417 if (update) {
7418 Signature[] total = new Signature[addedCount+mSignatures.length];
7419 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
7420 int j = mSignatures.length;
7421 for (int i=0; i<added.length; i++) {
7422 if (added[i] != null) {
7423 total[j] = added[i];
7424 j++;
7425 }
7426 }
7427 mSignatures = total;
7428 }
7429 return true;
7430 }
7431
7432 private void assignSignatures(Signature[] sigs) {
7433 if (sigs == null) {
7434 mSignatures = null;
7435 return;
7436 }
7437 mSignatures = new Signature[sigs.length];
7438 for (int i=0; i<sigs.length; i++) {
7439 mSignatures[i] = sigs[i];
7440 }
7441 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007443 @Override
7444 public String toString() {
7445 StringBuffer buf = new StringBuffer(128);
7446 buf.append("PackageSignatures{");
7447 buf.append(Integer.toHexString(System.identityHashCode(this)));
7448 buf.append(" [");
7449 if (mSignatures != null) {
7450 for (int i=0; i<mSignatures.length; i++) {
7451 if (i > 0) buf.append(", ");
7452 buf.append(Integer.toHexString(
7453 System.identityHashCode(mSignatures[i])));
7454 }
7455 }
7456 buf.append("]}");
7457 return buf.toString();
7458 }
7459 }
7460
7461 static class PreferredActivity extends IntentFilter {
7462 final int mMatch;
7463 final String[] mSetPackages;
7464 final String[] mSetClasses;
7465 final String[] mSetComponents;
7466 final ComponentName mActivity;
7467 final String mShortActivity;
7468 String mParseError;
7469
7470 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7471 ComponentName activity) {
7472 super(filter);
7473 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7474 mActivity = activity;
7475 mShortActivity = activity.flattenToShortString();
7476 mParseError = null;
7477 if (set != null) {
7478 final int N = set.length;
7479 String[] myPackages = new String[N];
7480 String[] myClasses = new String[N];
7481 String[] myComponents = new String[N];
7482 for (int i=0; i<N; i++) {
7483 ComponentName cn = set[i];
7484 if (cn == null) {
7485 mSetPackages = null;
7486 mSetClasses = null;
7487 mSetComponents = null;
7488 return;
7489 }
7490 myPackages[i] = cn.getPackageName().intern();
7491 myClasses[i] = cn.getClassName().intern();
7492 myComponents[i] = cn.flattenToShortString().intern();
7493 }
7494 mSetPackages = myPackages;
7495 mSetClasses = myClasses;
7496 mSetComponents = myComponents;
7497 } else {
7498 mSetPackages = null;
7499 mSetClasses = null;
7500 mSetComponents = null;
7501 }
7502 }
7503
7504 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7505 IOException {
7506 mShortActivity = parser.getAttributeValue(null, "name");
7507 mActivity = ComponentName.unflattenFromString(mShortActivity);
7508 if (mActivity == null) {
7509 mParseError = "Bad activity name " + mShortActivity;
7510 }
7511 String matchStr = parser.getAttributeValue(null, "match");
7512 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7513 String setCountStr = parser.getAttributeValue(null, "set");
7514 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7515
7516 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7517 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7518 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7519
7520 int setPos = 0;
7521
7522 int outerDepth = parser.getDepth();
7523 int type;
7524 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7525 && (type != XmlPullParser.END_TAG
7526 || parser.getDepth() > outerDepth)) {
7527 if (type == XmlPullParser.END_TAG
7528 || type == XmlPullParser.TEXT) {
7529 continue;
7530 }
7531
7532 String tagName = parser.getName();
7533 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7534 // + parser.getDepth() + " tag=" + tagName);
7535 if (tagName.equals("set")) {
7536 String name = parser.getAttributeValue(null, "name");
7537 if (name == null) {
7538 if (mParseError == null) {
7539 mParseError = "No name in set tag in preferred activity "
7540 + mShortActivity;
7541 }
7542 } else if (setPos >= setCount) {
7543 if (mParseError == null) {
7544 mParseError = "Too many set tags in preferred activity "
7545 + mShortActivity;
7546 }
7547 } else {
7548 ComponentName cn = ComponentName.unflattenFromString(name);
7549 if (cn == null) {
7550 if (mParseError == null) {
7551 mParseError = "Bad set name " + name + " in preferred activity "
7552 + mShortActivity;
7553 }
7554 } else {
7555 myPackages[setPos] = cn.getPackageName();
7556 myClasses[setPos] = cn.getClassName();
7557 myComponents[setPos] = name;
7558 setPos++;
7559 }
7560 }
7561 XmlUtils.skipCurrentTag(parser);
7562 } else if (tagName.equals("filter")) {
7563 //Log.i(TAG, "Starting to parse filter...");
7564 readFromXml(parser);
7565 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7566 // + parser.getDepth() + " tag=" + parser.getName());
7567 } else {
7568 reportSettingsProblem(Log.WARN,
7569 "Unknown element under <preferred-activities>: "
7570 + parser.getName());
7571 XmlUtils.skipCurrentTag(parser);
7572 }
7573 }
7574
7575 if (setPos != setCount) {
7576 if (mParseError == null) {
7577 mParseError = "Not enough set tags (expected " + setCount
7578 + " but found " + setPos + ") in " + mShortActivity;
7579 }
7580 }
7581
7582 mSetPackages = myPackages;
7583 mSetClasses = myClasses;
7584 mSetComponents = myComponents;
7585 }
7586
7587 public void writeToXml(XmlSerializer serializer) throws IOException {
7588 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7589 serializer.attribute(null, "name", mShortActivity);
7590 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7591 serializer.attribute(null, "set", Integer.toString(NS));
7592 for (int s=0; s<NS; s++) {
7593 serializer.startTag(null, "set");
7594 serializer.attribute(null, "name", mSetComponents[s]);
7595 serializer.endTag(null, "set");
7596 }
7597 serializer.startTag(null, "filter");
7598 super.writeToXml(serializer);
7599 serializer.endTag(null, "filter");
7600 }
7601
7602 boolean sameSet(List<ResolveInfo> query, int priority) {
7603 if (mSetPackages == null) return false;
7604 final int NQ = query.size();
7605 final int NS = mSetPackages.length;
7606 int numMatch = 0;
7607 for (int i=0; i<NQ; i++) {
7608 ResolveInfo ri = query.get(i);
7609 if (ri.priority != priority) continue;
7610 ActivityInfo ai = ri.activityInfo;
7611 boolean good = false;
7612 for (int j=0; j<NS; j++) {
7613 if (mSetPackages[j].equals(ai.packageName)
7614 && mSetClasses[j].equals(ai.name)) {
7615 numMatch++;
7616 good = true;
7617 break;
7618 }
7619 }
7620 if (!good) return false;
7621 }
7622 return numMatch == NS;
7623 }
7624 }
7625
7626 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007627 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007629 HashSet<String> grantedPermissions = new HashSet<String>();
7630 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007633 setFlags(pkgFlags);
7634 }
7635
7636 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007637 this.pkgFlags = pkgFlags & (
7638 ApplicationInfo.FLAG_SYSTEM |
7639 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Brown767225d2010-03-30 23:49:17 -07007640 ApplicationInfo.FLAG_EXTERNAL_STORAGE |;
7641 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007642 }
7643 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645 /**
7646 * Settings base class for pending and resolved classes.
7647 */
7648 static class PackageSettingBase extends GrantedPermissions {
7649 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007650 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007651 File codePath;
7652 String codePathString;
7653 File resourcePath;
7654 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007655 private long timeStamp;
7656 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007657 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007658
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007659 boolean uidError;
7660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007661 PackageSignatures signatures = new PackageSignatures();
7662
7663 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007664 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007666 /* Explicitly disabled components */
7667 HashSet<String> disabledComponents = new HashSet<String>(0);
7668 /* Explicitly enabled components */
7669 HashSet<String> enabledComponents = new HashSet<String>(0);
7670 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7671 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007672
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007673 PackageSettingBase origPackage;
7674
Jacek Surazski65e13172009-04-28 15:26:38 +02007675 /* package name of the app that installed this package */
7676 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007677
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007678 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007679 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007680 super(pkgFlags);
7681 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007682 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007683 init(codePath, resourcePath, pVersionCode);
7684 }
7685
7686 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 this.codePath = codePath;
7688 this.codePathString = codePath.toString();
7689 this.resourcePath = resourcePath;
7690 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007691 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007693
Jacek Surazski65e13172009-04-28 15:26:38 +02007694 public void setInstallerPackageName(String packageName) {
7695 installerPackageName = packageName;
7696 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007697
Jacek Surazski65e13172009-04-28 15:26:38 +02007698 String getInstallerPackageName() {
7699 return installerPackageName;
7700 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007702 public void setInstallStatus(int newStatus) {
7703 installStatus = newStatus;
7704 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007706 public int getInstallStatus() {
7707 return installStatus;
7708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710 public void setTimeStamp(long newStamp) {
7711 if (newStamp != timeStamp) {
7712 timeStamp = newStamp;
7713 timeStampString = Long.toString(newStamp);
7714 }
7715 }
7716
7717 public void setTimeStamp(long newStamp, String newStampStr) {
7718 timeStamp = newStamp;
7719 timeStampString = newStampStr;
7720 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722 public long getTimeStamp() {
7723 return timeStamp;
7724 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726 public String getTimeStampStr() {
7727 return timeStampString;
7728 }
7729
7730 public void copyFrom(PackageSettingBase base) {
7731 grantedPermissions = base.grantedPermissions;
7732 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007734 timeStamp = base.timeStamp;
7735 timeStampString = base.timeStampString;
7736 signatures = base.signatures;
7737 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007738 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007739 disabledComponents = base.disabledComponents;
7740 enabledComponents = base.enabledComponents;
7741 enabled = base.enabled;
7742 installStatus = base.installStatus;
7743 }
7744
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007745 boolean enableComponentLP(String componentClassName) {
7746 boolean changed = disabledComponents.remove(componentClassName);
7747 changed |= enabledComponents.add(componentClassName);
7748 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007749 }
7750
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007751 boolean disableComponentLP(String componentClassName) {
7752 boolean changed = enabledComponents.remove(componentClassName);
7753 changed |= disabledComponents.add(componentClassName);
7754 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007755 }
7756
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007757 boolean restoreComponentLP(String componentClassName) {
7758 boolean changed = enabledComponents.remove(componentClassName);
7759 changed |= disabledComponents.remove(componentClassName);
7760 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007761 }
7762
7763 int currentEnabledStateLP(String componentName) {
7764 if (enabledComponents.contains(componentName)) {
7765 return COMPONENT_ENABLED_STATE_ENABLED;
7766 } else if (disabledComponents.contains(componentName)) {
7767 return COMPONENT_ENABLED_STATE_DISABLED;
7768 } else {
7769 return COMPONENT_ENABLED_STATE_DEFAULT;
7770 }
7771 }
7772 }
7773
7774 /**
7775 * Settings data for a particular package we know about.
7776 */
7777 static final class PackageSetting extends PackageSettingBase {
7778 int userId;
7779 PackageParser.Package pkg;
7780 SharedUserSetting sharedUser;
7781
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007782 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007783 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007784 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 @Override
7788 public String toString() {
7789 return "PackageSetting{"
7790 + Integer.toHexString(System.identityHashCode(this))
7791 + " " + name + "/" + userId + "}";
7792 }
7793 }
7794
7795 /**
7796 * Settings data for a particular shared user ID we know about.
7797 */
7798 static final class SharedUserSetting extends GrantedPermissions {
7799 final String name;
7800 int userId;
7801 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7802 final PackageSignatures signatures = new PackageSignatures();
7803
7804 SharedUserSetting(String _name, int _pkgFlags) {
7805 super(_pkgFlags);
7806 name = _name;
7807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 @Override
7810 public String toString() {
7811 return "SharedUserSetting{"
7812 + Integer.toHexString(System.identityHashCode(this))
7813 + " " + name + "/" + userId + "}";
7814 }
7815 }
7816
7817 /**
7818 * Holds information about dynamic settings.
7819 */
7820 private static final class Settings {
7821 private final File mSettingsFilename;
7822 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007823 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 private final HashMap<String, PackageSetting> mPackages =
7825 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 // List of replaced system applications
7827 final HashMap<String, PackageSetting> mDisabledSysPackages =
7828 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007830 // The user's preferred activities associated with particular intent
7831 // filters.
7832 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7833 new IntentResolver<PreferredActivity, PreferredActivity>() {
7834 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007835 protected String packageForFilter(PreferredActivity filter) {
7836 return filter.mActivity.getPackageName();
7837 }
7838 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007839 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007840 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007841 out.print(prefix); out.print(
7842 Integer.toHexString(System.identityHashCode(filter)));
7843 out.print(' ');
7844 out.print(filter.mActivity.flattenToShortString());
7845 out.print(" match=0x");
7846 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007848 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007849 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007850 out.print(prefix); out.print(" ");
7851 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 }
7853 }
7854 }
7855 };
7856 private final HashMap<String, SharedUserSetting> mSharedUsers =
7857 new HashMap<String, SharedUserSetting>();
7858 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7859 private final SparseArray<Object> mOtherUserIds =
7860 new SparseArray<Object>();
7861
7862 // For reading/writing settings file.
7863 private final ArrayList<Signature> mPastSignatures =
7864 new ArrayList<Signature>();
7865
7866 // Mapping from permission names to info about them.
7867 final HashMap<String, BasePermission> mPermissions =
7868 new HashMap<String, BasePermission>();
7869
7870 // Mapping from permission tree names to info about them.
7871 final HashMap<String, BasePermission> mPermissionTrees =
7872 new HashMap<String, BasePermission>();
7873
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007874 // Packages that have been uninstalled and still need their external
7875 // storage data deleted.
7876 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7877
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007878 // Packages that have been renamed since they were first installed.
7879 // Keys are the new names of the packages, values are the original
7880 // names. The packages appear everwhere else under their original
7881 // names.
7882 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 private final StringBuilder mReadMessages = new StringBuilder();
7885
7886 private static final class PendingPackage extends PackageSettingBase {
7887 final int sharedId;
7888
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007889 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007890 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007891 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 this.sharedId = sharedId;
7893 }
7894 }
7895 private final ArrayList<PendingPackage> mPendingPackages
7896 = new ArrayList<PendingPackage>();
7897
7898 Settings() {
7899 File dataDir = Environment.getDataDirectory();
7900 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007901 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7902 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007904 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 FileUtils.setPermissions(systemDir.toString(),
7906 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7907 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7908 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007909 FileUtils.setPermissions(systemSecureDir.toString(),
7910 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7911 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7912 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007913 mSettingsFilename = new File(systemDir, "packages.xml");
7914 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007915 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 }
7917
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007918 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007919 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007920 int pkgFlags, boolean create, boolean add) {
7921 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007922 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007923 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 return p;
7925 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007926
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007927 PackageSetting peekPackageLP(String name) {
7928 return mPackages.get(name);
7929 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007930 PackageSetting p = mPackages.get(name);
7931 if (p != null && p.codePath.getPath().equals(codePath)) {
7932 return p;
7933 }
7934 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007935 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007938 void setInstallStatus(String pkgName, int status) {
7939 PackageSetting p = mPackages.get(pkgName);
7940 if(p != null) {
7941 if(p.getInstallStatus() != status) {
7942 p.setInstallStatus(status);
7943 }
7944 }
7945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007946
Jacek Surazski65e13172009-04-28 15:26:38 +02007947 void setInstallerPackageName(String pkgName,
7948 String installerPkgName) {
7949 PackageSetting p = mPackages.get(pkgName);
7950 if(p != null) {
7951 p.setInstallerPackageName(installerPkgName);
7952 }
7953 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007954
Jacek Surazski65e13172009-04-28 15:26:38 +02007955 String getInstallerPackageName(String pkgName) {
7956 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007957 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007958 }
7959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 int getInstallStatus(String pkgName) {
7961 PackageSetting p = mPackages.get(pkgName);
7962 if(p != null) {
7963 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007965 return -1;
7966 }
7967
7968 SharedUserSetting getSharedUserLP(String name,
7969 int pkgFlags, boolean create) {
7970 SharedUserSetting s = mSharedUsers.get(name);
7971 if (s == null) {
7972 if (!create) {
7973 return null;
7974 }
7975 s = new SharedUserSetting(name, pkgFlags);
7976 if (MULTIPLE_APPLICATION_UIDS) {
7977 s.userId = newUserIdLP(s);
7978 } else {
7979 s.userId = FIRST_APPLICATION_UID;
7980 }
7981 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7982 // < 0 means we couldn't assign a userid; fall out and return
7983 // s, which is currently null
7984 if (s.userId >= 0) {
7985 mSharedUsers.put(name, s);
7986 }
7987 }
7988
7989 return s;
7990 }
7991
7992 int disableSystemPackageLP(String name) {
7993 PackageSetting p = mPackages.get(name);
7994 if(p == null) {
7995 Log.w(TAG, "Package:"+name+" is not an installed package");
7996 return -1;
7997 }
7998 PackageSetting dp = mDisabledSysPackages.get(name);
7999 // always make sure the system package code and resource paths dont change
8000 if(dp == null) {
8001 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8002 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8003 }
8004 mDisabledSysPackages.put(name, p);
8005 }
8006 return removePackageLP(name);
8007 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008009 PackageSetting enableSystemPackageLP(String name) {
8010 PackageSetting p = mDisabledSysPackages.get(name);
8011 if(p == null) {
8012 Log.w(TAG, "Package:"+name+" is not disabled");
8013 return null;
8014 }
8015 // Reset flag in ApplicationInfo object
8016 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8017 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8018 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008019 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008020 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008021 mDisabledSysPackages.remove(name);
8022 return ret;
8023 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008024
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008025 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008026 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 PackageSetting p = mPackages.get(name);
8028 if (p != null) {
8029 if (p.userId == uid) {
8030 return p;
8031 }
8032 reportSettingsProblem(Log.ERROR,
8033 "Adding duplicate package, keeping first: " + name);
8034 return null;
8035 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008036 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008037 p.userId = uid;
8038 if (addUserIdLP(uid, p, name)) {
8039 mPackages.put(name, p);
8040 return p;
8041 }
8042 return null;
8043 }
8044
8045 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8046 SharedUserSetting s = mSharedUsers.get(name);
8047 if (s != null) {
8048 if (s.userId == uid) {
8049 return s;
8050 }
8051 reportSettingsProblem(Log.ERROR,
8052 "Adding duplicate shared user, keeping first: " + name);
8053 return null;
8054 }
8055 s = new SharedUserSetting(name, pkgFlags);
8056 s.userId = uid;
8057 if (addUserIdLP(uid, s, name)) {
8058 mSharedUsers.put(name, s);
8059 return s;
8060 }
8061 return null;
8062 }
8063
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008064 // Transfer ownership of permissions from one package to another.
8065 private void transferPermissions(String origPkg, String newPkg) {
8066 // Transfer ownership of permissions to the new package.
8067 for (int i=0; i<2; i++) {
8068 HashMap<String, BasePermission> permissions =
8069 i == 0 ? mPermissionTrees : mPermissions;
8070 for (BasePermission bp : permissions.values()) {
8071 if (origPkg.equals(bp.sourcePackage)) {
8072 if (DEBUG_UPGRADE) Log.v(TAG,
8073 "Moving permission " + bp.name
8074 + " from pkg " + bp.sourcePackage
8075 + " to " + newPkg);
8076 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008077 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008078 bp.perm = null;
8079 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008080 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008081 }
8082 bp.uid = 0;
8083 bp.gids = null;
8084 }
8085 }
8086 }
8087 }
8088
8089 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008090 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008091 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008092 PackageSetting p = mPackages.get(name);
8093 if (p != null) {
8094 if (!p.codePath.equals(codePath)) {
8095 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008096 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008097 // This is an updated system app with versions in both system
8098 // and data partition. Just let the most recent version
8099 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008100 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008101 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008102 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008103 // Just a change in the code path is not an issue, but
8104 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008105 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008106 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008107 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008108 }
8109 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 reportSettingsProblem(Log.WARN,
8111 "Package " + name + " shared user changed from "
8112 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8113 + " to "
8114 + (sharedUser != null ? sharedUser.name : "<nothing>")
8115 + "; replacing with new");
8116 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008117 } else {
8118 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8119 // If what we are scanning is a system package, then
8120 // make it so, regardless of whether it was previously
8121 // installed only in the data partition.
8122 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008124 }
8125 }
8126 if (p == null) {
8127 // Create a new PackageSettings entry. this can end up here because
8128 // of code path mismatch or user id mismatch of an updated system partition
8129 if (!create) {
8130 return null;
8131 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008132 if (origPackage != null) {
8133 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008134 p = new PackageSetting(origPackage.name, name, codePath,
8135 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008136 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8137 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008138 // Note that we will retain the new package's signature so
8139 // that we can keep its data.
8140 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008141 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008142 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008143 p.sharedUser = origPackage.sharedUser;
8144 p.userId = origPackage.userId;
8145 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008146 mRenamedPackages.put(name, origPackage.name);
8147 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008148 // Update new package state.
8149 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008150 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008151 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008152 p.setTimeStamp(codePath.lastModified());
8153 p.sharedUser = sharedUser;
8154 if (sharedUser != null) {
8155 p.userId = sharedUser.userId;
8156 } else if (MULTIPLE_APPLICATION_UIDS) {
8157 // Clone the setting here for disabled system packages
8158 PackageSetting dis = mDisabledSysPackages.get(name);
8159 if (dis != null) {
8160 // For disabled packages a new setting is created
8161 // from the existing user id. This still has to be
8162 // added to list of user id's
8163 // Copy signatures from previous setting
8164 if (dis.signatures.mSignatures != null) {
8165 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8166 }
8167 p.userId = dis.userId;
8168 // Clone permissions
8169 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008170 // Clone component info
8171 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8172 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8173 // Add new setting to list of user ids
8174 addUserIdLP(p.userId, p, name);
8175 } else {
8176 // Assign new user id
8177 p.userId = newUserIdLP(p);
8178 }
8179 } else {
8180 p.userId = FIRST_APPLICATION_UID;
8181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008182 }
8183 if (p.userId < 0) {
8184 reportSettingsProblem(Log.WARN,
8185 "Package " + name + " could not be assigned a valid uid");
8186 return null;
8187 }
8188 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008189 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008190 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008191 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 }
8193 }
8194 return p;
8195 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008196
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008197 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008198 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008199 String codePath = pkg.applicationInfo.sourceDir;
8200 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008201 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008202 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008203 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008204 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008205 p.codePath = new File(codePath);
8206 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008207 }
8208 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008209 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008210 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008211 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008212 p.resourcePath = new File(resourcePath);
8213 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008214 }
8215 // Update version code if needed
8216 if (pkg.mVersionCode != p.versionCode) {
8217 p.versionCode = pkg.mVersionCode;
8218 }
8219 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8220 }
8221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222 // Utility method that adds a PackageSetting to mPackages and
8223 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008224 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 SharedUserSetting sharedUser) {
8226 mPackages.put(name, p);
8227 if (sharedUser != null) {
8228 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8229 reportSettingsProblem(Log.ERROR,
8230 "Package " + p.name + " was user "
8231 + p.sharedUser + " but is now " + sharedUser
8232 + "; I am not changing its files so it will probably fail!");
8233 p.sharedUser.packages.remove(p);
8234 } else if (p.userId != sharedUser.userId) {
8235 reportSettingsProblem(Log.ERROR,
8236 "Package " + p.name + " was user id " + p.userId
8237 + " but is now user " + sharedUser
8238 + " with id " + sharedUser.userId
8239 + "; I am not changing its files so it will probably fail!");
8240 }
8241
8242 sharedUser.packages.add(p);
8243 p.sharedUser = sharedUser;
8244 p.userId = sharedUser.userId;
8245 }
8246 }
8247
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008248 /*
8249 * Update the shared user setting when a package using
8250 * specifying the shared user id is removed. The gids
8251 * associated with each permission of the deleted package
8252 * are removed from the shared user's gid list only if its
8253 * not in use by other permissions of packages in the
8254 * shared user setting.
8255 */
8256 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008257 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008258 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259 return;
8260 }
8261 // No sharedUserId
8262 if (deletedPs.sharedUser == null) {
8263 return;
8264 }
8265 SharedUserSetting sus = deletedPs.sharedUser;
8266 // Update permissions
8267 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8268 boolean used = false;
8269 if (!sus.grantedPermissions.contains (eachPerm)) {
8270 continue;
8271 }
8272 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008273 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008274 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008275 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 used = true;
8277 break;
8278 }
8279 }
8280 if (!used) {
8281 // can safely delete this permission from list
8282 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008283 }
8284 }
8285 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008286 int newGids[] = globalGids;
8287 for (String eachPerm : sus.grantedPermissions) {
8288 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008289 if (bp != null) {
8290 newGids = appendInts(newGids, bp.gids);
8291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008292 }
8293 sus.gids = newGids;
8294 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296 private int removePackageLP(String name) {
8297 PackageSetting p = mPackages.get(name);
8298 if (p != null) {
8299 mPackages.remove(name);
8300 if (p.sharedUser != null) {
8301 p.sharedUser.packages.remove(p);
8302 if (p.sharedUser.packages.size() == 0) {
8303 mSharedUsers.remove(p.sharedUser.name);
8304 removeUserIdLP(p.sharedUser.userId);
8305 return p.sharedUser.userId;
8306 }
8307 } else {
8308 removeUserIdLP(p.userId);
8309 return p.userId;
8310 }
8311 }
8312 return -1;
8313 }
8314
8315 private boolean addUserIdLP(int uid, Object obj, Object name) {
8316 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8317 return false;
8318 }
8319
8320 if (uid >= FIRST_APPLICATION_UID) {
8321 int N = mUserIds.size();
8322 final int index = uid - FIRST_APPLICATION_UID;
8323 while (index >= N) {
8324 mUserIds.add(null);
8325 N++;
8326 }
8327 if (mUserIds.get(index) != null) {
8328 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008329 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008330 + " name=" + name);
8331 return false;
8332 }
8333 mUserIds.set(index, obj);
8334 } else {
8335 if (mOtherUserIds.get(uid) != null) {
8336 reportSettingsProblem(Log.ERROR,
8337 "Adding duplicate shared id: " + uid
8338 + " name=" + name);
8339 return false;
8340 }
8341 mOtherUserIds.put(uid, obj);
8342 }
8343 return true;
8344 }
8345
8346 public Object getUserIdLP(int uid) {
8347 if (uid >= FIRST_APPLICATION_UID) {
8348 int N = mUserIds.size();
8349 final int index = uid - FIRST_APPLICATION_UID;
8350 return index < N ? mUserIds.get(index) : null;
8351 } else {
8352 return mOtherUserIds.get(uid);
8353 }
8354 }
8355
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008356 private Set<String> findPackagesWithFlag(int flag) {
8357 Set<String> ret = new HashSet<String>();
8358 for (PackageSetting ps : mPackages.values()) {
8359 // Has to match atleast all the flag bits set on flag
8360 if ((ps.pkgFlags & flag) == flag) {
8361 ret.add(ps.name);
8362 }
8363 }
8364 return ret;
8365 }
8366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008367 private void removeUserIdLP(int uid) {
8368 if (uid >= FIRST_APPLICATION_UID) {
8369 int N = mUserIds.size();
8370 final int index = uid - FIRST_APPLICATION_UID;
8371 if (index < N) mUserIds.set(index, null);
8372 } else {
8373 mOtherUserIds.remove(uid);
8374 }
8375 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008377 void writeLP() {
8378 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8379
8380 // Keep the old settings around until we know the new ones have
8381 // been successfully written.
8382 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008383 // Presence of backup settings file indicates that we failed
8384 // to persist settings earlier. So preserve the older
8385 // backup for future reference since the current settings
8386 // might have been corrupted.
8387 if (!mBackupSettingsFilename.exists()) {
8388 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008389 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008390 return;
8391 }
8392 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008393 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008394 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008396 }
8397
8398 mPastSignatures.clear();
8399
8400 try {
8401 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8402
8403 //XmlSerializer serializer = XmlUtils.serializerInstance();
8404 XmlSerializer serializer = new FastXmlSerializer();
8405 serializer.setOutput(str, "utf-8");
8406 serializer.startDocument(null, true);
8407 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8408
8409 serializer.startTag(null, "packages");
8410
8411 serializer.startTag(null, "permission-trees");
8412 for (BasePermission bp : mPermissionTrees.values()) {
8413 writePermission(serializer, bp);
8414 }
8415 serializer.endTag(null, "permission-trees");
8416
8417 serializer.startTag(null, "permissions");
8418 for (BasePermission bp : mPermissions.values()) {
8419 writePermission(serializer, bp);
8420 }
8421 serializer.endTag(null, "permissions");
8422
8423 for (PackageSetting pkg : mPackages.values()) {
8424 writePackage(serializer, pkg);
8425 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008427 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8428 writeDisabledSysPackage(serializer, pkg);
8429 }
8430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008431 serializer.startTag(null, "preferred-activities");
8432 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8433 serializer.startTag(null, "item");
8434 pa.writeToXml(serializer);
8435 serializer.endTag(null, "item");
8436 }
8437 serializer.endTag(null, "preferred-activities");
8438
8439 for (SharedUserSetting usr : mSharedUsers.values()) {
8440 serializer.startTag(null, "shared-user");
8441 serializer.attribute(null, "name", usr.name);
8442 serializer.attribute(null, "userId",
8443 Integer.toString(usr.userId));
8444 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8445 serializer.startTag(null, "perms");
8446 for (String name : usr.grantedPermissions) {
8447 serializer.startTag(null, "item");
8448 serializer.attribute(null, "name", name);
8449 serializer.endTag(null, "item");
8450 }
8451 serializer.endTag(null, "perms");
8452 serializer.endTag(null, "shared-user");
8453 }
8454
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008455 if (mPackagesToBeCleaned.size() > 0) {
8456 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8457 serializer.startTag(null, "cleaning-package");
8458 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8459 serializer.endTag(null, "cleaning-package");
8460 }
8461 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008462
8463 if (mRenamedPackages.size() > 0) {
8464 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8465 serializer.startTag(null, "renamed-package");
8466 serializer.attribute(null, "new", e.getKey());
8467 serializer.attribute(null, "old", e.getValue());
8468 serializer.endTag(null, "renamed-package");
8469 }
8470 }
8471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008472 serializer.endTag(null, "packages");
8473
8474 serializer.endDocument();
8475
8476 str.flush();
8477 str.close();
8478
8479 // New settings successfully written, old ones are no longer
8480 // needed.
8481 mBackupSettingsFilename.delete();
8482 FileUtils.setPermissions(mSettingsFilename.toString(),
8483 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8484 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8485 |FileUtils.S_IROTH,
8486 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008487
8488 // Write package list file now, use a JournaledFile.
8489 //
8490 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8491 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8492
8493 str = new FileOutputStream(journal.chooseForWrite());
8494 try {
8495 StringBuilder sb = new StringBuilder();
8496 for (PackageSetting pkg : mPackages.values()) {
8497 ApplicationInfo ai = pkg.pkg.applicationInfo;
8498 String dataPath = ai.dataDir;
8499 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8500
8501 // Avoid any application that has a space in its path
8502 // or that is handled by the system.
8503 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8504 continue;
8505
8506 // we store on each line the following information for now:
8507 //
8508 // pkgName - package name
8509 // userId - application-specific user id
8510 // debugFlag - 0 or 1 if the package is debuggable.
8511 // dataPath - path to package's data path
8512 //
8513 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8514 //
8515 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8516 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8517 // system/core/run-as/run-as.c
8518 //
8519 sb.setLength(0);
8520 sb.append(ai.packageName);
8521 sb.append(" ");
8522 sb.append((int)ai.uid);
8523 sb.append(isDebug ? " 1 " : " 0 ");
8524 sb.append(dataPath);
8525 sb.append("\n");
8526 str.write(sb.toString().getBytes());
8527 }
8528 str.flush();
8529 str.close();
8530 journal.commit();
8531 }
8532 catch (Exception e) {
8533 journal.rollback();
8534 }
8535
8536 FileUtils.setPermissions(mPackageListFilename.toString(),
8537 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8538 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8539 |FileUtils.S_IROTH,
8540 -1, -1);
8541
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008542 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008543
8544 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008545 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 -08008546 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008547 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 -08008548 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008549 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008550 if (mSettingsFilename.exists()) {
8551 if (!mSettingsFilename.delete()) {
8552 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8553 }
8554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008555 //Debug.stopMethodTracing();
8556 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008557
8558 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008559 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008560 serializer.startTag(null, "updated-package");
8561 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008562 if (pkg.realName != null) {
8563 serializer.attribute(null, "realName", pkg.realName);
8564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008565 serializer.attribute(null, "codePath", pkg.codePathString);
8566 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008567 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008568 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8569 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8570 }
8571 if (pkg.sharedUser == null) {
8572 serializer.attribute(null, "userId",
8573 Integer.toString(pkg.userId));
8574 } else {
8575 serializer.attribute(null, "sharedUserId",
8576 Integer.toString(pkg.userId));
8577 }
8578 serializer.startTag(null, "perms");
8579 if (pkg.sharedUser == null) {
8580 // If this is a shared user, the permissions will
8581 // be written there. We still need to write an
8582 // empty permissions list so permissionsFixed will
8583 // be set.
8584 for (final String name : pkg.grantedPermissions) {
8585 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008586 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 // We only need to write signature or system permissions but this wont
8588 // match the semantics of grantedPermissions. So write all permissions.
8589 serializer.startTag(null, "item");
8590 serializer.attribute(null, "name", name);
8591 serializer.endTag(null, "item");
8592 }
8593 }
8594 }
8595 serializer.endTag(null, "perms");
8596 serializer.endTag(null, "updated-package");
8597 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008598
8599 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008600 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 serializer.startTag(null, "package");
8602 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008603 if (pkg.realName != null) {
8604 serializer.attribute(null, "realName", pkg.realName);
8605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008606 serializer.attribute(null, "codePath", pkg.codePathString);
8607 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8608 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8609 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008610 serializer.attribute(null, "flags",
8611 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008613 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008614 if (pkg.sharedUser == null) {
8615 serializer.attribute(null, "userId",
8616 Integer.toString(pkg.userId));
8617 } else {
8618 serializer.attribute(null, "sharedUserId",
8619 Integer.toString(pkg.userId));
8620 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008621 if (pkg.uidError) {
8622 serializer.attribute(null, "uidError", "true");
8623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008624 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8625 serializer.attribute(null, "enabled",
8626 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8627 ? "true" : "false");
8628 }
8629 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8630 serializer.attribute(null, "installStatus", "false");
8631 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008632 if (pkg.installerPackageName != null) {
8633 serializer.attribute(null, "installer", pkg.installerPackageName);
8634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008635 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8636 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8637 serializer.startTag(null, "perms");
8638 if (pkg.sharedUser == null) {
8639 // If this is a shared user, the permissions will
8640 // be written there. We still need to write an
8641 // empty permissions list so permissionsFixed will
8642 // be set.
8643 for (final String name : pkg.grantedPermissions) {
8644 serializer.startTag(null, "item");
8645 serializer.attribute(null, "name", name);
8646 serializer.endTag(null, "item");
8647 }
8648 }
8649 serializer.endTag(null, "perms");
8650 }
8651 if (pkg.disabledComponents.size() > 0) {
8652 serializer.startTag(null, "disabled-components");
8653 for (final String name : pkg.disabledComponents) {
8654 serializer.startTag(null, "item");
8655 serializer.attribute(null, "name", name);
8656 serializer.endTag(null, "item");
8657 }
8658 serializer.endTag(null, "disabled-components");
8659 }
8660 if (pkg.enabledComponents.size() > 0) {
8661 serializer.startTag(null, "enabled-components");
8662 for (final String name : pkg.enabledComponents) {
8663 serializer.startTag(null, "item");
8664 serializer.attribute(null, "name", name);
8665 serializer.endTag(null, "item");
8666 }
8667 serializer.endTag(null, "enabled-components");
8668 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008670 serializer.endTag(null, "package");
8671 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008673 void writePermission(XmlSerializer serializer, BasePermission bp)
8674 throws XmlPullParserException, java.io.IOException {
8675 if (bp.type != BasePermission.TYPE_BUILTIN
8676 && bp.sourcePackage != null) {
8677 serializer.startTag(null, "item");
8678 serializer.attribute(null, "name", bp.name);
8679 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008680 if (bp.protectionLevel !=
8681 PermissionInfo.PROTECTION_NORMAL) {
8682 serializer.attribute(null, "protection",
8683 Integer.toString(bp.protectionLevel));
8684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008685 if (DEBUG_SETTINGS) Log.v(TAG,
8686 "Writing perm: name=" + bp.name + " type=" + bp.type);
8687 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8688 PermissionInfo pi = bp.perm != null ? bp.perm.info
8689 : bp.pendingInfo;
8690 if (pi != null) {
8691 serializer.attribute(null, "type", "dynamic");
8692 if (pi.icon != 0) {
8693 serializer.attribute(null, "icon",
8694 Integer.toString(pi.icon));
8695 }
8696 if (pi.nonLocalizedLabel != null) {
8697 serializer.attribute(null, "label",
8698 pi.nonLocalizedLabel.toString());
8699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008700 }
8701 }
8702 serializer.endTag(null, "item");
8703 }
8704 }
8705
8706 String getReadMessagesLP() {
8707 return mReadMessages.toString();
8708 }
8709
Oscar Montemayora8529f62009-11-18 10:14:20 -08008710 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008711 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8712 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008713 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 while(its.hasNext()) {
8715 String key = its.next();
8716 PackageSetting ps = mPackages.get(key);
8717 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008718 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008719 }
8720 }
8721 return ret;
8722 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008724 boolean readLP() {
8725 FileInputStream str = null;
8726 if (mBackupSettingsFilename.exists()) {
8727 try {
8728 str = new FileInputStream(mBackupSettingsFilename);
8729 mReadMessages.append("Reading from backup settings file\n");
8730 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008731 if (mSettingsFilename.exists()) {
8732 // If both the backup and settings file exist, we
8733 // ignore the settings since it might have been
8734 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008735 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008736 mSettingsFilename.delete();
8737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008738 } catch (java.io.IOException e) {
8739 // We'll try for the normal settings file.
8740 }
8741 }
8742
8743 mPastSignatures.clear();
8744
8745 try {
8746 if (str == null) {
8747 if (!mSettingsFilename.exists()) {
8748 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008749 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008750 return false;
8751 }
8752 str = new FileInputStream(mSettingsFilename);
8753 }
8754 XmlPullParser parser = Xml.newPullParser();
8755 parser.setInput(str, null);
8756
8757 int type;
8758 while ((type=parser.next()) != XmlPullParser.START_TAG
8759 && type != XmlPullParser.END_DOCUMENT) {
8760 ;
8761 }
8762
8763 if (type != XmlPullParser.START_TAG) {
8764 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008765 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766 return false;
8767 }
8768
8769 int outerDepth = parser.getDepth();
8770 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8771 && (type != XmlPullParser.END_TAG
8772 || parser.getDepth() > outerDepth)) {
8773 if (type == XmlPullParser.END_TAG
8774 || type == XmlPullParser.TEXT) {
8775 continue;
8776 }
8777
8778 String tagName = parser.getName();
8779 if (tagName.equals("package")) {
8780 readPackageLP(parser);
8781 } else if (tagName.equals("permissions")) {
8782 readPermissionsLP(mPermissions, parser);
8783 } else if (tagName.equals("permission-trees")) {
8784 readPermissionsLP(mPermissionTrees, parser);
8785 } else if (tagName.equals("shared-user")) {
8786 readSharedUserLP(parser);
8787 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008788 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008789 } else if (tagName.equals("preferred-activities")) {
8790 readPreferredActivitiesLP(parser);
8791 } else if(tagName.equals("updated-package")) {
8792 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008793 } else if (tagName.equals("cleaning-package")) {
8794 String name = parser.getAttributeValue(null, "name");
8795 if (name != null) {
8796 mPackagesToBeCleaned.add(name);
8797 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008798 } else if (tagName.equals("renamed-package")) {
8799 String nname = parser.getAttributeValue(null, "new");
8800 String oname = parser.getAttributeValue(null, "old");
8801 if (nname != null && oname != null) {
8802 mRenamedPackages.put(nname, oname);
8803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008804 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008805 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008806 + parser.getName());
8807 XmlUtils.skipCurrentTag(parser);
8808 }
8809 }
8810
8811 str.close();
8812
8813 } catch(XmlPullParserException e) {
8814 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008815 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008816
8817 } catch(java.io.IOException e) {
8818 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008819 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008820
8821 }
8822
8823 int N = mPendingPackages.size();
8824 for (int i=0; i<N; i++) {
8825 final PendingPackage pp = mPendingPackages.get(i);
8826 Object idObj = getUserIdLP(pp.sharedId);
8827 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008828 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008829 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008830 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008831 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008832 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008833 + pp.name);
8834 continue;
8835 }
8836 p.copyFrom(pp);
8837 } else if (idObj != null) {
8838 String msg = "Bad package setting: package " + pp.name
8839 + " has shared uid " + pp.sharedId
8840 + " that is not a shared uid\n";
8841 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008842 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008843 } else {
8844 String msg = "Bad package setting: package " + pp.name
8845 + " has shared uid " + pp.sharedId
8846 + " that is not defined\n";
8847 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008848 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008849 }
8850 }
8851 mPendingPackages.clear();
8852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 mReadMessages.append("Read completed successfully: "
8854 + mPackages.size() + " packages, "
8855 + mSharedUsers.size() + " shared uids\n");
8856
8857 return true;
8858 }
8859
8860 private int readInt(XmlPullParser parser, String ns, String name,
8861 int defValue) {
8862 String v = parser.getAttributeValue(ns, name);
8863 try {
8864 if (v == null) {
8865 return defValue;
8866 }
8867 return Integer.parseInt(v);
8868 } catch (NumberFormatException e) {
8869 reportSettingsProblem(Log.WARN,
8870 "Error in package manager settings: attribute " +
8871 name + " has bad integer value " + v + " at "
8872 + parser.getPositionDescription());
8873 }
8874 return defValue;
8875 }
8876
8877 private void readPermissionsLP(HashMap<String, BasePermission> out,
8878 XmlPullParser parser)
8879 throws IOException, XmlPullParserException {
8880 int outerDepth = parser.getDepth();
8881 int type;
8882 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8883 && (type != XmlPullParser.END_TAG
8884 || parser.getDepth() > outerDepth)) {
8885 if (type == XmlPullParser.END_TAG
8886 || type == XmlPullParser.TEXT) {
8887 continue;
8888 }
8889
8890 String tagName = parser.getName();
8891 if (tagName.equals("item")) {
8892 String name = parser.getAttributeValue(null, "name");
8893 String sourcePackage = parser.getAttributeValue(null, "package");
8894 String ptype = parser.getAttributeValue(null, "type");
8895 if (name != null && sourcePackage != null) {
8896 boolean dynamic = "dynamic".equals(ptype);
8897 BasePermission bp = new BasePermission(name, sourcePackage,
8898 dynamic
8899 ? BasePermission.TYPE_DYNAMIC
8900 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008901 bp.protectionLevel = readInt(parser, null, "protection",
8902 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008903 if (dynamic) {
8904 PermissionInfo pi = new PermissionInfo();
8905 pi.packageName = sourcePackage.intern();
8906 pi.name = name.intern();
8907 pi.icon = readInt(parser, null, "icon", 0);
8908 pi.nonLocalizedLabel = parser.getAttributeValue(
8909 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008910 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008911 bp.pendingInfo = pi;
8912 }
8913 out.put(bp.name, bp);
8914 } else {
8915 reportSettingsProblem(Log.WARN,
8916 "Error in package manager settings: permissions has"
8917 + " no name at " + parser.getPositionDescription());
8918 }
8919 } else {
8920 reportSettingsProblem(Log.WARN,
8921 "Unknown element reading permissions: "
8922 + parser.getName() + " at "
8923 + parser.getPositionDescription());
8924 }
8925 XmlUtils.skipCurrentTag(parser);
8926 }
8927 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008929 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008930 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008931 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008932 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008933 String codePathStr = parser.getAttributeValue(null, "codePath");
8934 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008935 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 resourcePathStr = codePathStr;
8937 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008938 String version = parser.getAttributeValue(null, "version");
8939 int versionCode = 0;
8940 if (version != null) {
8941 try {
8942 versionCode = Integer.parseInt(version);
8943 } catch (NumberFormatException e) {
8944 }
8945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947 int pkgFlags = 0;
8948 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008949 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008950 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008951 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 String timeStampStr = parser.getAttributeValue(null, "ts");
8953 if (timeStampStr != null) {
8954 try {
8955 long timeStamp = Long.parseLong(timeStampStr);
8956 ps.setTimeStamp(timeStamp, timeStampStr);
8957 } catch (NumberFormatException e) {
8958 }
8959 }
8960 String idStr = parser.getAttributeValue(null, "userId");
8961 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8962 if(ps.userId <= 0) {
8963 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8964 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8965 }
8966 int outerDepth = parser.getDepth();
8967 int type;
8968 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8969 && (type != XmlPullParser.END_TAG
8970 || parser.getDepth() > outerDepth)) {
8971 if (type == XmlPullParser.END_TAG
8972 || type == XmlPullParser.TEXT) {
8973 continue;
8974 }
8975
8976 String tagName = parser.getName();
8977 if (tagName.equals("perms")) {
8978 readGrantedPermissionsLP(parser,
8979 ps.grantedPermissions);
8980 } else {
8981 reportSettingsProblem(Log.WARN,
8982 "Unknown element under <updated-package>: "
8983 + parser.getName());
8984 XmlUtils.skipCurrentTag(parser);
8985 }
8986 }
8987 mDisabledSysPackages.put(name, ps);
8988 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008990 private void readPackageLP(XmlPullParser parser)
8991 throws XmlPullParserException, IOException {
8992 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008993 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008994 String idStr = null;
8995 String sharedIdStr = null;
8996 String codePathStr = null;
8997 String resourcePathStr = null;
8998 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008999 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009000 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001 int pkgFlags = 0;
9002 String timeStampStr;
9003 long timeStamp = 0;
9004 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009005 String version = null;
9006 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009007 try {
9008 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009009 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009010 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009011 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009012 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9013 codePathStr = parser.getAttributeValue(null, "codePath");
9014 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009015 version = parser.getAttributeValue(null, "version");
9016 if (version != null) {
9017 try {
9018 versionCode = Integer.parseInt(version);
9019 } catch (NumberFormatException e) {
9020 }
9021 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009022 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009023
9024 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009025 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009026 try {
9027 pkgFlags = Integer.parseInt(systemStr);
9028 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009029 }
9030 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009031 // For backward compatibility
9032 systemStr = parser.getAttributeValue(null, "system");
9033 if (systemStr != null) {
9034 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9035 } else {
9036 // Old settings that don't specify system... just treat
9037 // them as system, good enough.
9038 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009040 }
9041 timeStampStr = parser.getAttributeValue(null, "ts");
9042 if (timeStampStr != null) {
9043 try {
9044 timeStamp = Long.parseLong(timeStampStr);
9045 } catch (NumberFormatException e) {
9046 }
9047 }
9048 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9049 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9050 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9051 if (resourcePathStr == null) {
9052 resourcePathStr = codePathStr;
9053 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009054 if (realName != null) {
9055 realName = realName.intern();
9056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009057 if (name == null) {
9058 reportSettingsProblem(Log.WARN,
9059 "Error in package manager settings: <package> has no name at "
9060 + parser.getPositionDescription());
9061 } else if (codePathStr == null) {
9062 reportSettingsProblem(Log.WARN,
9063 "Error in package manager settings: <package> has no codePath at "
9064 + parser.getPositionDescription());
9065 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009066 packageSetting = addPackageLP(name.intern(), realName,
9067 new File(codePathStr), new File(resourcePathStr),
9068 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009069 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9070 + ": userId=" + userId + " pkg=" + packageSetting);
9071 if (packageSetting == null) {
9072 reportSettingsProblem(Log.ERROR,
9073 "Failure adding uid " + userId
9074 + " while parsing settings at "
9075 + parser.getPositionDescription());
9076 } else {
9077 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9078 }
9079 } else if (sharedIdStr != null) {
9080 userId = sharedIdStr != null
9081 ? Integer.parseInt(sharedIdStr) : 0;
9082 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009083 packageSetting = new PendingPackage(name.intern(), realName,
9084 new File(codePathStr), new File(resourcePathStr),
9085 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009086 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9087 mPendingPackages.add((PendingPackage) packageSetting);
9088 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9089 + ": sharedUserId=" + userId + " pkg="
9090 + packageSetting);
9091 } else {
9092 reportSettingsProblem(Log.WARN,
9093 "Error in package manager settings: package "
9094 + name + " has bad sharedId " + sharedIdStr
9095 + " at " + parser.getPositionDescription());
9096 }
9097 } else {
9098 reportSettingsProblem(Log.WARN,
9099 "Error in package manager settings: package "
9100 + name + " has bad userId " + idStr + " at "
9101 + parser.getPositionDescription());
9102 }
9103 } catch (NumberFormatException e) {
9104 reportSettingsProblem(Log.WARN,
9105 "Error in package manager settings: package "
9106 + name + " has bad userId " + idStr + " at "
9107 + parser.getPositionDescription());
9108 }
9109 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009110 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009111 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009112 final String enabledStr = parser.getAttributeValue(null, "enabled");
9113 if (enabledStr != null) {
9114 if (enabledStr.equalsIgnoreCase("true")) {
9115 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9116 } else if (enabledStr.equalsIgnoreCase("false")) {
9117 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9118 } else if (enabledStr.equalsIgnoreCase("default")) {
9119 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9120 } else {
9121 reportSettingsProblem(Log.WARN,
9122 "Error in package manager settings: package "
9123 + name + " has bad enabled value: " + idStr
9124 + " at " + parser.getPositionDescription());
9125 }
9126 } else {
9127 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9128 }
9129 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9130 if (installStatusStr != null) {
9131 if (installStatusStr.equalsIgnoreCase("false")) {
9132 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9133 } else {
9134 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9135 }
9136 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009138 int outerDepth = parser.getDepth();
9139 int type;
9140 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9141 && (type != XmlPullParser.END_TAG
9142 || parser.getDepth() > outerDepth)) {
9143 if (type == XmlPullParser.END_TAG
9144 || type == XmlPullParser.TEXT) {
9145 continue;
9146 }
9147
9148 String tagName = parser.getName();
9149 if (tagName.equals("disabled-components")) {
9150 readDisabledComponentsLP(packageSetting, parser);
9151 } else if (tagName.equals("enabled-components")) {
9152 readEnabledComponentsLP(packageSetting, parser);
9153 } else if (tagName.equals("sigs")) {
9154 packageSetting.signatures.readXml(parser, mPastSignatures);
9155 } else if (tagName.equals("perms")) {
9156 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009157 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009158 packageSetting.permissionsFixed = true;
9159 } else {
9160 reportSettingsProblem(Log.WARN,
9161 "Unknown element under <package>: "
9162 + parser.getName());
9163 XmlUtils.skipCurrentTag(parser);
9164 }
9165 }
9166 } else {
9167 XmlUtils.skipCurrentTag(parser);
9168 }
9169 }
9170
9171 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9172 XmlPullParser parser)
9173 throws IOException, XmlPullParserException {
9174 int outerDepth = parser.getDepth();
9175 int type;
9176 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9177 && (type != XmlPullParser.END_TAG
9178 || parser.getDepth() > outerDepth)) {
9179 if (type == XmlPullParser.END_TAG
9180 || type == XmlPullParser.TEXT) {
9181 continue;
9182 }
9183
9184 String tagName = parser.getName();
9185 if (tagName.equals("item")) {
9186 String name = parser.getAttributeValue(null, "name");
9187 if (name != null) {
9188 packageSetting.disabledComponents.add(name.intern());
9189 } else {
9190 reportSettingsProblem(Log.WARN,
9191 "Error in package manager settings: <disabled-components> has"
9192 + " no name at " + parser.getPositionDescription());
9193 }
9194 } else {
9195 reportSettingsProblem(Log.WARN,
9196 "Unknown element under <disabled-components>: "
9197 + parser.getName());
9198 }
9199 XmlUtils.skipCurrentTag(parser);
9200 }
9201 }
9202
9203 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9204 XmlPullParser parser)
9205 throws IOException, XmlPullParserException {
9206 int outerDepth = parser.getDepth();
9207 int type;
9208 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9209 && (type != XmlPullParser.END_TAG
9210 || parser.getDepth() > outerDepth)) {
9211 if (type == XmlPullParser.END_TAG
9212 || type == XmlPullParser.TEXT) {
9213 continue;
9214 }
9215
9216 String tagName = parser.getName();
9217 if (tagName.equals("item")) {
9218 String name = parser.getAttributeValue(null, "name");
9219 if (name != null) {
9220 packageSetting.enabledComponents.add(name.intern());
9221 } else {
9222 reportSettingsProblem(Log.WARN,
9223 "Error in package manager settings: <enabled-components> has"
9224 + " no name at " + parser.getPositionDescription());
9225 }
9226 } else {
9227 reportSettingsProblem(Log.WARN,
9228 "Unknown element under <enabled-components>: "
9229 + parser.getName());
9230 }
9231 XmlUtils.skipCurrentTag(parser);
9232 }
9233 }
9234
9235 private void readSharedUserLP(XmlPullParser parser)
9236 throws XmlPullParserException, IOException {
9237 String name = null;
9238 String idStr = null;
9239 int pkgFlags = 0;
9240 SharedUserSetting su = null;
9241 try {
9242 name = parser.getAttributeValue(null, "name");
9243 idStr = parser.getAttributeValue(null, "userId");
9244 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9245 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9246 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9247 }
9248 if (name == null) {
9249 reportSettingsProblem(Log.WARN,
9250 "Error in package manager settings: <shared-user> has no name at "
9251 + parser.getPositionDescription());
9252 } else if (userId == 0) {
9253 reportSettingsProblem(Log.WARN,
9254 "Error in package manager settings: shared-user "
9255 + name + " has bad userId " + idStr + " at "
9256 + parser.getPositionDescription());
9257 } else {
9258 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9259 reportSettingsProblem(Log.ERROR,
9260 "Occurred while parsing settings at "
9261 + parser.getPositionDescription());
9262 }
9263 }
9264 } catch (NumberFormatException e) {
9265 reportSettingsProblem(Log.WARN,
9266 "Error in package manager settings: package "
9267 + name + " has bad userId " + idStr + " at "
9268 + parser.getPositionDescription());
9269 };
9270
9271 if (su != null) {
9272 int outerDepth = parser.getDepth();
9273 int type;
9274 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9275 && (type != XmlPullParser.END_TAG
9276 || parser.getDepth() > outerDepth)) {
9277 if (type == XmlPullParser.END_TAG
9278 || type == XmlPullParser.TEXT) {
9279 continue;
9280 }
9281
9282 String tagName = parser.getName();
9283 if (tagName.equals("sigs")) {
9284 su.signatures.readXml(parser, mPastSignatures);
9285 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009286 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009287 } else {
9288 reportSettingsProblem(Log.WARN,
9289 "Unknown element under <shared-user>: "
9290 + parser.getName());
9291 XmlUtils.skipCurrentTag(parser);
9292 }
9293 }
9294
9295 } else {
9296 XmlUtils.skipCurrentTag(parser);
9297 }
9298 }
9299
9300 private void readGrantedPermissionsLP(XmlPullParser parser,
9301 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9302 int outerDepth = parser.getDepth();
9303 int type;
9304 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9305 && (type != XmlPullParser.END_TAG
9306 || parser.getDepth() > outerDepth)) {
9307 if (type == XmlPullParser.END_TAG
9308 || type == XmlPullParser.TEXT) {
9309 continue;
9310 }
9311
9312 String tagName = parser.getName();
9313 if (tagName.equals("item")) {
9314 String name = parser.getAttributeValue(null, "name");
9315 if (name != null) {
9316 outPerms.add(name.intern());
9317 } else {
9318 reportSettingsProblem(Log.WARN,
9319 "Error in package manager settings: <perms> has"
9320 + " no name at " + parser.getPositionDescription());
9321 }
9322 } else {
9323 reportSettingsProblem(Log.WARN,
9324 "Unknown element under <perms>: "
9325 + parser.getName());
9326 }
9327 XmlUtils.skipCurrentTag(parser);
9328 }
9329 }
9330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331 private void readPreferredActivitiesLP(XmlPullParser parser)
9332 throws XmlPullParserException, IOException {
9333 int outerDepth = parser.getDepth();
9334 int type;
9335 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9336 && (type != XmlPullParser.END_TAG
9337 || parser.getDepth() > outerDepth)) {
9338 if (type == XmlPullParser.END_TAG
9339 || type == XmlPullParser.TEXT) {
9340 continue;
9341 }
9342
9343 String tagName = parser.getName();
9344 if (tagName.equals("item")) {
9345 PreferredActivity pa = new PreferredActivity(parser);
9346 if (pa.mParseError == null) {
9347 mPreferredActivities.addFilter(pa);
9348 } else {
9349 reportSettingsProblem(Log.WARN,
9350 "Error in package manager settings: <preferred-activity> "
9351 + pa.mParseError + " at "
9352 + parser.getPositionDescription());
9353 }
9354 } else {
9355 reportSettingsProblem(Log.WARN,
9356 "Unknown element under <preferred-activities>: "
9357 + parser.getName());
9358 XmlUtils.skipCurrentTag(parser);
9359 }
9360 }
9361 }
9362
9363 // Returns -1 if we could not find an available UserId to assign
9364 private int newUserIdLP(Object obj) {
9365 // Let's be stupidly inefficient for now...
9366 final int N = mUserIds.size();
9367 for (int i=0; i<N; i++) {
9368 if (mUserIds.get(i) == null) {
9369 mUserIds.set(i, obj);
9370 return FIRST_APPLICATION_UID + i;
9371 }
9372 }
9373
9374 // None left?
9375 if (N >= MAX_APPLICATION_UIDS) {
9376 return -1;
9377 }
9378
9379 mUserIds.add(obj);
9380 return FIRST_APPLICATION_UID + N;
9381 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009383 public PackageSetting getDisabledSystemPkg(String name) {
9384 synchronized(mPackages) {
9385 PackageSetting ps = mDisabledSysPackages.get(name);
9386 return ps;
9387 }
9388 }
9389
9390 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9391 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9392 if (Config.LOGV) {
9393 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9394 + " componentName = " + componentInfo.name);
9395 Log.v(TAG, "enabledComponents: "
9396 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9397 Log.v(TAG, "disabledComponents: "
9398 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9399 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009400 if (packageSettings == null) {
9401 if (false) {
9402 Log.w(TAG, "WAITING FOR DEBUGGER");
9403 Debug.waitForDebugger();
9404 Log.i(TAG, "We will crash!");
9405 }
9406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009407 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9408 || ((componentInfo.enabled
9409 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9410 || (componentInfo.applicationInfo.enabled
9411 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9412 && !packageSettings.disabledComponents.contains(componentInfo.name))
9413 || packageSettings.enabledComponents.contains(componentInfo.name));
9414 }
9415 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009416
9417 // ------- apps on sdcard specific code -------
9418 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009419 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009420 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009421 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009422 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009423
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009424 private String getEncryptKey() {
9425 try {
9426 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9427 if (sdEncKey == null) {
9428 sdEncKey = SystemKeyStore.getInstance().
9429 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9430 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009431 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009432 return null;
9433 }
9434 }
9435 return sdEncKey;
9436 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009437 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009438 return null;
9439 }
9440 }
9441
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009442 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009443 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009444 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009445 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009446 if (list != null) {
9447 int idx = 0;
9448 int idList[] = new int[MAX_CONTAINERS];
9449 boolean neverFound = true;
9450 for (String name : list) {
9451 // Ignore null entries
9452 if (name == null) {
9453 continue;
9454 }
9455 int sidx = name.indexOf(prefix);
9456 if (sidx == -1) {
9457 // Not a temp file. just ignore
9458 continue;
9459 }
9460 String subStr = name.substring(sidx + prefix.length());
9461 idList[idx] = -1;
9462 if (subStr != null) {
9463 try {
9464 int cid = Integer.parseInt(subStr);
9465 idList[idx++] = cid;
9466 neverFound = false;
9467 } catch (NumberFormatException e) {
9468 }
9469 }
9470 }
9471 if (!neverFound) {
9472 // Sort idList
9473 Arrays.sort(idList);
9474 for (int j = 1; j <= idList.length; j++) {
9475 if (idList[j-1] != j) {
9476 tmpIdx = j;
9477 break;
9478 }
9479 }
9480 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009481 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009482 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009483 }
9484
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009485 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009486 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009487 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009488 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9489 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9490 throw new SecurityException("Media status can only be updated by the system");
9491 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009492 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009493 Log.i(TAG, "Updating external media status from " +
9494 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9495 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009496 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9497 mediaStatus+", mMediaMounted=" + mMediaMounted);
9498 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009499 if (reportStatus) {
9500 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9501 }
9502 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009503 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009504 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009505 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009506 // Queue up an async operation since the package installation may take a little while.
9507 mHandler.post(new Runnable() {
9508 public void run() {
9509 mHandler.removeCallbacks(this);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009510 try {
9511 updateExternalMediaStatusInner(mediaStatus);
9512 } finally {
9513 if (reportStatus) {
9514 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9515 }
9516 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009517 }
9518 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009519 }
9520
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009521 private void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009522 // If we are up here that means there are packages to be
9523 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009524 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009525 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009526 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009527 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009528 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009529
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009530 int uidList[] = new int[list.length];
9531 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009532 HashSet<String> removeCids = new HashSet<String>();
9533 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009534 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009535 for (String cid : list) {
9536 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009537 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9538 boolean failed = true;
9539 try {
9540 String pkgName = args.getPackageName();
9541 if (pkgName == null) {
9542 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009543 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009544 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9545 PackageSetting ps = mSettings.mPackages.get(pkgName);
9546 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009547 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009548 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9549 " corresponds to pkg : " + pkgName +
9550 " at code path: " + ps.codePathString);
9551 // We do have a valid package installed on sdcard
9552 processCids.put(args, ps.codePathString);
9553 failed = false;
9554 int uid = ps.userId;
9555 if (uid != -1) {
9556 uidList[num++] = uid;
9557 }
9558 }
9559 } finally {
9560 if (failed) {
9561 // Stale container on sdcard. Just delete
9562 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9563 removeCids.add(cid);
9564 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009565 }
9566 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009567 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009568 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009569 int uidArr[] = null;
9570 if (num > 0) {
9571 // Sort uid list
9572 Arrays.sort(uidList, 0, num);
9573 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009574 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009575 uidArr[0] = uidList[0];
9576 int di = 0;
9577 for (int i = 1; i < num; i++) {
9578 if (uidList[i-1] != uidList[i]) {
9579 uidArr[di++] = uidList[i];
9580 }
9581 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009582 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009583 // Process packages with valid entries.
9584 if (mediaStatus) {
9585 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009586 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009587 startCleaningPackages();
9588 } else {
9589 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009590 unloadMediaPackages(processCids, uidArr);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009591 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009592 }
9593
9594 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9595 ArrayList<String> pkgList, int uidArr[]) {
9596 int size = pkgList.size();
9597 if (size > 0) {
9598 // Send broadcasts here
9599 Bundle extras = new Bundle();
9600 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9601 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009602 if (uidArr != null) {
9603 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9604 }
9605 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9606 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009607 sendPackageBroadcast(action, null, extras);
9608 }
9609 }
9610
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009611 /*
9612 * Look at potentially valid container ids from processCids
9613 * If package information doesn't match the one on record
9614 * or package scanning fails, the cid is added to list of
9615 * removeCids and cleaned up. Since cleaning up containers
9616 * involves destroying them, we do not want any parse
9617 * references to such stale containers. So force gc's
9618 * to avoid unnecessary crashes.
9619 */
9620 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009621 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009622 ArrayList<String> pkgList = new ArrayList<String>();
9623 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009624 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009625 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009626 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009627 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9628 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009629 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009630 try {
9631 // Make sure there are no container errors first.
9632 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9633 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009634 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009635 " when installing from sdcard");
9636 continue;
9637 }
9638 // Check code path here.
9639 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009640 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009641 " does not match one in settings " + codePath);
9642 continue;
9643 }
9644 // Parse package
9645 int parseFlags = PackageParser.PARSE_CHATTY |
Jeff Brown07330792010-03-30 19:57:08 -07009646 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009647 PackageParser pp = new PackageParser(codePath);
9648 pp.setSeparateProcesses(mSeparateProcesses);
9649 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9650 codePath, mMetrics, parseFlags);
9651 pp = null;
9652 doGc = true;
9653 // Check for parse errors
9654 if (pkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009655 Slog.e(TAG, "Parse error when installing install pkg : "
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009656 + args.cid + " from " + args.cachePath);
9657 continue;
9658 }
9659 setApplicationInfoPaths(pkg, codePath, codePath);
9660 synchronized (mInstallLock) {
9661 // Scan the package
9662 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9663 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009664 retCode = PackageManager.INSTALL_SUCCEEDED;
9665 pkgList.add(pkg.packageName);
9666 // Post process args
9667 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9668 }
9669 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009670 Slog.i(TAG, "Failed to install pkg: " +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009671 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009672 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009673 }
9674
9675 } finally {
9676 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9677 // Don't destroy container here. Wait till gc clears things up.
9678 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009679 }
9680 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009681 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009682 synchronized (mPackages) {
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009683 // Make sure group IDs have been assigned, and any permission
9684 // changes in other apps are accounted for
9685 updatePermissionsLP(null, null, true, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009686 // Persist settings
9687 mSettings.writeLP();
9688 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009689 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009690 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009691 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9692 }
9693 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009694 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009695 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009696 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009697 if (removeCids != null) {
9698 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009699 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009700 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009701 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009702 }
9703
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009704 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009705 int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009706 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009707 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009708 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009709 Set<SdInstallArgs> keys = processCids.keySet();
9710 for (SdInstallArgs args : keys) {
9711 String cid = args.cid;
9712 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009713 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009714 // Delete package internally
9715 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9716 synchronized (mInstallLock) {
9717 boolean res = deletePackageLI(pkgName, false,
9718 PackageManager.DONT_DELETE_DATA, outInfo);
9719 if (res) {
9720 pkgList.add(pkgName);
9721 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009722 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009723 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009724 }
9725 }
9726 }
9727 // Send broadcasts
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009728 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009729 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009730 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009731 // Force gc
9732 Runtime.getRuntime().gc();
9733 // Just unmount all valid containers.
9734 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009735 synchronized (mInstallLock) {
9736 args.doPostDeleteLI(false);
9737 }
9738 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009739 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009740
9741 public void movePackage(final String packageName,
9742 final IPackageMoveObserver observer, final int flags) {
9743 if (packageName == null) {
9744 return;
9745 }
9746 mContext.enforceCallingOrSelfPermission(
9747 android.Manifest.permission.MOVE_PACKAGE, null);
9748 int returnCode = PackageManager.MOVE_SUCCEEDED;
9749 int currFlags = 0;
9750 int newFlags = 0;
9751 synchronized (mPackages) {
9752 PackageParser.Package pkg = mPackages.get(packageName);
9753 if (pkg == null) {
9754 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9755 }
9756 // Disable moving fwd locked apps and system packages
9757 if (pkg.applicationInfo != null &&
9758 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009759 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009760 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9761 } else if (pkg.applicationInfo != null &&
9762 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009763 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009764 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9765 } else {
9766 // Find install location first
9767 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9768 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009769 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009770 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9771 } else {
9772 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9773 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009774 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009775 PackageManager.INSTALL_EXTERNAL : 0;
9776 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009777 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009778 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9779 }
9780 }
9781 }
9782 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9783 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9784 } else {
9785 Message msg = mHandler.obtainMessage(INIT_COPY);
9786 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9787 pkg.applicationInfo.publicSourceDir);
9788 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9789 packageName);
9790 msg.obj = mp;
9791 mHandler.sendMessage(msg);
9792 }
9793 }
9794 }
9795
9796 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9797 // Queue up an async operation since the package deletion may take a little while.
9798 mHandler.post(new Runnable() {
9799 public void run() {
9800 mHandler.removeCallbacks(this);
9801 int returnCode = currentStatus;
9802 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9803 if (moveSucceeded) {
9804 int uid = -1;
9805 synchronized (mPackages) {
9806 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9807 }
9808 ArrayList<String> pkgList = new ArrayList<String>();
9809 pkgList.add(mp.packageName);
9810 int uidArr[] = new int[] { uid };
9811 // Send resources unavailable broadcast
9812 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9813
9814 // Update package code and resource paths
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009815 synchronized (mInstallLock) {
9816 synchronized (mPackages) {
9817 PackageParser.Package pkg = mPackages.get(mp.packageName);
9818 if (pkg != null) {
9819 String oldCodePath = pkg.mPath;
9820 String newCodePath = mp.targetArgs.getCodePath();
9821 String newResPath = mp.targetArgs.getResourcePath();
9822 pkg.mPath = newCodePath;
9823 // Move dex files around
9824 if (moveDexFilesLI(pkg)
9825 != PackageManager.INSTALL_SUCCEEDED) {
9826 // Moving of dex files failed. Set
9827 // error code and abort move.
9828 pkg.mPath = pkg.mScanPath;
9829 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9830 moveSucceeded = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009831 } else {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009832 pkg.mScanPath = newCodePath;
9833 pkg.applicationInfo.sourceDir = newCodePath;
9834 pkg.applicationInfo.publicSourceDir = newResPath;
9835 PackageSetting ps = (PackageSetting) pkg.mExtras;
9836 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9837 ps.codePathString = ps.codePath.getPath();
9838 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9839 ps.resourcePathString = ps.resourcePath.getPath();
9840 // Set the application info flag correctly.
9841 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9842 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9843 } else {
9844 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9845 }
9846 ps.setFlags(pkg.applicationInfo.flags);
9847 mAppDirs.remove(oldCodePath);
9848 mAppDirs.put(newCodePath, pkg);
9849 // Persist settings
9850 mSettings.writeLP();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009851 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009852 }
9853 }
9854 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009855 // Send resources available broadcast
9856 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009857 }
9858 if (!moveSucceeded){
9859 // Clean up failed installation
9860 if (mp.targetArgs != null) {
9861 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009862 returnCode);
9863 }
9864 } else {
9865 // Force a gc to clear things up.
9866 Runtime.getRuntime().gc();
9867 // Delete older code
9868 synchronized (mInstallLock) {
9869 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009870 }
9871 }
9872 IPackageMoveObserver observer = mp.observer;
9873 if (observer != null) {
9874 try {
9875 observer.packageMoved(mp.packageName, returnCode);
9876 } catch (RemoteException e) {
9877 Log.i(TAG, "Observer no longer exists.");
9878 }
9879 }
9880 }
9881 });
9882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009883}