blob: 1ab62632f272646ce4a690ee2025b16baf18f2c9 [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.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070035import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070036import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.content.Intent;
38import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070039import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080040import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070041import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.ActivityInfo;
43import android.content.pm.ApplicationInfo;
44import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070045import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.IPackageDataObserver;
47import android.content.pm.IPackageDeleteObserver;
48import android.content.pm.IPackageInstallObserver;
49import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080050import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.pm.IPackageStatsObserver;
52import android.content.pm.InstrumentationInfo;
53import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080054import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.pm.PackageManager;
56import android.content.pm.PackageStats;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.pm.PackageParser;
61import android.content.pm.PermissionInfo;
62import android.content.pm.PermissionGroupInfo;
63import android.content.pm.ProviderInfo;
64import android.content.pm.ResolveInfo;
65import android.content.pm.ServiceInfo;
66import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.net.Uri;
68import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070069import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080071import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080073import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070074import android.os.Looper;
75import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Parcel;
77import android.os.RemoteException;
78import android.os.Environment;
79import android.os.FileObserver;
80import android.os.FileUtils;
81import android.os.Handler;
82import android.os.ParcelFileDescriptor;
83import android.os.Process;
84import android.os.ServiceManager;
85import android.os.SystemClock;
86import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070087import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080088import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.util.*;
90import android.view.Display;
91import android.view.WindowManager;
92
93import java.io.File;
94import java.io.FileDescriptor;
95import java.io.FileInputStream;
96import java.io.FileNotFoundException;
97import java.io.FileOutputStream;
98import java.io.FileReader;
99import java.io.FilenameFilter;
100import java.io.IOException;
101import java.io.InputStream;
102import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800103import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800104import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.ArrayList;
106import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700107import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.Collections;
109import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800110import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.util.Enumeration;
112import java.util.HashMap;
113import java.util.HashSet;
114import java.util.Iterator;
115import java.util.List;
116import java.util.Map;
117import java.util.Set;
118import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800119import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import java.util.zip.ZipFile;
121import java.util.zip.ZipOutputStream;
122
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700123/**
124 * Keep track of all those .apks everywhere.
125 *
126 * This is very central to the platform's security; please run the unit
127 * tests whenever making modifications here:
128 *
129mmm frameworks/base/tests/AndroidTests
130adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
131adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
132 *
133 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134class PackageManagerService extends IPackageManager.Stub {
135 private static final String TAG = "PackageManager";
136 private static final boolean DEBUG_SETTINGS = false;
137 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800138 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800139 private static final boolean DEBUG_INSTALL = false;
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -0700140 private static final boolean DEBUG_NATIVE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
142 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
143 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400144 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 private static final int FIRST_APPLICATION_UID =
146 Process.FIRST_APPLICATION_UID;
147 private static final int MAX_APPLICATION_UIDS = 1000;
148
149 private static final boolean SHOW_INFO = false;
150
151 private static final boolean GET_CERTIFICATES = true;
152
Oscar Montemayora8529f62009-11-18 10:14:20 -0800153 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 private static final int REMOVE_EVENTS =
156 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
157 private static final int ADD_EVENTS =
158 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
159
160 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800161 // Suffix used during package installation when copying/moving
162 // package apks to install directory.
163 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800165 /**
166 * Indicates the state of installation. Used by PackageManager to
167 * figure out incomplete installations. Say a package is being installed
168 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
169 * the package installation is successful or unsuccesful lin which case
170 * the PackageManager will no longer maintain state information associated
171 * with the package. If some exception(like device freeze or battery being
172 * pulled out) occurs during installation of a package, the PackageManager
173 * needs this information to clean up the previously failed installation.
174 */
175 private static final int PKG_INSTALL_INCOMPLETE = 0;
176 private static final int PKG_INSTALL_COMPLETE = 1;
177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 static final int SCAN_MONITOR = 1<<0;
179 static final int SCAN_NO_DEX = 1<<1;
180 static final int SCAN_FORCE_DEX = 1<<2;
181 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800182 static final int SCAN_NEW_INSTALL = 1<<4;
183 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700185 static final int REMOVE_CHATTY = 1<<16;
186
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800187 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
188 "com.android.defcontainer",
189 "com.android.defcontainer.DefaultContainerService");
190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
192 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700193 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194
Dianne Hackborn851a5412009-05-08 12:06:44 -0700195 final int mSdkVersion = Build.VERSION.SDK_INT;
196 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
197 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 final Context mContext;
200 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700201 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 final DisplayMetrics mMetrics;
203 final int mDefParseFlags;
204 final String[] mSeparateProcesses;
205
206 // This is where all application persistent data goes.
207 final File mAppDataDir;
208
Oscar Montemayora8529f62009-11-18 10:14:20 -0800209 // If Encrypted File System feature is enabled, all application persistent data
210 // should go here instead.
211 final File mSecureAppDataDir;
212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 // This is the object monitoring the framework dir.
214 final FileObserver mFrameworkInstallObserver;
215
216 // This is the object monitoring the system app dir.
217 final FileObserver mSystemInstallObserver;
218
219 // This is the object monitoring mAppInstallDir.
220 final FileObserver mAppInstallObserver;
221
222 // This is the object monitoring mDrmAppPrivateInstallDir.
223 final FileObserver mDrmAppInstallObserver;
224
225 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
226 // LOCK HELD. Can be called with mInstallLock held.
227 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 final File mFrameworkDir;
230 final File mSystemAppDir;
231 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700232 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233
234 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
235 // apps.
236 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // Lock for state used when installing and doing other long running
241 // operations. Methods that must be called with this lock held have
242 // the prefix "LI".
243 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 // These are the directories in the 3rd party applications installed dir
246 // that we have currently loaded packages from. Keys are the application's
247 // installed zip file (absolute codePath), and values are Package.
248 final HashMap<String, PackageParser.Package> mAppDirs =
249 new HashMap<String, PackageParser.Package>();
250
251 // Information for the parser to write more useful error messages.
252 File mScanningPath;
253 int mLastScanError;
254
255 final int[] mOutPermissions = new int[3];
256
257 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 // Keys are String (package name), values are Package. This also serves
260 // as the lock for the global state. Methods that must be called with
261 // this lock held have the prefix "LP".
262 final HashMap<String, PackageParser.Package> mPackages =
263 new HashMap<String, PackageParser.Package>();
264
265 final Settings mSettings;
266 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267
268 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
269 int[] mGlobalGids;
270
271 // These are the built-in uid -> permission mappings that were read from the
272 // etc/permissions.xml file.
273 final SparseArray<HashSet<String>> mSystemPermissions =
274 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 // These are the built-in shared libraries that were read from the
277 // etc/permissions.xml file.
278 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800279
Dianne Hackborn49237342009-08-27 20:08:01 -0700280 // Temporary for building the final shared libraries for an .apk.
281 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800282
Dianne Hackborn49237342009-08-27 20:08:01 -0700283 // These are the features this devices supports that were read from the
284 // etc/permissions.xml file.
285 final HashMap<String, FeatureInfo> mAvailableFeatures =
286 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 // All available activities, for your resolving pleasure.
289 final ActivityIntentResolver mActivities =
290 new ActivityIntentResolver();
291
292 // All available receivers, for your resolving pleasure.
293 final ActivityIntentResolver mReceivers =
294 new ActivityIntentResolver();
295
296 // All available services, for your resolving pleasure.
297 final ServiceIntentResolver mServices = new ServiceIntentResolver();
298
299 // Keys are String (provider class name), values are Provider.
300 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
301 new HashMap<ComponentName, PackageParser.Provider>();
302
303 // Mapping from provider base names (first directory in content URI codePath)
304 // to the provider information.
305 final HashMap<String, PackageParser.Provider> mProviders =
306 new HashMap<String, PackageParser.Provider>();
307
308 // Mapping from instrumentation class names to info about them.
309 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
310 new HashMap<ComponentName, PackageParser.Instrumentation>();
311
312 // Mapping from permission names to info about them.
313 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
314 new HashMap<String, PackageParser.PermissionGroup>();
315
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800316 // Packages whose data we have transfered into another package, thus
317 // should no longer exist.
318 final HashSet<String> mTransferedPackages = new HashSet<String>();
319
Dianne Hackborn854060af2009-07-09 18:14:31 -0700320 // Broadcast actions that are only available to the system.
321 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 boolean mSystemReady;
324 boolean mSafeMode;
325 boolean mHasSystemUidErrors;
326
327 ApplicationInfo mAndroidApplication;
328 final ActivityInfo mResolveActivity = new ActivityInfo();
329 final ResolveInfo mResolveInfo = new ResolveInfo();
330 ComponentName mResolveComponentName;
331 PackageParser.Package mPlatformPackage;
332
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700333 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800334 final HashMap<String, ArrayList<String>> mPendingBroadcasts
335 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800336 // Service Connection to remote media container service to copy
337 // package uri's from external media onto secure containers
338 // or internal storage.
339 private IMediaContainerService mContainerService = null;
340
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700341 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800342 static final int MCS_BOUND = 3;
343 static final int END_COPY = 4;
344 static final int INIT_COPY = 5;
345 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800346 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800347 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800348 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800349 static final int MCS_RECONNECT = 10;
350 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700351 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700352 static final int WRITE_SETTINGS = 13;
353
354 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800355
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700356 // Delay time in millisecs
357 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800358 final private DefaultContainerConnection mDefContainerConn =
359 new DefaultContainerConnection();
360 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800361 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800362 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800363 IMediaContainerService imcs =
364 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800365 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800366 }
367
368 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800369 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800370 }
371 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700372
Christopher Tate1bb69062010-02-19 17:02:12 -0800373 // Recordkeeping of restore-after-install operations that are currently in flight
374 // between the Package Manager and the Backup Manager
375 class PostInstallData {
376 public InstallArgs args;
377 public PackageInstalledInfo res;
378
379 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
380 args = _a;
381 res = _r;
382 }
383 };
384 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
385 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
386
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700387 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800388 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800389 final ArrayList<HandlerParams> mPendingInstalls =
390 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800391
392 private boolean connectToService() {
393 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
394 " DefaultContainerService");
395 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700396 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800397 if (mContext.bindService(service, mDefContainerConn,
398 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700399 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800400 mBound = true;
401 return true;
402 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700403 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800404 return false;
405 }
406
407 private void disconnectService() {
408 mContainerService = null;
409 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700410 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800411 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700412 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800413 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800414
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700415 PackageHandler(Looper looper) {
416 super(looper);
417 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700418
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700419 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700420 try {
421 doHandleMessage(msg);
422 } finally {
423 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
424 }
425 }
426
427 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700428 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800429 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800430 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800431 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800432 int idx = mPendingInstalls.size();
433 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
434 // If a bind was already initiated we dont really
435 // need to do anything. The pending install
436 // will be processed later on.
437 if (!mBound) {
438 // If this is the only one pending we might
439 // have to bind to the service again.
440 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800441 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800442 params.serviceError();
443 return;
444 } else {
445 // Once we bind to the service, the first
446 // pending request will be processed.
447 mPendingInstalls.add(idx, params);
448 }
449 } else {
450 mPendingInstalls.add(idx, params);
451 // Already bound to the service. Just make
452 // sure we trigger off processing the first request.
453 if (idx == 0) {
454 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800455 }
456 }
457 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800458 }
459 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800460 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800461 if (msg.obj != null) {
462 mContainerService = (IMediaContainerService) msg.obj;
463 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800464 if (mContainerService == null) {
465 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800466 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800467 for (HandlerParams params : mPendingInstalls) {
468 mPendingInstalls.remove(0);
469 // Indicate service bind error
470 params.serviceError();
471 }
472 mPendingInstalls.clear();
473 } else if (mPendingInstalls.size() > 0) {
474 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800475 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800476 params.startCopy();
477 }
478 } else {
479 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800480 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800481 }
482 break;
483 }
484 case MCS_RECONNECT : {
485 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
486 if (mPendingInstalls.size() > 0) {
487 if (mBound) {
488 disconnectService();
489 }
490 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800491 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800492 for (HandlerParams params : mPendingInstalls) {
493 mPendingInstalls.remove(0);
494 // Indicate service bind error
495 params.serviceError();
496 }
497 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800498 }
499 }
500 break;
501 }
502 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800503 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
504 // Delete pending install
505 if (mPendingInstalls.size() > 0) {
506 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800507 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800508 if (mPendingInstalls.size() == 0) {
509 if (mBound) {
510 disconnectService();
511 }
512 } else {
513 // There are more pending requests in queue.
514 // Just post MCS_BOUND message to trigger processing
515 // of next pending install.
516 mHandler.sendEmptyMessage(MCS_BOUND);
517 }
518 break;
519 }
520 case MCS_GIVE_UP: {
521 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
522 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800523 break;
524 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700525 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800526 String packages[];
527 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700528 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700529 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700530 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800532 if (mPendingBroadcasts == null) {
533 return;
534 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700535 size = mPendingBroadcasts.size();
536 if (size <= 0) {
537 // Nothing to be done. Just return
538 return;
539 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800540 packages = new String[size];
541 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700542 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800543 Iterator<HashMap.Entry<String, ArrayList<String>>>
544 it = mPendingBroadcasts.entrySet().iterator();
545 int i = 0;
546 while (it.hasNext() && i < size) {
547 HashMap.Entry<String, ArrayList<String>> ent = it.next();
548 packages[i] = ent.getKey();
549 components[i] = ent.getValue();
550 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700551 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800552 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700553 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800554 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700555 mPendingBroadcasts.clear();
556 }
557 // Send broadcasts
558 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800559 sendPackageChangedBroadcast(packages[i], true,
560 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700561 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700562 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700563 break;
564 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800565 case START_CLEANING_PACKAGE: {
566 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700567 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800568 synchronized (mPackages) {
569 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
570 mSettings.mPackagesToBeCleaned.add(packageName);
571 }
572 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700573 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800574 startCleaningPackages();
575 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800576 case POST_INSTALL: {
577 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
578 PostInstallData data = mRunningInstalls.get(msg.arg1);
579 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700580 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800581
582 if (data != null) {
583 InstallArgs args = data.args;
584 PackageInstalledInfo res = data.res;
585
586 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700587 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800588 Bundle extras = new Bundle(1);
589 extras.putInt(Intent.EXTRA_UID, res.uid);
590 final boolean update = res.removedInfo.removedPackage != null;
591 if (update) {
592 extras.putBoolean(Intent.EXTRA_REPLACING, true);
593 }
594 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
595 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700596 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800597 if (update) {
598 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
599 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700600 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800601 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700602 if (res.removedInfo.args != null) {
603 // Remove the replaced package's older resources safely now
604 deleteOld = true;
605 }
606 }
607 // Force a gc to clear up things
608 Runtime.getRuntime().gc();
609 // We delete after a gc for applications on sdcard.
610 if (deleteOld) {
611 synchronized (mInstallLock) {
612 res.removedInfo.args.doPostDeleteLI(true);
613 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800614 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800615 if (args.observer != null) {
616 try {
617 args.observer.packageInstalled(res.name, res.returnCode);
618 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800619 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800620 }
621 }
622 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800623 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800624 }
625 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700626 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700627 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
628 boolean reportStatus = msg.arg1 == 1;
629 boolean doGc = msg.arg2 == 1;
630 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
631 if (doGc) {
632 // Force a gc to clear up stale containers.
633 Runtime.getRuntime().gc();
634 }
635 if (msg.obj != null) {
636 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
637 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
638 // Unload containers
639 unloadAllContainers(args);
640 }
641 if (reportStatus) {
642 try {
643 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
644 PackageHelper.getMountService().finishMediaUpdate();
645 } catch (RemoteException e) {
646 Log.e(TAG, "MountService not running?");
647 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700648 }
649 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700650 case WRITE_SETTINGS: {
651 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
652 synchronized (mPackages) {
653 removeMessages(WRITE_SETTINGS);
654 mSettings.writeLP();
655 }
656 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
657 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700658 }
659 }
660 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800661
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700662 void scheduleWriteSettingsLocked() {
663 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
664 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
665 }
666 }
667
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800668 static boolean installOnSd(int flags) {
669 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700670 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800671 return false;
672 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700673 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
674 return true;
675 }
676 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800677 }
678
679 static boolean isFwdLocked(int flags) {
680 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
681 return true;
682 }
683 return false;
684 }
685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 public static final IPackageManager main(Context context, boolean factoryTest) {
687 PackageManagerService m = new PackageManagerService(context, factoryTest);
688 ServiceManager.addService("package", m);
689 return m;
690 }
691
692 static String[] splitString(String str, char sep) {
693 int count = 1;
694 int i = 0;
695 while ((i=str.indexOf(sep, i)) >= 0) {
696 count++;
697 i++;
698 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 String[] res = new String[count];
701 i=0;
702 count = 0;
703 int lastI=0;
704 while ((i=str.indexOf(sep, i)) >= 0) {
705 res[count] = str.substring(lastI, i);
706 count++;
707 i++;
708 lastI = i;
709 }
710 res[count] = str.substring(lastI, str.length());
711 return res;
712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800715 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800719 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 mContext = context;
723 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700724 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 mMetrics = new DisplayMetrics();
726 mSettings = new Settings();
727 mSettings.addSharedUserLP("android.uid.system",
728 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
729 mSettings.addSharedUserLP("android.uid.phone",
730 MULTIPLE_APPLICATION_UIDS
731 ? RADIO_UID : FIRST_APPLICATION_UID,
732 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400733 mSettings.addSharedUserLP("android.uid.log",
734 MULTIPLE_APPLICATION_UIDS
735 ? LOG_UID : FIRST_APPLICATION_UID,
736 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737
738 String separateProcesses = SystemProperties.get("debug.separate_processes");
739 if (separateProcesses != null && separateProcesses.length() > 0) {
740 if ("*".equals(separateProcesses)) {
741 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
742 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800743 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 } else {
745 mDefParseFlags = 0;
746 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800747 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 + separateProcesses);
749 }
750 } else {
751 mDefParseFlags = 0;
752 mSeparateProcesses = null;
753 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 Installer installer = new Installer();
756 // Little hacky thing to check if installd is here, to determine
757 // whether we are running on the simulator and thus need to take
758 // care of building the /data file structure ourself.
759 // (apparently the sim now has a working installer)
760 if (installer.ping() && Process.supportsProcesses()) {
761 mInstaller = installer;
762 } else {
763 mInstaller = null;
764 }
765
766 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
767 Display d = wm.getDefaultDisplay();
768 d.getMetrics(mMetrics);
769
770 synchronized (mInstallLock) {
771 synchronized (mPackages) {
772 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700773 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 File dataDir = Environment.getDataDirectory();
776 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800777 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
779
780 if (mInstaller == null) {
781 // Make sure these dirs exist, when we are running in
782 // the simulator.
783 // Make a wide-open directory for random misc stuff.
784 File miscDir = new File(dataDir, "misc");
785 miscDir.mkdirs();
786 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800787 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 mDrmAppPrivateInstallDir.mkdirs();
789 }
790
791 readPermissions();
792
793 mRestoredSettings = mSettings.readLP();
794 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800795
796 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800798
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800799 // Set flag to monitor and not change apk file paths when
800 // scanning install directories.
801 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700802 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800803 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800804 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700805 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700810 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700813 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 /**
816 * Out of paranoia, ensure that everything in the boot class
817 * path has been dexed.
818 */
819 String bootClassPath = System.getProperty("java.boot.class.path");
820 if (bootClassPath != null) {
821 String[] paths = splitString(bootClassPath, ':');
822 for (int i=0; i<paths.length; i++) {
823 try {
824 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
825 libFiles.add(paths[i]);
826 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700827 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 }
829 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800830 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800832 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 }
834 }
835 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800836 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 /**
840 * Also ensure all external libraries have had dexopt run on them.
841 */
842 if (mSharedLibraries.size() > 0) {
843 Iterator<String> libs = mSharedLibraries.values().iterator();
844 while (libs.hasNext()) {
845 String lib = libs.next();
846 try {
847 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
848 libFiles.add(lib);
849 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700850 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 }
852 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800853 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800855 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 }
857 }
858 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 // Gross hack for now: we know this file doesn't contain any
861 // code, so don't dexopt it to avoid the resulting log spew.
862 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 /**
865 * And there are a number of commands implemented in Java, which
866 * we currently need to do the dexopt on so that they can be
867 * run from a non-root shell.
868 */
869 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700870 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 for (int i=0; i<frameworkFiles.length; i++) {
872 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
873 String path = libPath.getPath();
874 // Skip the file if we alrady did it.
875 if (libFiles.contains(path)) {
876 continue;
877 }
878 // Skip the file if it is not a type we want to dexopt.
879 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
880 continue;
881 }
882 try {
883 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
884 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700885 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 }
887 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800888 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800890 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 }
892 }
893 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800894
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700895 if (didDexOpt) {
896 // If we had to do a dexopt of one of the previous
897 // things, then something on the system has changed.
898 // Consider this significant, and wipe away all other
899 // existing dexopt files to ensure we don't leave any
900 // dangling around.
901 String[] files = mDalvikCacheDir.list();
902 if (files != null) {
903 for (int i=0; i<files.length; i++) {
904 String fn = files[i];
905 if (fn.startsWith("data@app@")
906 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800907 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700908 (new File(mDalvikCacheDir, fn)).delete();
909 }
910 }
911 }
912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800914
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800915 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 mFrameworkInstallObserver = new AppDirObserver(
917 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
918 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700919 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
920 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800921 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800922
923 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
925 mSystemInstallObserver = new AppDirObserver(
926 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
927 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700928 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
929 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800930
931 if (mInstaller != null) {
932 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
933 mInstaller.moveFiles();
934 }
935
936 // Prune any system packages that no longer exist.
937 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
938 while (psit.hasNext()) {
939 PackageSetting ps = psit.next();
940 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800941 && !mPackages.containsKey(ps.name)
942 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800943 psit.remove();
944 String msg = "System package " + ps.name
945 + " no longer exists; wiping its data";
946 reportSettingsProblem(Log.WARN, msg);
947 if (mInstaller != null) {
948 // XXX how to set useEncryptedFSDir for packages that
949 // are not encrypted?
950 mInstaller.remove(ps.name, true);
951 }
952 }
953 }
954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 mAppInstallDir = new File(dataDir, "app");
956 if (mInstaller == null) {
957 // Make sure these dirs exist, when we are running in
958 // the simulator.
959 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
960 }
961 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800962 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 //clean up list
964 for(int i = 0; i < deletePkgsList.size(); i++) {
965 //clean up here
966 cleanupInstallFailedPackage(deletePkgsList.get(i));
967 }
968 //delete tmp files
969 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800970
971 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 SystemClock.uptimeMillis());
973 mAppInstallObserver = new AppDirObserver(
974 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
975 mAppInstallObserver.startWatching();
976 scanDirLI(mAppInstallDir, 0, scanMode);
977
978 mDrmAppInstallObserver = new AppDirObserver(
979 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
980 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800981 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800983 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800985 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 + ((SystemClock.uptimeMillis()-startTime)/1000f)
987 + " seconds");
988
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700989 // If the platform SDK has changed since the last time we booted,
990 // we need to re-grant app permission to catch any new ones that
991 // appear. This is really a hack, and means that apps can in some
992 // cases get permissions that the user didn't initially explicitly
993 // allow... it would be nice to have some better way to handle
994 // this situation.
995 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
996 != mSdkVersion;
997 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
998 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
999 + "; regranting permissions for internal storage");
1000 mSettings.mInternalSdkPlatform = mSdkVersion;
1001
1002 updatePermissionsLP(null, null, true, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003
1004 mSettings.writeLP();
1005
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001006 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 // Now after opening every single application zip, make sure they
1010 // are all flushed. Not really needed, but keeps things nice and
1011 // tidy.
1012 Runtime.getRuntime().gc();
1013 } // synchronized (mPackages)
1014 } // synchronized (mInstallLock)
1015 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 @Override
1018 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1019 throws RemoteException {
1020 try {
1021 return super.onTransact(code, data, reply, flags);
1022 } catch (RuntimeException e) {
1023 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001024 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 }
1026 throw e;
1027 }
1028 }
1029
Dianne Hackborne6620b22010-01-22 14:46:21 -08001030 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001031 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001033 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1034 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001036 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001037 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
1039 } else {
1040 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001041 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 File dataDir = new File(pkg.applicationInfo.dataDir);
1043 dataDir.delete();
1044 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001045 if (ps.codePath != null) {
1046 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001047 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001048 }
1049 }
1050 if (ps.resourcePath != null) {
1051 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001052 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001053 }
1054 }
1055 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
1057
1058 void readPermissions() {
1059 // Read permissions from .../etc/permission directory.
1060 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1061 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001062 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 return;
1064 }
1065 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001066 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 return;
1068 }
1069
1070 // Iterate over the files in the directory and scan .xml files
1071 for (File f : libraryDir.listFiles()) {
1072 // We'll read platform.xml last
1073 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1074 continue;
1075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001078 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 continue;
1080 }
1081 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001082 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 continue;
1084 }
1085
1086 readPermissionsFromXml(f);
1087 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1090 final File permFile = new File(Environment.getRootDirectory(),
1091 "etc/permissions/platform.xml");
1092 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001093
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001094 StringBuilder sb = new StringBuilder(128);
1095 sb.append("Libs:");
1096 Iterator<String> it = mSharedLibraries.keySet().iterator();
1097 while (it.hasNext()) {
1098 sb.append(' ');
1099 String name = it.next();
1100 sb.append(name);
1101 sb.append(':');
1102 sb.append(mSharedLibraries.get(name));
1103 }
1104 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001105
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001106 sb.setLength(0);
1107 sb.append("Features:");
1108 it = mAvailableFeatures.keySet().iterator();
1109 while (it.hasNext()) {
1110 sb.append(' ');
1111 sb.append(it.next());
1112 }
1113 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001115
1116 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 FileReader permReader = null;
1118 try {
1119 permReader = new FileReader(permFile);
1120 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001121 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 return;
1123 }
1124
1125 try {
1126 XmlPullParser parser = Xml.newPullParser();
1127 parser.setInput(permReader);
1128
1129 XmlUtils.beginDocument(parser, "permissions");
1130
1131 while (true) {
1132 XmlUtils.nextElement(parser);
1133 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1134 break;
1135 }
1136
1137 String name = parser.getName();
1138 if ("group".equals(name)) {
1139 String gidStr = parser.getAttributeValue(null, "gid");
1140 if (gidStr != null) {
1141 int gid = Integer.parseInt(gidStr);
1142 mGlobalGids = appendInt(mGlobalGids, gid);
1143 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001144 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 + parser.getPositionDescription());
1146 }
1147
1148 XmlUtils.skipCurrentTag(parser);
1149 continue;
1150 } else if ("permission".equals(name)) {
1151 String perm = parser.getAttributeValue(null, "name");
1152 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001153 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 + parser.getPositionDescription());
1155 XmlUtils.skipCurrentTag(parser);
1156 continue;
1157 }
1158 perm = perm.intern();
1159 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 } else if ("assign-permission".equals(name)) {
1162 String perm = parser.getAttributeValue(null, "name");
1163 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001164 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 + parser.getPositionDescription());
1166 XmlUtils.skipCurrentTag(parser);
1167 continue;
1168 }
1169 String uidStr = parser.getAttributeValue(null, "uid");
1170 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001171 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 + parser.getPositionDescription());
1173 XmlUtils.skipCurrentTag(parser);
1174 continue;
1175 }
1176 int uid = Process.getUidForName(uidStr);
1177 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001178 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 + uidStr + "\" at "
1180 + parser.getPositionDescription());
1181 XmlUtils.skipCurrentTag(parser);
1182 continue;
1183 }
1184 perm = perm.intern();
1185 HashSet<String> perms = mSystemPermissions.get(uid);
1186 if (perms == null) {
1187 perms = new HashSet<String>();
1188 mSystemPermissions.put(uid, perms);
1189 }
1190 perms.add(perm);
1191 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 } else if ("library".equals(name)) {
1194 String lname = parser.getAttributeValue(null, "name");
1195 String lfile = parser.getAttributeValue(null, "file");
1196 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001197 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 + parser.getPositionDescription());
1199 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001200 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 + parser.getPositionDescription());
1202 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001203 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001204 mSharedLibraries.put(lname, lfile);
1205 }
1206 XmlUtils.skipCurrentTag(parser);
1207 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001208
Dianne Hackborn49237342009-08-27 20:08:01 -07001209 } else if ("feature".equals(name)) {
1210 String fname = parser.getAttributeValue(null, "name");
1211 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001212 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001213 + parser.getPositionDescription());
1214 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001215 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001216 FeatureInfo fi = new FeatureInfo();
1217 fi.name = fname;
1218 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 }
1220 XmlUtils.skipCurrentTag(parser);
1221 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 } else {
1224 XmlUtils.skipCurrentTag(parser);
1225 continue;
1226 }
1227
1228 }
1229 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001230 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001232 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
1234 }
1235
1236 void readPermission(XmlPullParser parser, String name)
1237 throws IOException, XmlPullParserException {
1238
1239 name = name.intern();
1240
1241 BasePermission bp = mSettings.mPermissions.get(name);
1242 if (bp == null) {
1243 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1244 mSettings.mPermissions.put(name, bp);
1245 }
1246 int outerDepth = parser.getDepth();
1247 int type;
1248 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1249 && (type != XmlPullParser.END_TAG
1250 || parser.getDepth() > outerDepth)) {
1251 if (type == XmlPullParser.END_TAG
1252 || type == XmlPullParser.TEXT) {
1253 continue;
1254 }
1255
1256 String tagName = parser.getName();
1257 if ("group".equals(tagName)) {
1258 String gidStr = parser.getAttributeValue(null, "gid");
1259 if (gidStr != null) {
1260 int gid = Process.getGidForName(gidStr);
1261 bp.gids = appendInt(bp.gids, gid);
1262 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001263 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 + parser.getPositionDescription());
1265 }
1266 }
1267 XmlUtils.skipCurrentTag(parser);
1268 }
1269 }
1270
1271 static int[] appendInt(int[] cur, int val) {
1272 if (cur == null) {
1273 return new int[] { val };
1274 }
1275 final int N = cur.length;
1276 for (int i=0; i<N; i++) {
1277 if (cur[i] == val) {
1278 return cur;
1279 }
1280 }
1281 int[] ret = new int[N+1];
1282 System.arraycopy(cur, 0, ret, 0, N);
1283 ret[N] = val;
1284 return ret;
1285 }
1286
1287 static int[] appendInts(int[] cur, int[] add) {
1288 if (add == null) return cur;
1289 if (cur == null) return add;
1290 final int N = add.length;
1291 for (int i=0; i<N; i++) {
1292 cur = appendInt(cur, add[i]);
1293 }
1294 return cur;
1295 }
1296
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001297 static int[] removeInt(int[] cur, int val) {
1298 if (cur == null) {
1299 return null;
1300 }
1301 final int N = cur.length;
1302 for (int i=0; i<N; i++) {
1303 if (cur[i] == val) {
1304 int[] ret = new int[N-1];
1305 if (i > 0) {
1306 System.arraycopy(cur, 0, ret, 0, i);
1307 }
1308 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001309 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001310 }
1311 return ret;
1312 }
1313 }
1314 return cur;
1315 }
1316
1317 static int[] removeInts(int[] cur, int[] rem) {
1318 if (rem == null) return cur;
1319 if (cur == null) return cur;
1320 final int N = rem.length;
1321 for (int i=0; i<N; i++) {
1322 cur = removeInt(cur, rem[i]);
1323 }
1324 return cur;
1325 }
1326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001328 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1329 // The package has been uninstalled but has retained data and resources.
1330 return PackageParser.generatePackageInfo(p, null, flags);
1331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 final PackageSetting ps = (PackageSetting)p.mExtras;
1333 if (ps == null) {
1334 return null;
1335 }
1336 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1337 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1338 }
1339
1340 public PackageInfo getPackageInfo(String packageName, int flags) {
1341 synchronized (mPackages) {
1342 PackageParser.Package p = mPackages.get(packageName);
1343 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001344 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 + ": " + p);
1346 if (p != null) {
1347 return generatePackageInfo(p, flags);
1348 }
1349 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1350 return generatePackageInfoFromSettingsLP(packageName, flags);
1351 }
1352 }
1353 return null;
1354 }
1355
Dianne Hackborn47096932010-02-11 15:57:09 -08001356 public String[] currentToCanonicalPackageNames(String[] names) {
1357 String[] out = new String[names.length];
1358 synchronized (mPackages) {
1359 for (int i=names.length-1; i>=0; i--) {
1360 PackageSetting ps = mSettings.mPackages.get(names[i]);
1361 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1362 }
1363 }
1364 return out;
1365 }
1366
1367 public String[] canonicalToCurrentPackageNames(String[] names) {
1368 String[] out = new String[names.length];
1369 synchronized (mPackages) {
1370 for (int i=names.length-1; i>=0; i--) {
1371 String cur = mSettings.mRenamedPackages.get(names[i]);
1372 out[i] = cur != null ? cur : names[i];
1373 }
1374 }
1375 return out;
1376 }
1377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 public int getPackageUid(String packageName) {
1379 synchronized (mPackages) {
1380 PackageParser.Package p = mPackages.get(packageName);
1381 if(p != null) {
1382 return p.applicationInfo.uid;
1383 }
1384 PackageSetting ps = mSettings.mPackages.get(packageName);
1385 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1386 return -1;
1387 }
1388 p = ps.pkg;
1389 return p != null ? p.applicationInfo.uid : -1;
1390 }
1391 }
1392
1393 public int[] getPackageGids(String packageName) {
1394 synchronized (mPackages) {
1395 PackageParser.Package p = mPackages.get(packageName);
1396 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001397 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 + ": " + p);
1399 if (p != null) {
1400 final PackageSetting ps = (PackageSetting)p.mExtras;
1401 final SharedUserSetting suid = ps.sharedUser;
1402 return suid != null ? suid.gids : ps.gids;
1403 }
1404 }
1405 // stupid thing to indicate an error.
1406 return new int[0];
1407 }
1408
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001409 static final PermissionInfo generatePermissionInfo(
1410 BasePermission bp, int flags) {
1411 if (bp.perm != null) {
1412 return PackageParser.generatePermissionInfo(bp.perm, flags);
1413 }
1414 PermissionInfo pi = new PermissionInfo();
1415 pi.name = bp.name;
1416 pi.packageName = bp.sourcePackage;
1417 pi.nonLocalizedLabel = bp.name;
1418 pi.protectionLevel = bp.protectionLevel;
1419 return pi;
1420 }
1421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 public PermissionInfo getPermissionInfo(String name, int flags) {
1423 synchronized (mPackages) {
1424 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001425 if (p != null) {
1426 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428 return null;
1429 }
1430 }
1431
1432 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1433 synchronized (mPackages) {
1434 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1435 for (BasePermission p : mSettings.mPermissions.values()) {
1436 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001437 if (p.perm == null || p.perm.info.group == null) {
1438 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001441 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1443 }
1444 }
1445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 if (out.size() > 0) {
1448 return out;
1449 }
1450 return mPermissionGroups.containsKey(group) ? out : null;
1451 }
1452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1455 synchronized (mPackages) {
1456 return PackageParser.generatePermissionGroupInfo(
1457 mPermissionGroups.get(name), flags);
1458 }
1459 }
1460
1461 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1462 synchronized (mPackages) {
1463 final int N = mPermissionGroups.size();
1464 ArrayList<PermissionGroupInfo> out
1465 = new ArrayList<PermissionGroupInfo>(N);
1466 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1467 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1468 }
1469 return out;
1470 }
1471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1474 PackageSetting ps = mSettings.mPackages.get(packageName);
1475 if(ps != null) {
1476 if(ps.pkg == null) {
1477 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1478 if(pInfo != null) {
1479 return pInfo.applicationInfo;
1480 }
1481 return null;
1482 }
1483 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1484 }
1485 return null;
1486 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1489 PackageSetting ps = mSettings.mPackages.get(packageName);
1490 if(ps != null) {
1491 if(ps.pkg == null) {
1492 ps.pkg = new PackageParser.Package(packageName);
1493 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001494 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1495 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1496 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1497 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 }
1499 return generatePackageInfo(ps.pkg, flags);
1500 }
1501 return null;
1502 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1505 synchronized (mPackages) {
1506 PackageParser.Package p = mPackages.get(packageName);
1507 if (Config.LOGV) Log.v(
1508 TAG, "getApplicationInfo " + packageName
1509 + ": " + p);
1510 if (p != null) {
1511 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001512 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 }
1514 if ("android".equals(packageName)||"system".equals(packageName)) {
1515 return mAndroidApplication;
1516 }
1517 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1518 return generateApplicationInfoFromSettingsLP(packageName, flags);
1519 }
1520 }
1521 return null;
1522 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001523
1524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1526 mContext.enforceCallingOrSelfPermission(
1527 android.Manifest.permission.CLEAR_APP_CACHE, null);
1528 // Queue up an async operation since clearing cache may take a little while.
1529 mHandler.post(new Runnable() {
1530 public void run() {
1531 mHandler.removeCallbacks(this);
1532 int retCode = -1;
1533 if (mInstaller != null) {
1534 retCode = mInstaller.freeCache(freeStorageSize);
1535 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001536 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
1538 } //end if mInstaller
1539 if (observer != null) {
1540 try {
1541 observer.onRemoveCompleted(null, (retCode >= 0));
1542 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001543 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
1545 }
1546 }
1547 });
1548 }
1549
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001550 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001551 mContext.enforceCallingOrSelfPermission(
1552 android.Manifest.permission.CLEAR_APP_CACHE, null);
1553 // Queue up an async operation since clearing cache may take a little while.
1554 mHandler.post(new Runnable() {
1555 public void run() {
1556 mHandler.removeCallbacks(this);
1557 int retCode = -1;
1558 if (mInstaller != null) {
1559 retCode = mInstaller.freeCache(freeStorageSize);
1560 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001561 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001562 }
1563 }
1564 if(pi != null) {
1565 try {
1566 // Callback via pending intent
1567 int code = (retCode >= 0) ? 1 : 0;
1568 pi.sendIntent(null, code, null,
1569 null, null);
1570 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001571 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001572 }
1573 }
1574 }
1575 });
1576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1579 synchronized (mPackages) {
1580 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001581
1582 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001584 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 }
1586 if (mResolveComponentName.equals(component)) {
1587 return mResolveActivity;
1588 }
1589 }
1590 return null;
1591 }
1592
1593 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1594 synchronized (mPackages) {
1595 PackageParser.Activity a = mReceivers.mActivities.get(component);
1596 if (Config.LOGV) Log.v(
1597 TAG, "getReceiverInfo " + component + ": " + a);
1598 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1599 return PackageParser.generateActivityInfo(a, flags);
1600 }
1601 }
1602 return null;
1603 }
1604
1605 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1606 synchronized (mPackages) {
1607 PackageParser.Service s = mServices.mServices.get(component);
1608 if (Config.LOGV) Log.v(
1609 TAG, "getServiceInfo " + component + ": " + s);
1610 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1611 return PackageParser.generateServiceInfo(s, flags);
1612 }
1613 }
1614 return null;
1615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 public String[] getSystemSharedLibraryNames() {
1618 Set<String> libSet;
1619 synchronized (mPackages) {
1620 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001621 int size = libSet.size();
1622 if (size > 0) {
1623 String[] libs = new String[size];
1624 libSet.toArray(libs);
1625 return libs;
1626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001628 return null;
1629 }
1630
1631 public FeatureInfo[] getSystemAvailableFeatures() {
1632 Collection<FeatureInfo> featSet;
1633 synchronized (mPackages) {
1634 featSet = mAvailableFeatures.values();
1635 int size = featSet.size();
1636 if (size > 0) {
1637 FeatureInfo[] features = new FeatureInfo[size+1];
1638 featSet.toArray(features);
1639 FeatureInfo fi = new FeatureInfo();
1640 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1641 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1642 features[size] = fi;
1643 return features;
1644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 }
1646 return null;
1647 }
1648
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001649 public boolean hasSystemFeature(String name) {
1650 synchronized (mPackages) {
1651 return mAvailableFeatures.containsKey(name);
1652 }
1653 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 public int checkPermission(String permName, String pkgName) {
1656 synchronized (mPackages) {
1657 PackageParser.Package p = mPackages.get(pkgName);
1658 if (p != null && p.mExtras != null) {
1659 PackageSetting ps = (PackageSetting)p.mExtras;
1660 if (ps.sharedUser != null) {
1661 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1662 return PackageManager.PERMISSION_GRANTED;
1663 }
1664 } else if (ps.grantedPermissions.contains(permName)) {
1665 return PackageManager.PERMISSION_GRANTED;
1666 }
1667 }
1668 }
1669 return PackageManager.PERMISSION_DENIED;
1670 }
1671
1672 public int checkUidPermission(String permName, int uid) {
1673 synchronized (mPackages) {
1674 Object obj = mSettings.getUserIdLP(uid);
1675 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001676 GrantedPermissions gp = (GrantedPermissions)obj;
1677 if (gp.grantedPermissions.contains(permName)) {
1678 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 }
1680 } else {
1681 HashSet<String> perms = mSystemPermissions.get(uid);
1682 if (perms != null && perms.contains(permName)) {
1683 return PackageManager.PERMISSION_GRANTED;
1684 }
1685 }
1686 }
1687 return PackageManager.PERMISSION_DENIED;
1688 }
1689
1690 private BasePermission findPermissionTreeLP(String permName) {
1691 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1692 if (permName.startsWith(bp.name) &&
1693 permName.length() > bp.name.length() &&
1694 permName.charAt(bp.name.length()) == '.') {
1695 return bp;
1696 }
1697 }
1698 return null;
1699 }
1700
1701 private BasePermission checkPermissionTreeLP(String permName) {
1702 if (permName != null) {
1703 BasePermission bp = findPermissionTreeLP(permName);
1704 if (bp != null) {
1705 if (bp.uid == Binder.getCallingUid()) {
1706 return bp;
1707 }
1708 throw new SecurityException("Calling uid "
1709 + Binder.getCallingUid()
1710 + " is not allowed to add to permission tree "
1711 + bp.name + " owned by uid " + bp.uid);
1712 }
1713 }
1714 throw new SecurityException("No permission tree found for " + permName);
1715 }
1716
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001717 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1718 if (s1 == null) {
1719 return s2 == null;
1720 }
1721 if (s2 == null) {
1722 return false;
1723 }
1724 if (s1.getClass() != s2.getClass()) {
1725 return false;
1726 }
1727 return s1.equals(s2);
1728 }
1729
1730 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1731 if (pi1.icon != pi2.icon) return false;
1732 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1733 if (!compareStrings(pi1.name, pi2.name)) return false;
1734 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1735 // We'll take care of setting this one.
1736 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1737 // These are not currently stored in settings.
1738 //if (!compareStrings(pi1.group, pi2.group)) return false;
1739 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1740 //if (pi1.labelRes != pi2.labelRes) return false;
1741 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1742 return true;
1743 }
1744
1745 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1746 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1747 throw new SecurityException("Label must be specified in permission");
1748 }
1749 BasePermission tree = checkPermissionTreeLP(info.name);
1750 BasePermission bp = mSettings.mPermissions.get(info.name);
1751 boolean added = bp == null;
1752 boolean changed = true;
1753 if (added) {
1754 bp = new BasePermission(info.name, tree.sourcePackage,
1755 BasePermission.TYPE_DYNAMIC);
1756 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1757 throw new SecurityException(
1758 "Not allowed to modify non-dynamic permission "
1759 + info.name);
1760 } else {
1761 if (bp.protectionLevel == info.protectionLevel
1762 && bp.perm.owner.equals(tree.perm.owner)
1763 && bp.uid == tree.uid
1764 && comparePermissionInfos(bp.perm.info, info)) {
1765 changed = false;
1766 }
1767 }
1768 bp.protectionLevel = info.protectionLevel;
1769 bp.perm = new PackageParser.Permission(tree.perm.owner,
1770 new PermissionInfo(info));
1771 bp.perm.info.packageName = tree.perm.info.packageName;
1772 bp.uid = tree.uid;
1773 if (added) {
1774 mSettings.mPermissions.put(info.name, bp);
1775 }
1776 if (changed) {
1777 if (!async) {
1778 mSettings.writeLP();
1779 } else {
1780 scheduleWriteSettingsLocked();
1781 }
1782 }
1783 return added;
1784 }
1785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 public boolean addPermission(PermissionInfo info) {
1787 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001788 return addPermissionLocked(info, false);
1789 }
1790 }
1791
1792 public boolean addPermissionAsync(PermissionInfo info) {
1793 synchronized (mPackages) {
1794 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 }
1796 }
1797
1798 public void removePermission(String name) {
1799 synchronized (mPackages) {
1800 checkPermissionTreeLP(name);
1801 BasePermission bp = mSettings.mPermissions.get(name);
1802 if (bp != null) {
1803 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1804 throw new SecurityException(
1805 "Not allowed to modify non-dynamic permission "
1806 + name);
1807 }
1808 mSettings.mPermissions.remove(name);
1809 mSettings.writeLP();
1810 }
1811 }
1812 }
1813
Dianne Hackborn854060af2009-07-09 18:14:31 -07001814 public boolean isProtectedBroadcast(String actionName) {
1815 synchronized (mPackages) {
1816 return mProtectedBroadcasts.contains(actionName);
1817 }
1818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 public int checkSignatures(String pkg1, String pkg2) {
1821 synchronized (mPackages) {
1822 PackageParser.Package p1 = mPackages.get(pkg1);
1823 PackageParser.Package p2 = mPackages.get(pkg2);
1824 if (p1 == null || p1.mExtras == null
1825 || p2 == null || p2.mExtras == null) {
1826 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1827 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001828 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830 }
1831
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001832 public int checkUidSignatures(int uid1, int uid2) {
1833 synchronized (mPackages) {
1834 Signature[] s1;
1835 Signature[] s2;
1836 Object obj = mSettings.getUserIdLP(uid1);
1837 if (obj != null) {
1838 if (obj instanceof SharedUserSetting) {
1839 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1840 } else if (obj instanceof PackageSetting) {
1841 s1 = ((PackageSetting)obj).signatures.mSignatures;
1842 } else {
1843 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1844 }
1845 } else {
1846 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1847 }
1848 obj = mSettings.getUserIdLP(uid2);
1849 if (obj != null) {
1850 if (obj instanceof SharedUserSetting) {
1851 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1852 } else if (obj instanceof PackageSetting) {
1853 s2 = ((PackageSetting)obj).signatures.mSignatures;
1854 } else {
1855 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1856 }
1857 } else {
1858 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1859 }
1860 return checkSignaturesLP(s1, s2);
1861 }
1862 }
1863
1864 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1865 if (s1 == null) {
1866 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1868 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1869 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001870 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1872 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001873 HashSet<Signature> set1 = new HashSet<Signature>();
1874 for (Signature sig : s1) {
1875 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001877 HashSet<Signature> set2 = new HashSet<Signature>();
1878 for (Signature sig : s2) {
1879 set2.add(sig);
1880 }
1881 // Make sure s2 contains all signatures in s1.
1882 if (set1.equals(set2)) {
1883 return PackageManager.SIGNATURE_MATCH;
1884 }
1885 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 }
1887
1888 public String[] getPackagesForUid(int uid) {
1889 synchronized (mPackages) {
1890 Object obj = mSettings.getUserIdLP(uid);
1891 if (obj instanceof SharedUserSetting) {
1892 SharedUserSetting sus = (SharedUserSetting)obj;
1893 final int N = sus.packages.size();
1894 String[] res = new String[N];
1895 Iterator<PackageSetting> it = sus.packages.iterator();
1896 int i=0;
1897 while (it.hasNext()) {
1898 res[i++] = it.next().name;
1899 }
1900 return res;
1901 } else if (obj instanceof PackageSetting) {
1902 PackageSetting ps = (PackageSetting)obj;
1903 return new String[] { ps.name };
1904 }
1905 }
1906 return null;
1907 }
1908
1909 public String getNameForUid(int uid) {
1910 synchronized (mPackages) {
1911 Object obj = mSettings.getUserIdLP(uid);
1912 if (obj instanceof SharedUserSetting) {
1913 SharedUserSetting sus = (SharedUserSetting)obj;
1914 return sus.name + ":" + sus.userId;
1915 } else if (obj instanceof PackageSetting) {
1916 PackageSetting ps = (PackageSetting)obj;
1917 return ps.name;
1918 }
1919 }
1920 return null;
1921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 public int getUidForSharedUser(String sharedUserName) {
1924 if(sharedUserName == null) {
1925 return -1;
1926 }
1927 synchronized (mPackages) {
1928 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1929 if(suid == null) {
1930 return -1;
1931 }
1932 return suid.userId;
1933 }
1934 }
1935
1936 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1937 int flags) {
1938 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001939 return chooseBestActivity(intent, resolvedType, flags, query);
1940 }
1941
Mihai Predaeae850c2009-05-13 10:13:48 +02001942 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1943 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 if (query != null) {
1945 final int N = query.size();
1946 if (N == 1) {
1947 return query.get(0);
1948 } else if (N > 1) {
1949 // If there is more than one activity with the same priority,
1950 // then let the user decide between them.
1951 ResolveInfo r0 = query.get(0);
1952 ResolveInfo r1 = query.get(1);
1953 if (false) {
1954 System.out.println(r0.activityInfo.name +
1955 "=" + r0.priority + " vs " +
1956 r1.activityInfo.name +
1957 "=" + r1.priority);
1958 }
1959 // If the first activity has a higher priority, or a different
1960 // default, then it is always desireable to pick it.
1961 if (r0.priority != r1.priority
1962 || r0.preferredOrder != r1.preferredOrder
1963 || r0.isDefault != r1.isDefault) {
1964 return query.get(0);
1965 }
1966 // If we have saved a preference for a preferred activity for
1967 // this Intent, use that.
1968 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1969 flags, query, r0.priority);
1970 if (ri != null) {
1971 return ri;
1972 }
1973 return mResolveInfo;
1974 }
1975 }
1976 return null;
1977 }
1978
1979 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1980 int flags, List<ResolveInfo> query, int priority) {
1981 synchronized (mPackages) {
1982 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1983 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001984 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1986 if (prefs != null && prefs.size() > 0) {
1987 // First figure out how good the original match set is.
1988 // We will only allow preferred activities that came
1989 // from the same match quality.
1990 int match = 0;
1991 final int N = query.size();
1992 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1993 for (int j=0; j<N; j++) {
1994 ResolveInfo ri = query.get(j);
1995 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1996 + ": 0x" + Integer.toHexString(match));
1997 if (ri.match > match) match = ri.match;
1998 }
1999 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2000 + Integer.toHexString(match));
2001 match &= IntentFilter.MATCH_CATEGORY_MASK;
2002 final int M = prefs.size();
2003 for (int i=0; i<M; i++) {
2004 PreferredActivity pa = prefs.get(i);
2005 if (pa.mMatch != match) {
2006 continue;
2007 }
2008 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2009 if (DEBUG_PREFERRED) {
2010 Log.v(TAG, "Got preferred activity:");
2011 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
2012 }
2013 if (ai != null) {
2014 for (int j=0; j<N; j++) {
2015 ResolveInfo ri = query.get(j);
2016 if (!ri.activityInfo.applicationInfo.packageName
2017 .equals(ai.applicationInfo.packageName)) {
2018 continue;
2019 }
2020 if (!ri.activityInfo.name.equals(ai.name)) {
2021 continue;
2022 }
2023
2024 // Okay we found a previously set preferred app.
2025 // If the result set is different from when this
2026 // was created, we need to clear it and re-ask the
2027 // user their preference.
2028 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002029 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 + intent + " type " + resolvedType);
2031 mSettings.mPreferredActivities.removeFilter(pa);
2032 return null;
2033 }
2034
2035 // Yay!
2036 return ri;
2037 }
2038 }
2039 }
2040 }
2041 }
2042 return null;
2043 }
2044
2045 public List<ResolveInfo> queryIntentActivities(Intent intent,
2046 String resolvedType, int flags) {
2047 ComponentName comp = intent.getComponent();
2048 if (comp != null) {
2049 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2050 ActivityInfo ai = getActivityInfo(comp, flags);
2051 if (ai != null) {
2052 ResolveInfo ri = new ResolveInfo();
2053 ri.activityInfo = ai;
2054 list.add(ri);
2055 }
2056 return list;
2057 }
2058
2059 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002060 String pkgName = intent.getPackage();
2061 if (pkgName == null) {
2062 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2063 resolvedType, flags);
2064 }
2065 PackageParser.Package pkg = mPackages.get(pkgName);
2066 if (pkg != null) {
2067 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2068 resolvedType, flags, pkg.activities);
2069 }
2070 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072 }
2073
2074 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2075 Intent[] specifics, String[] specificTypes, Intent intent,
2076 String resolvedType, int flags) {
2077 final String resultsAction = intent.getAction();
2078
2079 List<ResolveInfo> results = queryIntentActivities(
2080 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2081 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2082
2083 int specificsPos = 0;
2084 int N;
2085
2086 // todo: note that the algorithm used here is O(N^2). This
2087 // isn't a problem in our current environment, but if we start running
2088 // into situations where we have more than 5 or 10 matches then this
2089 // should probably be changed to something smarter...
2090
2091 // First we go through and resolve each of the specific items
2092 // that were supplied, taking care of removing any corresponding
2093 // duplicate items in the generic resolve list.
2094 if (specifics != null) {
2095 for (int i=0; i<specifics.length; i++) {
2096 final Intent sintent = specifics[i];
2097 if (sintent == null) {
2098 continue;
2099 }
2100
2101 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2102 String action = sintent.getAction();
2103 if (resultsAction != null && resultsAction.equals(action)) {
2104 // If this action was explicitly requested, then don't
2105 // remove things that have it.
2106 action = null;
2107 }
2108 ComponentName comp = sintent.getComponent();
2109 ResolveInfo ri = null;
2110 ActivityInfo ai = null;
2111 if (comp == null) {
2112 ri = resolveIntent(
2113 sintent,
2114 specificTypes != null ? specificTypes[i] : null,
2115 flags);
2116 if (ri == null) {
2117 continue;
2118 }
2119 if (ri == mResolveInfo) {
2120 // ACK! Must do something better with this.
2121 }
2122 ai = ri.activityInfo;
2123 comp = new ComponentName(ai.applicationInfo.packageName,
2124 ai.name);
2125 } else {
2126 ai = getActivityInfo(comp, flags);
2127 if (ai == null) {
2128 continue;
2129 }
2130 }
2131
2132 // Look for any generic query activities that are duplicates
2133 // of this specific one, and remove them from the results.
2134 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2135 N = results.size();
2136 int j;
2137 for (j=specificsPos; j<N; j++) {
2138 ResolveInfo sri = results.get(j);
2139 if ((sri.activityInfo.name.equals(comp.getClassName())
2140 && sri.activityInfo.applicationInfo.packageName.equals(
2141 comp.getPackageName()))
2142 || (action != null && sri.filter.matchAction(action))) {
2143 results.remove(j);
2144 if (Config.LOGV) Log.v(
2145 TAG, "Removing duplicate item from " + j
2146 + " due to specific " + specificsPos);
2147 if (ri == null) {
2148 ri = sri;
2149 }
2150 j--;
2151 N--;
2152 }
2153 }
2154
2155 // Add this specific item to its proper place.
2156 if (ri == null) {
2157 ri = new ResolveInfo();
2158 ri.activityInfo = ai;
2159 }
2160 results.add(specificsPos, ri);
2161 ri.specificIndex = i;
2162 specificsPos++;
2163 }
2164 }
2165
2166 // Now we go through the remaining generic results and remove any
2167 // duplicate actions that are found here.
2168 N = results.size();
2169 for (int i=specificsPos; i<N-1; i++) {
2170 final ResolveInfo rii = results.get(i);
2171 if (rii.filter == null) {
2172 continue;
2173 }
2174
2175 // Iterate over all of the actions of this result's intent
2176 // filter... typically this should be just one.
2177 final Iterator<String> it = rii.filter.actionsIterator();
2178 if (it == null) {
2179 continue;
2180 }
2181 while (it.hasNext()) {
2182 final String action = it.next();
2183 if (resultsAction != null && resultsAction.equals(action)) {
2184 // If this action was explicitly requested, then don't
2185 // remove things that have it.
2186 continue;
2187 }
2188 for (int j=i+1; j<N; j++) {
2189 final ResolveInfo rij = results.get(j);
2190 if (rij.filter != null && rij.filter.hasAction(action)) {
2191 results.remove(j);
2192 if (Config.LOGV) Log.v(
2193 TAG, "Removing duplicate item from " + j
2194 + " due to action " + action + " at " + i);
2195 j--;
2196 N--;
2197 }
2198 }
2199 }
2200
2201 // If the caller didn't request filter information, drop it now
2202 // so we don't have to marshall/unmarshall it.
2203 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2204 rii.filter = null;
2205 }
2206 }
2207
2208 // Filter out the caller activity if so requested.
2209 if (caller != null) {
2210 N = results.size();
2211 for (int i=0; i<N; i++) {
2212 ActivityInfo ainfo = results.get(i).activityInfo;
2213 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2214 && caller.getClassName().equals(ainfo.name)) {
2215 results.remove(i);
2216 break;
2217 }
2218 }
2219 }
2220
2221 // If the caller didn't request filter information,
2222 // drop them now so we don't have to
2223 // marshall/unmarshall it.
2224 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2225 N = results.size();
2226 for (int i=0; i<N; i++) {
2227 results.get(i).filter = null;
2228 }
2229 }
2230
2231 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2232 return results;
2233 }
2234
2235 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2236 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002237 ComponentName comp = intent.getComponent();
2238 if (comp != null) {
2239 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2240 ActivityInfo ai = getReceiverInfo(comp, flags);
2241 if (ai != null) {
2242 ResolveInfo ri = new ResolveInfo();
2243 ri.activityInfo = ai;
2244 list.add(ri);
2245 }
2246 return list;
2247 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002250 String pkgName = intent.getPackage();
2251 if (pkgName == null) {
2252 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2253 resolvedType, flags);
2254 }
2255 PackageParser.Package pkg = mPackages.get(pkgName);
2256 if (pkg != null) {
2257 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2258 resolvedType, flags, pkg.receivers);
2259 }
2260 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 }
2262 }
2263
2264 public ResolveInfo resolveService(Intent intent, String resolvedType,
2265 int flags) {
2266 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2267 flags);
2268 if (query != null) {
2269 if (query.size() >= 1) {
2270 // If there is more than one service with the same priority,
2271 // just arbitrarily pick the first one.
2272 return query.get(0);
2273 }
2274 }
2275 return null;
2276 }
2277
2278 public List<ResolveInfo> queryIntentServices(Intent intent,
2279 String resolvedType, int flags) {
2280 ComponentName comp = intent.getComponent();
2281 if (comp != null) {
2282 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2283 ServiceInfo si = getServiceInfo(comp, flags);
2284 if (si != null) {
2285 ResolveInfo ri = new ResolveInfo();
2286 ri.serviceInfo = si;
2287 list.add(ri);
2288 }
2289 return list;
2290 }
2291
2292 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002293 String pkgName = intent.getPackage();
2294 if (pkgName == null) {
2295 return (List<ResolveInfo>)mServices.queryIntent(intent,
2296 resolvedType, flags);
2297 }
2298 PackageParser.Package pkg = mPackages.get(pkgName);
2299 if (pkg != null) {
2300 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2301 resolvedType, flags, pkg.services);
2302 }
2303 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 }
2305 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307 public List<PackageInfo> getInstalledPackages(int flags) {
2308 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2309
2310 synchronized (mPackages) {
2311 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2312 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2313 while (i.hasNext()) {
2314 final PackageSetting ps = i.next();
2315 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2316 if(psPkg != null) {
2317 finalList.add(psPkg);
2318 }
2319 }
2320 }
2321 else {
2322 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2323 while (i.hasNext()) {
2324 final PackageParser.Package p = i.next();
2325 if (p.applicationInfo != null) {
2326 PackageInfo pi = generatePackageInfo(p, flags);
2327 if(pi != null) {
2328 finalList.add(pi);
2329 }
2330 }
2331 }
2332 }
2333 }
2334 return finalList;
2335 }
2336
2337 public List<ApplicationInfo> getInstalledApplications(int flags) {
2338 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2339 synchronized(mPackages) {
2340 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2341 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2342 while (i.hasNext()) {
2343 final PackageSetting ps = i.next();
2344 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2345 if(ai != null) {
2346 finalList.add(ai);
2347 }
2348 }
2349 }
2350 else {
2351 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2352 while (i.hasNext()) {
2353 final PackageParser.Package p = i.next();
2354 if (p.applicationInfo != null) {
2355 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2356 if(ai != null) {
2357 finalList.add(ai);
2358 }
2359 }
2360 }
2361 }
2362 }
2363 return finalList;
2364 }
2365
2366 public List<ApplicationInfo> getPersistentApplications(int flags) {
2367 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2368
2369 synchronized (mPackages) {
2370 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2371 while (i.hasNext()) {
2372 PackageParser.Package p = i.next();
2373 if (p.applicationInfo != null
2374 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2375 && (!mSafeMode || (p.applicationInfo.flags
2376 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2377 finalList.add(p.applicationInfo);
2378 }
2379 }
2380 }
2381
2382 return finalList;
2383 }
2384
2385 public ProviderInfo resolveContentProvider(String name, int flags) {
2386 synchronized (mPackages) {
2387 final PackageParser.Provider provider = mProviders.get(name);
2388 return provider != null
2389 && mSettings.isEnabledLP(provider.info, flags)
2390 && (!mSafeMode || (provider.info.applicationInfo.flags
2391 &ApplicationInfo.FLAG_SYSTEM) != 0)
2392 ? PackageParser.generateProviderInfo(provider, flags)
2393 : null;
2394 }
2395 }
2396
Fred Quintana718d8a22009-04-29 17:53:20 -07002397 /**
2398 * @deprecated
2399 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 public void querySyncProviders(List outNames, List outInfo) {
2401 synchronized (mPackages) {
2402 Iterator<Map.Entry<String, PackageParser.Provider>> i
2403 = mProviders.entrySet().iterator();
2404
2405 while (i.hasNext()) {
2406 Map.Entry<String, PackageParser.Provider> entry = i.next();
2407 PackageParser.Provider p = entry.getValue();
2408
2409 if (p.syncable
2410 && (!mSafeMode || (p.info.applicationInfo.flags
2411 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2412 outNames.add(entry.getKey());
2413 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2414 }
2415 }
2416 }
2417 }
2418
2419 public List<ProviderInfo> queryContentProviders(String processName,
2420 int uid, int flags) {
2421 ArrayList<ProviderInfo> finalList = null;
2422
2423 synchronized (mPackages) {
2424 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2425 while (i.hasNext()) {
2426 PackageParser.Provider p = i.next();
2427 if (p.info.authority != null
2428 && (processName == null ||
2429 (p.info.processName.equals(processName)
2430 && p.info.applicationInfo.uid == uid))
2431 && mSettings.isEnabledLP(p.info, flags)
2432 && (!mSafeMode || (p.info.applicationInfo.flags
2433 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2434 if (finalList == null) {
2435 finalList = new ArrayList<ProviderInfo>(3);
2436 }
2437 finalList.add(PackageParser.generateProviderInfo(p,
2438 flags));
2439 }
2440 }
2441 }
2442
2443 if (finalList != null) {
2444 Collections.sort(finalList, mProviderInitOrderSorter);
2445 }
2446
2447 return finalList;
2448 }
2449
2450 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2451 int flags) {
2452 synchronized (mPackages) {
2453 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2454 return PackageParser.generateInstrumentationInfo(i, flags);
2455 }
2456 }
2457
2458 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2459 int flags) {
2460 ArrayList<InstrumentationInfo> finalList =
2461 new ArrayList<InstrumentationInfo>();
2462
2463 synchronized (mPackages) {
2464 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2465 while (i.hasNext()) {
2466 PackageParser.Instrumentation p = i.next();
2467 if (targetPackage == null
2468 || targetPackage.equals(p.info.targetPackage)) {
2469 finalList.add(PackageParser.generateInstrumentationInfo(p,
2470 flags));
2471 }
2472 }
2473 }
2474
2475 return finalList;
2476 }
2477
2478 private void scanDirLI(File dir, int flags, int scanMode) {
2479 Log.d(TAG, "Scanning app dir " + dir);
2480
2481 String[] files = dir.list();
2482
2483 int i;
2484 for (i=0; i<files.length; i++) {
2485 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002486 if (!isPackageFilename(files[i])) {
2487 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002488 continue;
2489 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002490 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002492 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002493 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2494 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002495 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002496 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002497 file.delete();
2498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 }
2500 }
2501
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002502 private static File getSettingsProblemFile() {
2503 File dataDir = Environment.getDataDirectory();
2504 File systemDir = new File(dataDir, "system");
2505 File fname = new File(systemDir, "uiderrors.txt");
2506 return fname;
2507 }
2508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 private static void reportSettingsProblem(int priority, String msg) {
2510 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002511 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 FileOutputStream out = new FileOutputStream(fname, true);
2513 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002514 SimpleDateFormat formatter = new SimpleDateFormat();
2515 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2516 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 pw.close();
2518 FileUtils.setPermissions(
2519 fname.toString(),
2520 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2521 -1, -1);
2522 } catch (java.io.IOException e) {
2523 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002524 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 }
2526
2527 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2528 PackageParser.Package pkg, File srcFile, int parseFlags) {
2529 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002530 if (ps != null
2531 && ps.codePath.equals(srcFile)
2532 && ps.getTimeStamp() == srcFile.lastModified()) {
2533 if (ps.signatures.mSignatures != null
2534 && ps.signatures.mSignatures.length != 0) {
2535 // Optimization: reuse the existing cached certificates
2536 // if the package appears to be unchanged.
2537 pkg.mSignatures = ps.signatures.mSignatures;
2538 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 }
Jeff Browne7600722010-04-07 18:28:23 -07002540
2541 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002542 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002543 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2544 }
2545
2546 if (!pp.collectCertificates(pkg, parseFlags)) {
2547 mLastScanError = pp.getParseError();
2548 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 }
2550 }
2551 return true;
2552 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 /*
2555 * Scan a package and return the newly parsed package.
2556 * Returns null in case of errors and the error code is stored in mLastScanError
2557 */
2558 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002559 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002561 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002563 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002566 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 if (pkg == null) {
2568 mLastScanError = pp.getParseError();
2569 return null;
2570 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002571 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 PackageSetting updatedPkg;
2573 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002574 // Look to see if we already know about this package.
2575 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002576 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002577 // This package has been renamed to its original name. Let's
2578 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002579 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002580 }
2581 // If there was no original package, see one for the real package name.
2582 if (ps == null) {
2583 ps = mSettings.peekPackageLP(pkg.packageName);
2584 }
2585 // Check to see if this package could be hiding/updating a system
2586 // package. Must look for it either under the original or real
2587 // package name depending on our state.
2588 updatedPkg = mSettings.mDisabledSysPackages.get(
2589 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002591 // First check if this is a system package that may involve an update
2592 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2593 if (!ps.codePath.equals(scanFile)) {
2594 // The path has changed from what was last scanned... check the
2595 // version of the new path against what we have stored to determine
2596 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002597 if (pkg.mVersionCode < ps.versionCode) {
2598 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002599 // Ignore entry. Skip it.
2600 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2601 + "ignored: updated version " + ps.versionCode
2602 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002603 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2604 return null;
2605 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002606 // The current app on the system partion is better than
2607 // what we have updated to on the data partition; switch
2608 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002609 // At this point, its safely assumed that package installation for
2610 // apps in system partition will go through. If not there won't be a working
2611 // version of the app
2612 synchronized (mPackages) {
2613 // Just remove the loaded entries from package lists.
2614 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002615 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002616 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002617 + "reverting from " + ps.codePathString
2618 + ": new version " + pkg.mVersionCode
2619 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002620 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2621 args.cleanUpResourcesLI();
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07002622 removeNativeBinariesLI(pkg);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002623 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 }
2626 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002627 if (updatedPkg != null) {
2628 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2629 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2630 }
2631 // Verify certificates against what was last scanned
2632 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002633 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002634 return null;
2635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 // The apk is forward locked (not public) if its code and resources
2637 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002638 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002640 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002641 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002642
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002643 String codePath = null;
2644 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002645 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2646 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002647 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002648 } else {
2649 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002650 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002651 }
2652 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002653 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002654 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002655 codePath = pkg.mScanPath;
2656 // Set application objects path explicitly.
2657 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002659 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 }
2661
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002662 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2663 String destCodePath, String destResPath) {
2664 pkg.mPath = pkg.mScanPath = destCodePath;
2665 pkg.applicationInfo.sourceDir = destCodePath;
2666 pkg.applicationInfo.publicSourceDir = destResPath;
2667 }
2668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 private static String fixProcessName(String defProcessName,
2670 String processName, int uid) {
2671 if (processName == null) {
2672 return defProcessName;
2673 }
2674 return processName;
2675 }
2676
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002677 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002678 PackageParser.Package pkg) {
2679 if (pkgSetting.signatures.mSignatures != null) {
2680 // Already existing package. Make sure signatures match
2681 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2682 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002683 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002684 + " signatures do not match the previously installed version; ignoring!");
2685 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 return false;
2687 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002688 }
2689 // Check for shared user signatures
2690 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2691 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2692 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2693 Slog.e(TAG, "Package " + pkg.packageName
2694 + " has no signatures that match those in shared user "
2695 + pkgSetting.sharedUser.name + "; ignoring!");
2696 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2697 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 }
2700 return true;
2701 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002702
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002703 public boolean performDexOpt(String packageName) {
2704 if (!mNoDexOpt) {
2705 return false;
2706 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002707
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002708 PackageParser.Package p;
2709 synchronized (mPackages) {
2710 p = mPackages.get(packageName);
2711 if (p == null || p.mDidDexOpt) {
2712 return false;
2713 }
2714 }
2715 synchronized (mInstallLock) {
2716 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2717 }
2718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002719
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002720 static final int DEX_OPT_SKIPPED = 0;
2721 static final int DEX_OPT_PERFORMED = 1;
2722 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002723
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002724 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2725 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002726 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002727 String path = pkg.mScanPath;
2728 int ret = 0;
2729 try {
2730 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002731 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002732 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002733 pkg.mDidDexOpt = true;
2734 performed = true;
2735 }
2736 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002737 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002738 ret = -1;
2739 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002740 Slog.w(TAG, "IOException reading apk: " + path, e);
2741 ret = -1;
2742 } catch (dalvik.system.StaleDexCacheError e) {
2743 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2744 ret = -1;
2745 } catch (Exception e) {
2746 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002747 ret = -1;
2748 }
2749 if (ret < 0) {
2750 //error from installer
2751 return DEX_OPT_FAILED;
2752 }
2753 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002754
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002755 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2756 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002757
2758 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2759 return Environment.isEncryptedFilesystemEnabled() &&
2760 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2761 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002762
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002763 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2764 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002765 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002766 + " to " + newPkg.packageName
2767 + ": old package not in system partition");
2768 return false;
2769 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002770 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002771 + " to " + newPkg.packageName
2772 + ": old package still exists");
2773 return false;
2774 }
2775 return true;
2776 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002777
2778 private File getDataPathForPackage(PackageParser.Package pkg) {
2779 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2780 File dataPath;
2781 if (useEncryptedFSDir) {
2782 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2783 } else {
2784 dataPath = new File(mAppDataDir, pkg.packageName);
2785 }
2786 return dataPath;
2787 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002788
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002789 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2790 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002791 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002792 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2793 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002794 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002795 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002796 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2797 return null;
2798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 mScanningPath = scanFile;
2800 if (pkg == null) {
2801 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2802 return null;
2803 }
2804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2806 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2807 }
2808
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002809 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 synchronized (mPackages) {
2811 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002812 Slog.w(TAG, "*************************************************");
2813 Slog.w(TAG, "Core android package being redefined. Skipping.");
2814 Slog.w(TAG, " file=" + mScanningPath);
2815 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2817 return null;
2818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 // Set up information for our fall-back user intent resolution
2821 // activity.
2822 mPlatformPackage = pkg;
2823 pkg.mVersionCode = mSdkVersion;
2824 mAndroidApplication = pkg.applicationInfo;
2825 mResolveActivity.applicationInfo = mAndroidApplication;
2826 mResolveActivity.name = ResolverActivity.class.getName();
2827 mResolveActivity.packageName = mAndroidApplication.packageName;
2828 mResolveActivity.processName = mAndroidApplication.processName;
2829 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2830 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2831 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2832 mResolveActivity.exported = true;
2833 mResolveActivity.enabled = true;
2834 mResolveInfo.activityInfo = mResolveActivity;
2835 mResolveInfo.priority = 0;
2836 mResolveInfo.preferredOrder = 0;
2837 mResolveInfo.match = 0;
2838 mResolveComponentName = new ComponentName(
2839 mAndroidApplication.packageName, mResolveActivity.name);
2840 }
2841 }
2842
2843 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002844 TAG, "Scanning package " + pkg.packageName);
2845 if (mPackages.containsKey(pkg.packageName)
2846 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002847 Slog.w(TAG, "*************************************************");
2848 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002850 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2852 return null;
2853 }
2854
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002855 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002856 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2857 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 SharedUserSetting suid = null;
2860 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002861
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002862 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2863 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002864 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002865 pkg.mRealPackage = null;
2866 pkg.mAdoptPermissions = null;
2867 }
2868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 synchronized (mPackages) {
2870 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002871 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2872 if (mTmpSharedLibraries == null ||
2873 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2874 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2875 }
2876 int num = 0;
2877 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2878 for (int i=0; i<N; i++) {
2879 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002881 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002883 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2885 return null;
2886 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002887 mTmpSharedLibraries[num] = file;
2888 num++;
2889 }
2890 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2891 for (int i=0; i<N; i++) {
2892 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2893 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002894 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002895 + " desires unavailable shared library "
2896 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2897 } else {
2898 mTmpSharedLibraries[num] = file;
2899 num++;
2900 }
2901 }
2902 if (num > 0) {
2903 pkg.usesLibraryFiles = new String[num];
2904 System.arraycopy(mTmpSharedLibraries, 0,
2905 pkg.usesLibraryFiles, 0, num);
2906 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002907
Dianne Hackborn49237342009-08-27 20:08:01 -07002908 if (pkg.reqFeatures != null) {
2909 N = pkg.reqFeatures.size();
2910 for (int i=0; i<N; i++) {
2911 FeatureInfo fi = pkg.reqFeatures.get(i);
2912 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2913 // Don't care.
2914 continue;
2915 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002916
Dianne Hackborn49237342009-08-27 20:08:01 -07002917 if (fi.name != null) {
2918 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002919 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002920 + " requires unavailable feature "
2921 + fi.name + "; failing!");
2922 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2923 return null;
2924 }
2925 }
2926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 }
2928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 if (pkg.mSharedUserId != null) {
2931 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2932 pkg.applicationInfo.flags, true);
2933 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002934 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 + " for shared user failed");
2936 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2937 return null;
2938 }
2939 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2940 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2941 + suid.userId + "): packages=" + suid.packages);
2942 }
2943 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002944
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002945 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002946 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002947 Log.w(TAG, "WAITING FOR DEBUGGER");
2948 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002949 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2950 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002951 }
2952 }
2953
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002954 // Check if we are renaming from an original package name.
2955 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002956 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002957 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002958 // This package may need to be renamed to a previously
2959 // installed name. Let's check on that...
2960 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002961 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002962 // This package had originally been installed as the
2963 // original name, and we have already taken care of
2964 // transitioning to the new one. Just update the new
2965 // one to continue using the old name.
2966 realName = pkg.mRealPackage;
2967 if (!pkg.packageName.equals(renamed)) {
2968 // Callers into this function may have already taken
2969 // care of renaming the package; only do it here if
2970 // it is not already done.
2971 pkg.setPackageName(renamed);
2972 }
2973
Dianne Hackbornc1552392010-03-03 16:19:01 -08002974 } else {
2975 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2976 if ((origPackage=mSettings.peekPackageLP(
2977 pkg.mOriginalPackages.get(i))) != null) {
2978 // We do have the package already installed under its
2979 // original name... should we use it?
2980 if (!verifyPackageUpdate(origPackage, pkg)) {
2981 // New package is not compatible with original.
2982 origPackage = null;
2983 continue;
2984 } else if (origPackage.sharedUser != null) {
2985 // Make sure uid is compatible between packages.
2986 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002987 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002988 + " to " + pkg.packageName + ": old uid "
2989 + origPackage.sharedUser.name
2990 + " differs from " + pkg.mSharedUserId);
2991 origPackage = null;
2992 continue;
2993 }
2994 } else {
2995 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2996 + pkg.packageName + " to old name " + origPackage.name);
2997 }
2998 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002999 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003000 }
3001 }
3002 }
3003
3004 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003005 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003006 + " was transferred to another, but its .apk remains");
3007 }
3008
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003009 // Just create the setting, don't add it yet. For already existing packages
3010 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003011 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 destResourceFile, pkg.applicationInfo.flags, true, false);
3013 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003014 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3016 return null;
3017 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003018
3019 if (pkgSetting.origPackage != null) {
3020 // If we are first transitioning from an original package,
3021 // fix up the new package's name now. We need to do this after
3022 // looking up the package under its new name, so getPackageLP
3023 // can take care of fiddling things correctly.
3024 pkg.setPackageName(origPackage.name);
3025
3026 // File a report about this.
3027 String msg = "New package " + pkgSetting.realName
3028 + " renamed to replace old package " + pkgSetting.name;
3029 reportSettingsProblem(Log.WARN, msg);
3030
3031 // Make a note of it.
3032 mTransferedPackages.add(origPackage.name);
3033
3034 // No longer need to retain this.
3035 pkgSetting.origPackage = null;
3036 }
3037
3038 if (realName != null) {
3039 // Make a note of it.
3040 mTransferedPackages.add(pkg.packageName);
3041 }
3042
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003043 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003044 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3045 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 pkg.applicationInfo.uid = pkgSetting.userId;
3048 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003049
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003050 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003051 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 return null;
3053 }
3054 // The signature has changed, but this package is in the system
3055 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003056 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 // However... if this package is part of a shared user, but it
3058 // doesn't match the signature of the shared user, let's fail.
3059 // What this means is that you can't change the signatures
3060 // associated with an overall shared user, which doesn't seem all
3061 // that unreasonable.
3062 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003063 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3064 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3065 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3067 return null;
3068 }
3069 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003070 // File a report about this.
3071 String msg = "System package " + pkg.packageName
3072 + " signature changed; retaining data.";
3073 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003074 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003075
The Android Open Source Project10592532009-03-18 17:39:46 -07003076 // Verify that this new package doesn't have any content providers
3077 // that conflict with existing packages. Only do this if the
3078 // package isn't already installed, since we don't want to break
3079 // things that are installed.
3080 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3081 int N = pkg.providers.size();
3082 int i;
3083 for (i=0; i<N; i++) {
3084 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003085 if (p.info.authority != null) {
3086 String names[] = p.info.authority.split(";");
3087 for (int j = 0; j < names.length; j++) {
3088 if (mProviders.containsKey(names[j])) {
3089 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003090 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003091 " (in package " + pkg.applicationInfo.packageName +
3092 ") is already used by "
3093 + ((other != null && other.getComponentName() != null)
3094 ? other.getComponentName().getPackageName() : "?"));
3095 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3096 return null;
3097 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003098 }
3099 }
3100 }
3101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 }
3103
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003104 final String pkgName = pkg.packageName;
3105
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003106 if (pkg.mAdoptPermissions != null) {
3107 // This package wants to adopt ownership of permissions from
3108 // another package.
3109 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3110 String origName = pkg.mAdoptPermissions.get(i);
3111 PackageSetting orig = mSettings.peekPackageLP(origName);
3112 if (orig != null) {
3113 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003114 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003115 + origName + " to " + pkg.packageName);
3116 mSettings.transferPermissions(origName, pkg.packageName);
3117 }
3118 }
3119 }
3120 }
3121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 long scanFileTime = scanFile.lastModified();
3123 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3124 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3125 pkg.applicationInfo.processName = fixProcessName(
3126 pkg.applicationInfo.packageName,
3127 pkg.applicationInfo.processName,
3128 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129
3130 File dataPath;
3131 if (mPlatformPackage == pkg) {
3132 // The system package is special.
3133 dataPath = new File (Environment.getDataDirectory(), "system");
3134 pkg.applicationInfo.dataDir = dataPath.getPath();
3135 } else {
3136 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003137 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003138 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003139
3140 boolean uidError = false;
3141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 if (dataPath.exists()) {
3143 mOutPermissions[1] = 0;
3144 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3145 if (mOutPermissions[1] == pkg.applicationInfo.uid
3146 || !Process.supportsProcesses()) {
3147 pkg.applicationInfo.dataDir = dataPath.getPath();
3148 } else {
3149 boolean recovered = false;
3150 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3151 // If this is a system app, we can at least delete its
3152 // current data so the application will still work.
3153 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003154 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003155 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 // Old data gone!
3157 String msg = "System package " + pkg.packageName
3158 + " has changed from uid: "
3159 + mOutPermissions[1] + " to "
3160 + pkg.applicationInfo.uid + "; old data erased";
3161 reportSettingsProblem(Log.WARN, msg);
3162 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003164 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003165 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166 pkg.applicationInfo.uid);
3167 if (ret == -1) {
3168 // Ack should not happen!
3169 msg = "System package " + pkg.packageName
3170 + " could not have data directory re-created after delete.";
3171 reportSettingsProblem(Log.WARN, msg);
3172 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3173 return null;
3174 }
3175 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 if (!recovered) {
3178 mHasSystemUidErrors = true;
3179 }
3180 }
3181 if (!recovered) {
3182 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3183 + pkg.applicationInfo.uid + "/fs_"
3184 + mOutPermissions[1];
3185 String msg = "Package " + pkg.packageName
3186 + " has mismatched uid: "
3187 + mOutPermissions[1] + " on disk, "
3188 + pkg.applicationInfo.uid + " in settings";
3189 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003190 mSettings.mReadMessages.append(msg);
3191 mSettings.mReadMessages.append('\n');
3192 uidError = true;
3193 if (!pkgSetting.uidError) {
3194 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 }
3197 }
3198 }
3199 pkg.applicationInfo.dataDir = dataPath.getPath();
3200 } else {
3201 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3202 Log.v(TAG, "Want this data dir: " + dataPath);
3203 //invoke installer to do the actual installation
3204 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003205 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 pkg.applicationInfo.uid);
3207 if(ret < 0) {
3208 // Error from installer
3209 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3210 return null;
3211 }
3212 } else {
3213 dataPath.mkdirs();
3214 if (dataPath.exists()) {
3215 FileUtils.setPermissions(
3216 dataPath.toString(),
3217 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3218 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3219 }
3220 }
3221 if (dataPath.exists()) {
3222 pkg.applicationInfo.dataDir = dataPath.getPath();
3223 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003224 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 pkg.applicationInfo.dataDir = null;
3226 }
3227 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003228
3229 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 }
3231
3232 // Perform shared library installation and dex validation and
3233 // optimization, if this is not a system app.
3234 if (mInstaller != null) {
3235 String path = scanFile.getPath();
3236 if (scanFileNewer) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003237 // Note: We don't want to unpack the native binaries for
3238 // system applications, unless they have been updated
3239 // (the binaries are already under /system/lib).
3240 //
3241 // In other words, we're going to unpack the binaries
3242 // only for non-system apps and system app upgrades.
3243 //
3244 int flags = pkg.applicationInfo.flags;
3245 if ((flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
3246 (flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3247 Log.i(TAG, path + " changed; unpacking");
3248 int err = cachePackageSharedLibsLI(pkg, scanFile);
3249 if (err != PackageManager.INSTALL_SUCCEEDED) {
3250 mLastScanError = err;
3251 return null;
3252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 }
3254 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003255 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003256
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003257 if ((scanMode&SCAN_NO_DEX) == 0) {
3258 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3260 return null;
3261 }
3262 }
3263 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 if (mFactoryTest && pkg.requestedPermissions.contains(
3266 android.Manifest.permission.FACTORY_TEST)) {
3267 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3268 }
3269
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003270 // Request the ActivityManager to kill the process(only for existing packages)
3271 // so that we do not end up in a confused state while the user is still using the older
3272 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003273 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003274 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003275 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003276 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003279 // We don't expect installation to fail beyond this point,
3280 if ((scanMode&SCAN_MONITOR) != 0) {
3281 mAppDirs.put(pkg.mPath, pkg);
3282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003284 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003286 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003287 // Make sure we don't accidentally delete its data.
3288 mSettings.mPackagesToBeCleaned.remove(pkgName);
3289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 int N = pkg.providers.size();
3291 StringBuilder r = null;
3292 int i;
3293 for (i=0; i<N; i++) {
3294 PackageParser.Provider p = pkg.providers.get(i);
3295 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3296 p.info.processName, pkg.applicationInfo.uid);
3297 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3298 p.info.name), p);
3299 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003300 if (p.info.authority != null) {
3301 String names[] = p.info.authority.split(";");
3302 p.info.authority = null;
3303 for (int j = 0; j < names.length; j++) {
3304 if (j == 1 && p.syncable) {
3305 // We only want the first authority for a provider to possibly be
3306 // syncable, so if we already added this provider using a different
3307 // authority clear the syncable flag. We copy the provider before
3308 // changing it because the mProviders object contains a reference
3309 // to a provider that we don't want to change.
3310 // Only do this for the second authority since the resulting provider
3311 // object can be the same for all future authorities for this provider.
3312 p = new PackageParser.Provider(p);
3313 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003315 if (!mProviders.containsKey(names[j])) {
3316 mProviders.put(names[j], p);
3317 if (p.info.authority == null) {
3318 p.info.authority = names[j];
3319 } else {
3320 p.info.authority = p.info.authority + ";" + names[j];
3321 }
3322 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3323 Log.d(TAG, "Registered content provider: " + names[j] +
3324 ", className = " + p.info.name +
3325 ", isSyncable = " + p.info.isSyncable);
3326 } else {
3327 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003328 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003329 " (in package " + pkg.applicationInfo.packageName +
3330 "): name already used by "
3331 + ((other != null && other.getComponentName() != null)
3332 ? other.getComponentName().getPackageName() : "?"));
3333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 }
3335 }
3336 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3337 if (r == null) {
3338 r = new StringBuilder(256);
3339 } else {
3340 r.append(' ');
3341 }
3342 r.append(p.info.name);
3343 }
3344 }
3345 if (r != null) {
3346 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3347 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 N = pkg.services.size();
3350 r = null;
3351 for (i=0; i<N; i++) {
3352 PackageParser.Service s = pkg.services.get(i);
3353 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3354 s.info.processName, pkg.applicationInfo.uid);
3355 mServices.addService(s);
3356 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3357 if (r == null) {
3358 r = new StringBuilder(256);
3359 } else {
3360 r.append(' ');
3361 }
3362 r.append(s.info.name);
3363 }
3364 }
3365 if (r != null) {
3366 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3367 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 N = pkg.receivers.size();
3370 r = null;
3371 for (i=0; i<N; i++) {
3372 PackageParser.Activity a = pkg.receivers.get(i);
3373 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3374 a.info.processName, pkg.applicationInfo.uid);
3375 mReceivers.addActivity(a, "receiver");
3376 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3377 if (r == null) {
3378 r = new StringBuilder(256);
3379 } else {
3380 r.append(' ');
3381 }
3382 r.append(a.info.name);
3383 }
3384 }
3385 if (r != null) {
3386 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3387 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 N = pkg.activities.size();
3390 r = null;
3391 for (i=0; i<N; i++) {
3392 PackageParser.Activity a = pkg.activities.get(i);
3393 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3394 a.info.processName, pkg.applicationInfo.uid);
3395 mActivities.addActivity(a, "activity");
3396 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3397 if (r == null) {
3398 r = new StringBuilder(256);
3399 } else {
3400 r.append(' ');
3401 }
3402 r.append(a.info.name);
3403 }
3404 }
3405 if (r != null) {
3406 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3407 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 N = pkg.permissionGroups.size();
3410 r = null;
3411 for (i=0; i<N; i++) {
3412 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3413 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3414 if (cur == null) {
3415 mPermissionGroups.put(pg.info.name, pg);
3416 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3417 if (r == null) {
3418 r = new StringBuilder(256);
3419 } else {
3420 r.append(' ');
3421 }
3422 r.append(pg.info.name);
3423 }
3424 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003425 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426 + pg.info.packageName + " ignored: original from "
3427 + cur.info.packageName);
3428 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3429 if (r == null) {
3430 r = new StringBuilder(256);
3431 } else {
3432 r.append(' ');
3433 }
3434 r.append("DUP:");
3435 r.append(pg.info.name);
3436 }
3437 }
3438 }
3439 if (r != null) {
3440 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3441 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 N = pkg.permissions.size();
3444 r = null;
3445 for (i=0; i<N; i++) {
3446 PackageParser.Permission p = pkg.permissions.get(i);
3447 HashMap<String, BasePermission> permissionMap =
3448 p.tree ? mSettings.mPermissionTrees
3449 : mSettings.mPermissions;
3450 p.group = mPermissionGroups.get(p.info.group);
3451 if (p.info.group == null || p.group != null) {
3452 BasePermission bp = permissionMap.get(p.info.name);
3453 if (bp == null) {
3454 bp = new BasePermission(p.info.name, p.info.packageName,
3455 BasePermission.TYPE_NORMAL);
3456 permissionMap.put(p.info.name, bp);
3457 }
3458 if (bp.perm == null) {
3459 if (bp.sourcePackage == null
3460 || bp.sourcePackage.equals(p.info.packageName)) {
3461 BasePermission tree = findPermissionTreeLP(p.info.name);
3462 if (tree == null
3463 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003464 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 bp.perm = p;
3466 bp.uid = pkg.applicationInfo.uid;
3467 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3468 if (r == null) {
3469 r = new StringBuilder(256);
3470 } else {
3471 r.append(' ');
3472 }
3473 r.append(p.info.name);
3474 }
3475 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003476 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 + p.info.packageName + " ignored: base tree "
3478 + tree.name + " is from package "
3479 + tree.sourcePackage);
3480 }
3481 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003482 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 + p.info.packageName + " ignored: original from "
3484 + bp.sourcePackage);
3485 }
3486 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3487 if (r == null) {
3488 r = new StringBuilder(256);
3489 } else {
3490 r.append(' ');
3491 }
3492 r.append("DUP:");
3493 r.append(p.info.name);
3494 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003495 if (bp.perm == p) {
3496 bp.protectionLevel = p.info.protectionLevel;
3497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003499 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 + p.info.packageName + " ignored: no group "
3501 + p.group);
3502 }
3503 }
3504 if (r != null) {
3505 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3506 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003508 N = pkg.instrumentation.size();
3509 r = null;
3510 for (i=0; i<N; i++) {
3511 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3512 a.info.packageName = pkg.applicationInfo.packageName;
3513 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3514 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3515 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003516 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3518 if (r == null) {
3519 r = new StringBuilder(256);
3520 } else {
3521 r.append(' ');
3522 }
3523 r.append(a.info.name);
3524 }
3525 }
3526 if (r != null) {
3527 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3528 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003529
Dianne Hackborn854060af2009-07-09 18:14:31 -07003530 if (pkg.protectedBroadcasts != null) {
3531 N = pkg.protectedBroadcasts.size();
3532 for (i=0; i<N; i++) {
3533 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3534 }
3535 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 pkgSetting.setTimeStamp(scanFileTime);
3538 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 return pkg;
3541 }
3542
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003543 private void killApplication(String pkgName, int uid) {
3544 // Request the ActivityManager to kill the process(only for existing packages)
3545 // so that we do not end up in a confused state while the user is still using the older
3546 // version of the application while the new one gets installed.
3547 IActivityManager am = ActivityManagerNative.getDefault();
3548 if (am != null) {
3549 try {
3550 am.killApplicationWithUid(pkgName, uid);
3551 } catch (RemoteException e) {
3552 }
3553 }
3554 }
3555
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003556 // The following constants are returned by cachePackageSharedLibsForAbiLI
3557 // to indicate if native shared libraries were found in the package.
3558 // Values are:
3559 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3560 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3561 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3562 // in package (and not installed)
3563 //
3564 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3565 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3566 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003568 // Return the path of the directory that will contain the native binaries
3569 // of a given installed package. This is relative to the data path.
3570 //
3571 private static File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3572 return new File(pkg.applicationInfo.dataDir + "/lib");
3573 }
3574
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003575 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3576 // and automatically copy them to /data/data/<appname>/lib if present.
3577 //
3578 // NOTE: this method may throw an IOException if the library cannot
3579 // be copied to its final destination, e.g. if there isn't enough
3580 // room left on the data partition, or a ZipException if the package
3581 // file is malformed.
3582 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003583 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003584 File scanFile, String cpuAbi) throws IOException, ZipException {
3585 File sharedLibraryDir = getNativeBinaryDirForPackage(pkg);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003586 final String apkLib = "lib/";
3587 final int apkLibLen = apkLib.length();
3588 final int cpuAbiLen = cpuAbi.length();
3589 final String libPrefix = "lib";
3590 final int libPrefixLen = libPrefix.length();
3591 final String libSuffix = ".so";
3592 final int libSuffixLen = libSuffix.length();
3593 boolean hasNativeLibraries = false;
3594 boolean installedNativeLibraries = false;
3595
3596 // the minimum length of a valid native shared library of the form
3597 // lib/<something>/lib<name>.so.
3598 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3599
3600 ZipFile zipFile = new ZipFile(scanFile);
3601 Enumeration<ZipEntry> entries =
3602 (Enumeration<ZipEntry>) zipFile.entries();
3603
3604 while (entries.hasMoreElements()) {
3605 ZipEntry entry = entries.nextElement();
3606 // skip directories
3607 if (entry.isDirectory()) {
3608 continue;
3609 }
3610 String entryName = entry.getName();
3611
3612 // check that the entry looks like lib/<something>/lib<name>.so
3613 // here, but don't check the ABI just yet.
3614 //
3615 // - must be sufficiently long
3616 // - must end with libSuffix, i.e. ".so"
3617 // - must start with apkLib, i.e. "lib/"
3618 if (entryName.length() < minEntryLen ||
3619 !entryName.endsWith(libSuffix) ||
3620 !entryName.startsWith(apkLib) ) {
3621 continue;
3622 }
3623
3624 // file name must start with libPrefix, i.e. "lib"
3625 int lastSlash = entryName.lastIndexOf('/');
3626
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003627 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003628 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3629 continue;
3630 }
3631
3632 hasNativeLibraries = true;
3633
3634 // check the cpuAbi now, between lib/ and /lib<name>.so
3635 //
3636 if (lastSlash != apkLibLen + cpuAbiLen ||
3637 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3638 continue;
3639
3640 // extract the library file name, ensure it doesn't contain
3641 // weird characters. we're guaranteed here that it doesn't contain
3642 // a directory separator though.
3643 String libFileName = entryName.substring(lastSlash+1);
3644 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3645 continue;
3646 }
3647
3648 installedNativeLibraries = true;
3649
3650 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3651 File.separator + libFileName;
3652 File sharedLibraryFile = new File(sharedLibraryFilePath);
3653 if (! sharedLibraryFile.exists() ||
3654 sharedLibraryFile.length() != entry.getSize() ||
3655 sharedLibraryFile.lastModified() != entry.getTime()) {
3656 if (Config.LOGD) {
3657 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003659 if (mInstaller == null) {
3660 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003661 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003662 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003663 sharedLibraryFile);
3664 }
3665 }
3666 if (!hasNativeLibraries)
3667 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3668
3669 if (!installedNativeLibraries)
3670 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3671
3672 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3673 }
3674
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003675 // Find the gdbserver executable program in a package at
3676 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3677 //
3678 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3679 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3680 //
3681 private int cachePackageGdbServerLI(PackageParser.Package pkg,
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003682 File scanFile, String cpuAbi) throws IOException, ZipException {
3683 File installGdbServerDir = getNativeBinaryDirForPackage(pkg);
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003684 final String GDBSERVER = "gdbserver";
3685 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3686
3687 ZipFile zipFile = new ZipFile(scanFile);
3688 Enumeration<ZipEntry> entries =
3689 (Enumeration<ZipEntry>) zipFile.entries();
3690
3691 while (entries.hasMoreElements()) {
3692 ZipEntry entry = entries.nextElement();
3693 // skip directories
3694 if (entry.isDirectory()) {
3695 continue;
3696 }
3697 String entryName = entry.getName();
3698
3699 if (!entryName.equals(apkGdbServerPath)) {
3700 continue;
3701 }
3702
3703 String installGdbServerPath = installGdbServerDir.getPath() +
3704 "/" + GDBSERVER;
3705 File installGdbServerFile = new File(installGdbServerPath);
3706 if (! installGdbServerFile.exists() ||
3707 installGdbServerFile.length() != entry.getSize() ||
3708 installGdbServerFile.lastModified() != entry.getTime()) {
3709 if (Config.LOGD) {
3710 Log.d(TAG, "Caching gdbserver " + entry.getName());
3711 }
3712 if (mInstaller == null) {
3713 installGdbServerDir.mkdir();
3714 }
3715 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3716 installGdbServerFile);
3717 }
3718 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3719 }
3720 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3721 }
3722
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003723 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3724 // and copy them to /data/data/<appname>/lib.
3725 //
3726 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3727 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3728 // one if ro.product.cpu.abi2 is defined.
3729 //
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003730 private int cachePackageSharedLibsLI(PackageParser.Package pkg, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003731 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003732 try {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003733 int result = cachePackageSharedLibsForAbiLI(pkg, scanFile, cpuAbi);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003734
3735 // some architectures are capable of supporting several CPU ABIs
3736 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3737 // this is indicated by the definition of the ro.product.cpu.abi2
3738 // system property.
3739 //
3740 // only scan the package twice in case of ABI mismatch
3741 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003742 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003743 if (cpuAbi2 != null) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003744 result = cachePackageSharedLibsForAbiLI(pkg, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003746
3747 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003748 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003749 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003751
3752 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3753 cpuAbi = cpuAbi2;
3754 }
3755 }
3756
3757 // for debuggable packages, also extract gdbserver from lib/<abi>
3758 // into /data/data/<appname>/lib too.
3759 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3760 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003761 int result2 = cachePackageGdbServerLI(pkg, scanFile, cpuAbi);
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003762 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3763 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003766 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003767 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003768 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003770 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003771 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003773 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003774 }
3775
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003776 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003778 File binaryDir,
3779 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780 InputStream inputStream = zipFile.getInputStream(entry);
3781 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003782 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003784 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785 // now need to be left as world readable and owned by the system.
3786 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3787 ! tempFile.setLastModified(entry.getTime()) ||
3788 FileUtils.setPermissions(tempFilePath,
3789 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003790 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003792 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 // Failed to properly write file.
3794 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003795 throw new IOException("Couldn't create cached binary "
3796 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797 }
3798 } finally {
3799 inputStream.close();
3800 }
3801 }
3802
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003803 // Remove the native binaries of a given package. This simply
3804 // gets rid of the files in the 'lib' sub-directory.
3805 private void removeNativeBinariesLI(PackageParser.Package pkg) {
3806 File binaryDir = getNativeBinaryDirForPackage(pkg);
3807
3808 if (DEBUG_NATIVE) {
3809 Slog.w(TAG,"Deleting native binaries from: " + binaryDir.getPath());
3810 }
3811
3812 // Just remove any file in the directory. Since the directory
3813 // is owned by the 'system' UID, the application is not supposed
3814 // to have written anything there.
3815 //
3816 if (binaryDir.exists()) {
3817 File[] binaries = binaryDir.listFiles();
3818 if (binaries != null) {
3819 for (int nn=0; nn < binaries.length; nn++) {
3820 if (DEBUG_NATIVE) {
3821 Slog.d(TAG," Deleting " + binaries[nn].getName());
3822 }
3823 if (!binaries[nn].delete()) {
3824 Slog.w(TAG,"Could not delete native binary: " +
3825 binaries[nn].getPath());
3826 }
3827 }
3828 }
3829 // Do not delete 'lib' directory itself, or this will prevent
3830 // installation of future updates.
3831 }
3832 }
3833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3835 if (chatty && Config.LOGD) Log.d(
3836 TAG, "Removing package " + pkg.applicationInfo.packageName );
3837
3838 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003841 mPackages.remove(pkg.applicationInfo.packageName);
3842 if (pkg.mPath != null) {
3843 mAppDirs.remove(pkg.mPath);
3844 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 PackageSetting ps = (PackageSetting)pkg.mExtras;
3847 if (ps != null && ps.sharedUser != null) {
3848 // XXX don't do this until the data is removed.
3849 if (false) {
3850 ps.sharedUser.packages.remove(ps);
3851 if (ps.sharedUser.packages.size() == 0) {
3852 // Remove.
3853 }
3854 }
3855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 int N = pkg.providers.size();
3858 StringBuilder r = null;
3859 int i;
3860 for (i=0; i<N; i++) {
3861 PackageParser.Provider p = pkg.providers.get(i);
3862 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3863 p.info.name));
3864 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 /* The is another ContentProvider with this authority when
3867 * this app was installed so this authority is null,
3868 * Ignore it as we don't have to unregister the provider.
3869 */
3870 continue;
3871 }
3872 String names[] = p.info.authority.split(";");
3873 for (int j = 0; j < names.length; j++) {
3874 if (mProviders.get(names[j]) == p) {
3875 mProviders.remove(names[j]);
3876 if (chatty && Config.LOGD) Log.d(
3877 TAG, "Unregistered content provider: " + names[j] +
3878 ", className = " + p.info.name +
3879 ", isSyncable = " + p.info.isSyncable);
3880 }
3881 }
3882 if (chatty) {
3883 if (r == null) {
3884 r = new StringBuilder(256);
3885 } else {
3886 r.append(' ');
3887 }
3888 r.append(p.info.name);
3889 }
3890 }
3891 if (r != null) {
3892 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3893 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 N = pkg.services.size();
3896 r = null;
3897 for (i=0; i<N; i++) {
3898 PackageParser.Service s = pkg.services.get(i);
3899 mServices.removeService(s);
3900 if (chatty) {
3901 if (r == null) {
3902 r = new StringBuilder(256);
3903 } else {
3904 r.append(' ');
3905 }
3906 r.append(s.info.name);
3907 }
3908 }
3909 if (r != null) {
3910 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3911 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 N = pkg.receivers.size();
3914 r = null;
3915 for (i=0; i<N; i++) {
3916 PackageParser.Activity a = pkg.receivers.get(i);
3917 mReceivers.removeActivity(a, "receiver");
3918 if (chatty) {
3919 if (r == null) {
3920 r = new StringBuilder(256);
3921 } else {
3922 r.append(' ');
3923 }
3924 r.append(a.info.name);
3925 }
3926 }
3927 if (r != null) {
3928 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 N = pkg.activities.size();
3932 r = null;
3933 for (i=0; i<N; i++) {
3934 PackageParser.Activity a = pkg.activities.get(i);
3935 mActivities.removeActivity(a, "activity");
3936 if (chatty) {
3937 if (r == null) {
3938 r = new StringBuilder(256);
3939 } else {
3940 r.append(' ');
3941 }
3942 r.append(a.info.name);
3943 }
3944 }
3945 if (r != null) {
3946 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3947 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 N = pkg.permissions.size();
3950 r = null;
3951 for (i=0; i<N; i++) {
3952 PackageParser.Permission p = pkg.permissions.get(i);
3953 boolean tree = false;
3954 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3955 if (bp == null) {
3956 tree = true;
3957 bp = mSettings.mPermissionTrees.get(p.info.name);
3958 }
3959 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003960 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 if (chatty) {
3962 if (r == null) {
3963 r = new StringBuilder(256);
3964 } else {
3965 r.append(' ');
3966 }
3967 r.append(p.info.name);
3968 }
3969 }
3970 }
3971 if (r != null) {
3972 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3973 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 N = pkg.instrumentation.size();
3976 r = null;
3977 for (i=0; i<N; i++) {
3978 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003979 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 if (chatty) {
3981 if (r == null) {
3982 r = new StringBuilder(256);
3983 } else {
3984 r.append(' ');
3985 }
3986 r.append(a.info.name);
3987 }
3988 }
3989 if (r != null) {
3990 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3991 }
3992 }
3993 }
3994
3995 private static final boolean isPackageFilename(String name) {
3996 return name != null && name.endsWith(".apk");
3997 }
3998
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003999 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
4000 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
4001 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
4002 return true;
4003 }
4004 }
4005 return false;
4006 }
4007
4008 private void updatePermissionsLP(String changingPkg,
4009 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 // Make sure there are no dangling permission trees.
4011 Iterator<BasePermission> it = mSettings.mPermissionTrees
4012 .values().iterator();
4013 while (it.hasNext()) {
4014 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004015 if (bp.packageSetting == null) {
4016 // We may not yet have parsed the package, so just see if
4017 // we still know about its settings.
4018 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4019 }
4020 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004021 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 + " from package " + bp.sourcePackage);
4023 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004024 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4025 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4026 Slog.i(TAG, "Removing old permission tree: " + bp.name
4027 + " from package " + bp.sourcePackage);
4028 grantPermissions = true;
4029 it.remove();
4030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 }
4032 }
4033
4034 // Make sure all dynamic permissions have been assigned to a package,
4035 // and make sure there are no dangling permissions.
4036 it = mSettings.mPermissions.values().iterator();
4037 while (it.hasNext()) {
4038 BasePermission bp = it.next();
4039 if (bp.type == BasePermission.TYPE_DYNAMIC) {
4040 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
4041 + bp.name + " pkg=" + bp.sourcePackage
4042 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004043 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 BasePermission tree = findPermissionTreeLP(bp.name);
4045 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004046 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 bp.perm = new PackageParser.Permission(tree.perm.owner,
4048 new PermissionInfo(bp.pendingInfo));
4049 bp.perm.info.packageName = tree.perm.info.packageName;
4050 bp.perm.info.name = bp.name;
4051 bp.uid = tree.uid;
4052 }
4053 }
4054 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004055 if (bp.packageSetting == null) {
4056 // We may not yet have parsed the package, so just see if
4057 // we still know about its settings.
4058 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4059 }
4060 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004061 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004062 + " from package " + bp.sourcePackage);
4063 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004064 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4065 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4066 Slog.i(TAG, "Removing old permission: " + bp.name
4067 + " from package " + bp.sourcePackage);
4068 grantPermissions = true;
4069 it.remove();
4070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 }
4072 }
4073
4074 // Now update the permissions for all packages, in particular
4075 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004076 if (grantPermissions) {
4077 for (PackageParser.Package pkg : mPackages.values()) {
4078 if (pkg != pkgInfo) {
4079 grantPermissionsLP(pkg, false);
4080 }
4081 }
4082 }
4083
4084 if (pkgInfo != null) {
4085 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 }
4087 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
4090 final PackageSetting ps = (PackageSetting)pkg.mExtras;
4091 if (ps == null) {
4092 return;
4093 }
4094 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004095 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 if (replace) {
4098 ps.permissionsFixed = false;
4099 if (gp == ps) {
4100 gp.grantedPermissions.clear();
4101 gp.gids = mGlobalGids;
4102 }
4103 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 if (gp.gids == null) {
4106 gp.gids = mGlobalGids;
4107 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 final int N = pkg.requestedPermissions.size();
4110 for (int i=0; i<N; i++) {
4111 String name = pkg.requestedPermissions.get(i);
4112 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 if (false) {
4114 if (gp != ps) {
4115 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004116 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 }
4118 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004119 if (bp != null && bp.packageSetting != null) {
4120 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004122 boolean allowedSig = false;
4123 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4124 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004126 } else if (bp.packageSetting == null) {
4127 // This permission is invalid; skip it.
4128 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004129 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4130 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4131 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004133 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004135 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4137 // For updated system applications, the signatureOrSystem permission
4138 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004139 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4141 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4142 if(sysPs.grantedPermissions.contains(perm)) {
4143 allowed = true;
4144 } else {
4145 allowed = false;
4146 }
4147 } else {
4148 allowed = true;
4149 }
4150 }
4151 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004152 if (allowed) {
4153 allowedSig = true;
4154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 } else {
4156 allowed = false;
4157 }
4158 if (false) {
4159 if (gp != ps) {
4160 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4161 }
4162 }
4163 if (allowed) {
4164 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4165 && ps.permissionsFixed) {
4166 // If this is an existing, non-system package, then
4167 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004168 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004170 // Except... if this is a permission that was added
4171 // to the platform (note: need to only do this when
4172 // updating the platform).
4173 final int NP = PackageParser.NEW_PERMISSIONS.length;
4174 for (int ip=0; ip<NP; ip++) {
4175 final PackageParser.NewPermissionInfo npi
4176 = PackageParser.NEW_PERMISSIONS[ip];
4177 if (npi.name.equals(perm)
4178 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4179 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004180 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004181 + pkg.packageName);
4182 break;
4183 }
4184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004185 }
4186 }
4187 if (allowed) {
4188 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004189 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 gp.grantedPermissions.add(perm);
4191 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004192 } else if (!ps.haveGids) {
4193 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 }
4195 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004196 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004197 + " to package " + pkg.packageName
4198 + " because it was previously installed without");
4199 }
4200 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004201 if (gp.grantedPermissions.remove(perm)) {
4202 changedPermission = true;
4203 gp.gids = removeInts(gp.gids, bp.gids);
4204 Slog.i(TAG, "Un-granting permission " + perm
4205 + " from package " + pkg.packageName
4206 + " (protectionLevel=" + bp.protectionLevel
4207 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4208 + ")");
4209 } else {
4210 Slog.w(TAG, "Not granting permission " + perm
4211 + " to package " + pkg.packageName
4212 + " (protectionLevel=" + bp.protectionLevel
4213 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4214 + ")");
4215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 }
4217 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004218 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004219 + " in package " + pkg.packageName);
4220 }
4221 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004222
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004223 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004224 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4225 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004226 // This is the first that we have heard about this package, so the
4227 // permissions we have now selected are fixed until explicitly
4228 // changed.
4229 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004231 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004232 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 private final class ActivityIntentResolver
4235 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004236 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004238 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 }
4240
Mihai Preda074edef2009-05-18 17:13:31 +02004241 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004243 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4245 }
4246
Mihai Predaeae850c2009-05-13 10:13:48 +02004247 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4248 ArrayList<PackageParser.Activity> packageActivities) {
4249 if (packageActivities == null) {
4250 return null;
4251 }
4252 mFlags = flags;
4253 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4254 int N = packageActivities.size();
4255 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4256 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004257
4258 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004259 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004260 intentFilters = packageActivities.get(i).intents;
4261 if (intentFilters != null && intentFilters.size() > 0) {
4262 listCut.add(intentFilters);
4263 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004264 }
4265 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4266 }
4267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004269 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 if (SHOW_INFO || Config.LOGV) Log.v(
4271 TAG, " " + type + " " +
4272 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4273 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4274 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004275 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4277 if (SHOW_INFO || Config.LOGV) {
4278 Log.v(TAG, " IntentFilter:");
4279 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4280 }
4281 if (!intent.debugCheck()) {
4282 Log.w(TAG, "==> For Activity " + a.info.name);
4283 }
4284 addFilter(intent);
4285 }
4286 }
4287
4288 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004289 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 if (SHOW_INFO || Config.LOGV) Log.v(
4291 TAG, " " + type + " " +
4292 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4293 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4294 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004295 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4297 if (SHOW_INFO || Config.LOGV) {
4298 Log.v(TAG, " IntentFilter:");
4299 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4300 }
4301 removeFilter(intent);
4302 }
4303 }
4304
4305 @Override
4306 protected boolean allowFilterResult(
4307 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4308 ActivityInfo filterAi = filter.activity.info;
4309 for (int i=dest.size()-1; i>=0; i--) {
4310 ActivityInfo destAi = dest.get(i).activityInfo;
4311 if (destAi.name == filterAi.name
4312 && destAi.packageName == filterAi.packageName) {
4313 return false;
4314 }
4315 }
4316 return true;
4317 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004320 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4321 return info.activity.owner.packageName;
4322 }
4323
4324 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4326 int match) {
4327 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4328 return null;
4329 }
4330 final PackageParser.Activity activity = info.activity;
4331 if (mSafeMode && (activity.info.applicationInfo.flags
4332 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4333 return null;
4334 }
4335 final ResolveInfo res = new ResolveInfo();
4336 res.activityInfo = PackageParser.generateActivityInfo(activity,
4337 mFlags);
4338 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4339 res.filter = info;
4340 }
4341 res.priority = info.getPriority();
4342 res.preferredOrder = activity.owner.mPreferredOrder;
4343 //System.out.println("Result: " + res.activityInfo.className +
4344 // " = " + res.priority);
4345 res.match = match;
4346 res.isDefault = info.hasDefault;
4347 res.labelRes = info.labelRes;
4348 res.nonLocalizedLabel = info.nonLocalizedLabel;
4349 res.icon = info.icon;
4350 return res;
4351 }
4352
4353 @Override
4354 protected void sortResults(List<ResolveInfo> results) {
4355 Collections.sort(results, mResolvePrioritySorter);
4356 }
4357
4358 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004359 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004361 out.print(prefix); out.print(
4362 Integer.toHexString(System.identityHashCode(filter.activity)));
4363 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004364 out.print(filter.activity.getComponentShortName());
4365 out.print(" filter ");
4366 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 }
4368
4369// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4370// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4371// final List<ResolveInfo> retList = Lists.newArrayList();
4372// while (i.hasNext()) {
4373// final ResolveInfo resolveInfo = i.next();
4374// if (isEnabledLP(resolveInfo.activityInfo)) {
4375// retList.add(resolveInfo);
4376// }
4377// }
4378// return retList;
4379// }
4380
4381 // Keys are String (activity class name), values are Activity.
4382 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4383 = new HashMap<ComponentName, PackageParser.Activity>();
4384 private int mFlags;
4385 }
4386
4387 private final class ServiceIntentResolver
4388 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004389 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004391 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 }
4393
Mihai Preda074edef2009-05-18 17:13:31 +02004394 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004395 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004396 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4398 }
4399
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004400 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4401 ArrayList<PackageParser.Service> packageServices) {
4402 if (packageServices == null) {
4403 return null;
4404 }
4405 mFlags = flags;
4406 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4407 int N = packageServices.size();
4408 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4409 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4410
4411 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4412 for (int i = 0; i < N; ++i) {
4413 intentFilters = packageServices.get(i).intents;
4414 if (intentFilters != null && intentFilters.size() > 0) {
4415 listCut.add(intentFilters);
4416 }
4417 }
4418 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4419 }
4420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004421 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004422 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004423 if (SHOW_INFO || Config.LOGV) Log.v(
4424 TAG, " " + (s.info.nonLocalizedLabel != null
4425 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4426 if (SHOW_INFO || Config.LOGV) Log.v(
4427 TAG, " Class=" + s.info.name);
4428 int NI = s.intents.size();
4429 int j;
4430 for (j=0; j<NI; j++) {
4431 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4432 if (SHOW_INFO || Config.LOGV) {
4433 Log.v(TAG, " IntentFilter:");
4434 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4435 }
4436 if (!intent.debugCheck()) {
4437 Log.w(TAG, "==> For Service " + s.info.name);
4438 }
4439 addFilter(intent);
4440 }
4441 }
4442
4443 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004444 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 if (SHOW_INFO || Config.LOGV) Log.v(
4446 TAG, " " + (s.info.nonLocalizedLabel != null
4447 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4448 if (SHOW_INFO || Config.LOGV) Log.v(
4449 TAG, " Class=" + s.info.name);
4450 int NI = s.intents.size();
4451 int j;
4452 for (j=0; j<NI; j++) {
4453 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4454 if (SHOW_INFO || Config.LOGV) {
4455 Log.v(TAG, " IntentFilter:");
4456 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4457 }
4458 removeFilter(intent);
4459 }
4460 }
4461
4462 @Override
4463 protected boolean allowFilterResult(
4464 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4465 ServiceInfo filterSi = filter.service.info;
4466 for (int i=dest.size()-1; i>=0; i--) {
4467 ServiceInfo destAi = dest.get(i).serviceInfo;
4468 if (destAi.name == filterSi.name
4469 && destAi.packageName == filterSi.packageName) {
4470 return false;
4471 }
4472 }
4473 return true;
4474 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004477 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4478 return info.service.owner.packageName;
4479 }
4480
4481 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4483 int match) {
4484 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4485 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4486 return null;
4487 }
4488 final PackageParser.Service service = info.service;
4489 if (mSafeMode && (service.info.applicationInfo.flags
4490 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4491 return null;
4492 }
4493 final ResolveInfo res = new ResolveInfo();
4494 res.serviceInfo = PackageParser.generateServiceInfo(service,
4495 mFlags);
4496 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4497 res.filter = filter;
4498 }
4499 res.priority = info.getPriority();
4500 res.preferredOrder = service.owner.mPreferredOrder;
4501 //System.out.println("Result: " + res.activityInfo.className +
4502 // " = " + res.priority);
4503 res.match = match;
4504 res.isDefault = info.hasDefault;
4505 res.labelRes = info.labelRes;
4506 res.nonLocalizedLabel = info.nonLocalizedLabel;
4507 res.icon = info.icon;
4508 return res;
4509 }
4510
4511 @Override
4512 protected void sortResults(List<ResolveInfo> results) {
4513 Collections.sort(results, mResolvePrioritySorter);
4514 }
4515
4516 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004517 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004518 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004519 out.print(prefix); out.print(
4520 Integer.toHexString(System.identityHashCode(filter.service)));
4521 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004522 out.print(filter.service.getComponentShortName());
4523 out.print(" filter ");
4524 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 }
4526
4527// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4528// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4529// final List<ResolveInfo> retList = Lists.newArrayList();
4530// while (i.hasNext()) {
4531// final ResolveInfo resolveInfo = (ResolveInfo) i;
4532// if (isEnabledLP(resolveInfo.serviceInfo)) {
4533// retList.add(resolveInfo);
4534// }
4535// }
4536// return retList;
4537// }
4538
4539 // Keys are String (activity class name), values are Activity.
4540 private final HashMap<ComponentName, PackageParser.Service> mServices
4541 = new HashMap<ComponentName, PackageParser.Service>();
4542 private int mFlags;
4543 };
4544
4545 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4546 new Comparator<ResolveInfo>() {
4547 public int compare(ResolveInfo r1, ResolveInfo r2) {
4548 int v1 = r1.priority;
4549 int v2 = r2.priority;
4550 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4551 if (v1 != v2) {
4552 return (v1 > v2) ? -1 : 1;
4553 }
4554 v1 = r1.preferredOrder;
4555 v2 = r2.preferredOrder;
4556 if (v1 != v2) {
4557 return (v1 > v2) ? -1 : 1;
4558 }
4559 if (r1.isDefault != r2.isDefault) {
4560 return r1.isDefault ? -1 : 1;
4561 }
4562 v1 = r1.match;
4563 v2 = r2.match;
4564 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4565 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4566 }
4567 };
4568
4569 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4570 new Comparator<ProviderInfo>() {
4571 public int compare(ProviderInfo p1, ProviderInfo p2) {
4572 final int v1 = p1.initOrder;
4573 final int v2 = p2.initOrder;
4574 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4575 }
4576 };
4577
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004578 private static final void sendPackageBroadcast(String action, String pkg,
4579 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580 IActivityManager am = ActivityManagerNative.getDefault();
4581 if (am != null) {
4582 try {
4583 final Intent intent = new Intent(action,
4584 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4585 if (extras != null) {
4586 intent.putExtras(extras);
4587 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004588 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004589 am.broadcastIntent(null, intent, null, finishedReceiver,
4590 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004591 } catch (RemoteException ex) {
4592 }
4593 }
4594 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004595
4596 public String nextPackageToClean(String lastPackage) {
4597 synchronized (mPackages) {
4598 if (!mMediaMounted) {
4599 // If the external storage is no longer mounted at this point,
4600 // the caller may not have been able to delete all of this
4601 // packages files and can not delete any more. Bail.
4602 return null;
4603 }
4604 if (lastPackage != null) {
4605 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4606 }
4607 return mSettings.mPackagesToBeCleaned.size() > 0
4608 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4609 }
4610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004611
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004612 void schedulePackageCleaning(String packageName) {
4613 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4614 }
4615
4616 void startCleaningPackages() {
4617 synchronized (mPackages) {
4618 if (!mMediaMounted) {
4619 return;
4620 }
4621 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4622 return;
4623 }
4624 }
4625 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4626 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4627 IActivityManager am = ActivityManagerNative.getDefault();
4628 if (am != null) {
4629 try {
4630 am.startService(null, intent, null);
4631 } catch (RemoteException e) {
4632 }
4633 }
4634 }
4635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004636 private final class AppDirObserver extends FileObserver {
4637 public AppDirObserver(String path, int mask, boolean isrom) {
4638 super(path, mask);
4639 mRootDir = path;
4640 mIsRom = isrom;
4641 }
4642
4643 public void onEvent(int event, String path) {
4644 String removedPackage = null;
4645 int removedUid = -1;
4646 String addedPackage = null;
4647 int addedUid = -1;
4648
4649 synchronized (mInstallLock) {
4650 String fullPathStr = null;
4651 File fullPath = null;
4652 if (path != null) {
4653 fullPath = new File(mRootDir, path);
4654 fullPathStr = fullPath.getPath();
4655 }
4656
4657 if (Config.LOGV) Log.v(
4658 TAG, "File " + fullPathStr + " changed: "
4659 + Integer.toHexString(event));
4660
4661 if (!isPackageFilename(path)) {
4662 if (Config.LOGV) Log.v(
4663 TAG, "Ignoring change of non-package file: " + fullPathStr);
4664 return;
4665 }
4666
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004667 // Ignore packages that are being installed or
4668 // have just been installed.
4669 if (ignoreCodePath(fullPathStr)) {
4670 return;
4671 }
4672 PackageParser.Package p = null;
4673 synchronized (mPackages) {
4674 p = mAppDirs.get(fullPathStr);
4675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004676 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004677 if (p != null) {
4678 removePackageLI(p, true);
4679 removedPackage = p.applicationInfo.packageName;
4680 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004681 }
4682 }
4683
4684 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004685 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004686 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004687 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4688 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 PackageParser.PARSE_CHATTY |
4690 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004691 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004692 if (p != null) {
4693 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004694 updatePermissionsLP(p.packageName, p,
4695 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004696 }
4697 addedPackage = p.applicationInfo.packageName;
4698 addedUid = p.applicationInfo.uid;
4699 }
4700 }
4701 }
4702
4703 synchronized (mPackages) {
4704 mSettings.writeLP();
4705 }
4706 }
4707
4708 if (removedPackage != null) {
4709 Bundle extras = new Bundle(1);
4710 extras.putInt(Intent.EXTRA_UID, removedUid);
4711 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004712 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4713 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004714 }
4715 if (addedPackage != null) {
4716 Bundle extras = new Bundle(1);
4717 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004718 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4719 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004720 }
4721 }
4722
4723 private final String mRootDir;
4724 private final boolean mIsRom;
4725 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004727 /* Called when a downloaded package installation has been confirmed by the user */
4728 public void installPackage(
4729 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004730 installPackage(packageURI, observer, flags, null);
4731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004732
Jacek Surazski65e13172009-04-28 15:26:38 +02004733 /* Called when a downloaded package installation has been confirmed by the user */
4734 public void installPackage(
4735 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4736 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004737 mContext.enforceCallingOrSelfPermission(
4738 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004739
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004740 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004741 msg.obj = new InstallParams(packageURI, observer, flags,
4742 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004743 mHandler.sendMessage(msg);
4744 }
4745
Christopher Tate1bb69062010-02-19 17:02:12 -08004746 public void finishPackageInstall(int token) {
4747 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4748 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4749 mHandler.sendMessage(msg);
4750 }
4751
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004752 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004753 // Queue up an async operation since the package installation may take a little while.
4754 mHandler.post(new Runnable() {
4755 public void run() {
4756 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004757 // Result object to be returned
4758 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004759 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004760 res.uid = -1;
4761 res.pkg = null;
4762 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004763 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004764 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004765 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004766 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004767 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004768 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004770
4771 // A restore should be performed at this point if (a) the install
4772 // succeeded, (b) the operation is not an update, and (c) the new
4773 // package has a backupAgent defined.
4774 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004775 boolean doRestore = (!update
4776 && res.pkg != null
4777 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004778
4779 // Set up the post-install work request bookkeeping. This will be used
4780 // and cleaned up by the post-install event handling regardless of whether
4781 // there's a restore pass performed. Token values are >= 1.
4782 int token;
4783 if (mNextInstallToken < 0) mNextInstallToken = 1;
4784 token = mNextInstallToken++;
4785
4786 PostInstallData data = new PostInstallData(args, res);
4787 mRunningInstalls.put(token, data);
4788 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4789
4790 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4791 // Pass responsibility to the Backup Manager. It will perform a
4792 // restore if appropriate, then pass responsibility back to the
4793 // Package Manager to run the post-install observer callbacks
4794 // and broadcasts.
4795 IBackupManager bm = IBackupManager.Stub.asInterface(
4796 ServiceManager.getService(Context.BACKUP_SERVICE));
4797 if (bm != null) {
4798 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4799 + " to BM for possible restore");
4800 try {
4801 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4802 } catch (RemoteException e) {
4803 // can't happen; the backup manager is local
4804 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004805 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004806 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004807 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004808 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004809 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004810 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004813
4814 if (!doRestore) {
4815 // No restore possible, or the Backup Manager was mysteriously not
4816 // available -- just fire the post-install work request directly.
4817 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4818 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4819 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004821 }
4822 });
4823 }
4824
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004825 abstract class HandlerParams {
4826 final static int MAX_RETRIES = 4;
4827 int retry = 0;
4828 final void startCopy() {
4829 try {
4830 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4831 retry++;
4832 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004833 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004834 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4835 handleServiceError();
4836 return;
4837 } else {
4838 handleStartCopy();
4839 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4840 mHandler.sendEmptyMessage(MCS_UNBIND);
4841 }
4842 } catch (RemoteException e) {
4843 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4844 mHandler.sendEmptyMessage(MCS_RECONNECT);
4845 }
4846 handleReturnCode();
4847 }
4848
4849 final void serviceError() {
4850 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4851 handleServiceError();
4852 handleReturnCode();
4853 }
4854 abstract void handleStartCopy() throws RemoteException;
4855 abstract void handleServiceError();
4856 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004857 }
4858
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004859 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004860 final IPackageInstallObserver observer;
4861 int flags;
4862 final Uri packageURI;
4863 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004864 private InstallArgs mArgs;
4865 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004866 InstallParams(Uri packageURI,
4867 IPackageInstallObserver observer, int flags,
4868 String installerPackageName) {
4869 this.packageURI = packageURI;
4870 this.flags = flags;
4871 this.observer = observer;
4872 this.installerPackageName = installerPackageName;
4873 }
4874
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004875 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4876 String packageName = pkgLite.packageName;
4877 int installLocation = pkgLite.installLocation;
4878 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4879 synchronized (mPackages) {
4880 PackageParser.Package pkg = mPackages.get(packageName);
4881 if (pkg != null) {
4882 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4883 // Check for updated system application.
4884 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4885 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004886 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004887 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4888 }
4889 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4890 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004891 if (onSd) {
4892 // Install flag overrides everything.
4893 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4894 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004895 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004896 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4897 // Application explicitly specified internal.
4898 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4899 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4900 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004901 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004902 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004903 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4904 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4905 }
4906 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004907 }
4908 }
4909 } else {
4910 // Invalid install. Return error code
4911 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4912 }
4913 }
4914 }
4915 // All the special cases have been taken care of.
4916 // Return result based on recommended install location.
4917 if (onSd) {
4918 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4919 }
4920 return pkgLite.recommendedInstallLocation;
4921 }
4922
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004923 /*
4924 * Invoke remote method to get package information and install
4925 * location values. Override install location based on default
4926 * policy if needed and then create install arguments based
4927 * on the install location.
4928 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004929 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004930 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004931 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4932 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004933 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4934 if (onInt && onSd) {
4935 // Check if both bits are set.
4936 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4937 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4938 } else if (fwdLocked && onSd) {
4939 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004940 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004941 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004942 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004943 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004944 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004945 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004946 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4947 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4948 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4949 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4950 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004951 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4952 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4953 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004954 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4955 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004956 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004957 // Override with defaults if needed.
4958 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004959 if (!onSd && !onInt) {
4960 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004961 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4962 // Set the flag to install on external media.
4963 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004964 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004965 } else {
4966 // Make sure the flag for installing on external
4967 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004968 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004969 flags &= ~PackageManager.INSTALL_EXTERNAL;
4970 }
4971 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004972 }
4973 }
4974 // Create the file args now.
4975 mArgs = createInstallArgs(this);
4976 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4977 // Create copy only if we are not in an erroneous state.
4978 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004979 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004980 }
4981 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004982 }
4983
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004984 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004985 void handleReturnCode() {
4986 processPendingInstall(mArgs, mRet);
4987 }
4988
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004989 @Override
4990 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004991 mArgs = createInstallArgs(this);
4992 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004993 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004994 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004995
4996 /*
4997 * Utility class used in movePackage api.
4998 * srcArgs and targetArgs are not set for invalid flags and make
4999 * sure to do null checks when invoking methods on them.
5000 * We probably want to return ErrorPrams for both failed installs
5001 * and moves.
5002 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005003 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005004 final IPackageMoveObserver observer;
5005 final int flags;
5006 final String packageName;
5007 final InstallArgs srcArgs;
5008 final InstallArgs targetArgs;
5009 int mRet;
5010 MoveParams(InstallArgs srcArgs,
5011 IPackageMoveObserver observer,
5012 int flags, String packageName) {
5013 this.srcArgs = srcArgs;
5014 this.observer = observer;
5015 this.flags = flags;
5016 this.packageName = packageName;
5017 if (srcArgs != null) {
5018 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
5019 targetArgs = createInstallArgs(packageUri, flags, packageName);
5020 } else {
5021 targetArgs = null;
5022 }
5023 }
5024
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005025 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005026 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5027 // Check for storage space on target medium
5028 if (!targetArgs.checkFreeStorage(mContainerService)) {
5029 Log.w(TAG, "Insufficient storage to install");
5030 return;
5031 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005032 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005033 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005034 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005035 if (DEBUG_SD_INSTALL) {
5036 StringBuilder builder = new StringBuilder();
5037 if (srcArgs != null) {
5038 builder.append("src: ");
5039 builder.append(srcArgs.getCodePath());
5040 }
5041 if (targetArgs != null) {
5042 builder.append(" target : ");
5043 builder.append(targetArgs.getCodePath());
5044 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005045 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005046 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005047 }
5048
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005049 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005050 void handleReturnCode() {
5051 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005052 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
5053 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
5054 currentStatus = PackageManager.MOVE_SUCCEEDED;
5055 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
5056 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
5057 }
5058 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005059 }
5060
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005061 @Override
5062 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005063 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005064 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005065 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005066
5067 private InstallArgs createInstallArgs(InstallParams params) {
5068 if (installOnSd(params.flags)) {
5069 return new SdInstallArgs(params);
5070 } else {
5071 return new FileInstallArgs(params);
5072 }
5073 }
5074
5075 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
5076 if (installOnSd(flags)) {
5077 return new SdInstallArgs(fullCodePath, fullResourcePath);
5078 } else {
5079 return new FileInstallArgs(fullCodePath, fullResourcePath);
5080 }
5081 }
5082
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005083 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
5084 if (installOnSd(flags)) {
5085 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5086 return new SdInstallArgs(packageURI, cid);
5087 } else {
5088 return new FileInstallArgs(packageURI, pkgName);
5089 }
5090 }
5091
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005092 static abstract class InstallArgs {
5093 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005094 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005095 final int flags;
5096 final Uri packageURI;
5097 final String installerPackageName;
5098
5099 InstallArgs(Uri packageURI,
5100 IPackageInstallObserver observer, int flags,
5101 String installerPackageName) {
5102 this.packageURI = packageURI;
5103 this.flags = flags;
5104 this.observer = observer;
5105 this.installerPackageName = installerPackageName;
5106 }
5107
5108 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005109 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005110 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005111 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005112 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005113 abstract String getCodePath();
5114 abstract String getResourcePath();
5115 // Need installer lock especially for dex file removal.
5116 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005117 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005118 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005119 }
5120
5121 class FileInstallArgs extends InstallArgs {
5122 File installDir;
5123 String codeFileName;
5124 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005125 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005126
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005127 FileInstallArgs(InstallParams params) {
5128 super(params.packageURI, params.observer,
5129 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005130 }
5131
5132 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5133 super(null, null, 0, null);
5134 File codeFile = new File(fullCodePath);
5135 installDir = codeFile.getParentFile();
5136 codeFileName = fullCodePath;
5137 resourceFileName = fullResourcePath;
5138 }
5139
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005140 FileInstallArgs(Uri packageURI, String pkgName) {
5141 super(packageURI, null, 0, null);
5142 boolean fwdLocked = isFwdLocked(flags);
5143 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5144 String apkName = getNextCodePath(null, pkgName, ".apk");
5145 codeFileName = new File(installDir, apkName + ".apk").getPath();
5146 resourceFileName = getResourcePathFromCodePath();
5147 }
5148
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005149 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5150 return imcs.checkFreeStorage(false, packageURI);
5151 }
5152
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005153 String getCodePath() {
5154 return codeFileName;
5155 }
5156
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005157 void createCopyFile() {
5158 boolean fwdLocked = isFwdLocked(flags);
5159 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5160 codeFileName = createTempPackageFile(installDir).getPath();
5161 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005162 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005163 }
5164
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005165 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005166 if (temp) {
5167 // Generate temp file name
5168 createCopyFile();
5169 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005170 // Get a ParcelFileDescriptor to write to the output file
5171 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005172 if (!created) {
5173 try {
5174 codeFile.createNewFile();
5175 // Set permissions
5176 if (!setPermissions()) {
5177 // Failed setting permissions.
5178 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5179 }
5180 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005181 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005182 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5183 }
5184 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005185 ParcelFileDescriptor out = null;
5186 try {
5187 out = ParcelFileDescriptor.open(codeFile,
5188 ParcelFileDescriptor.MODE_READ_WRITE);
5189 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005190 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005191 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5192 }
5193 // Copy the resource now
5194 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5195 try {
5196 if (imcs.copyResource(packageURI, out)) {
5197 ret = PackageManager.INSTALL_SUCCEEDED;
5198 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005199 } finally {
5200 try { if (out != null) out.close(); } catch (IOException e) {}
5201 }
5202 return ret;
5203 }
5204
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005205 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005206 if (status != PackageManager.INSTALL_SUCCEEDED) {
5207 cleanUp();
5208 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005209 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005210 }
5211
5212 boolean doRename(int status, final String pkgName, String oldCodePath) {
5213 if (status != PackageManager.INSTALL_SUCCEEDED) {
5214 cleanUp();
5215 return false;
5216 } else {
5217 // Rename based on packageName
5218 File codeFile = new File(getCodePath());
5219 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5220 File desFile = new File(installDir, apkName + ".apk");
5221 if (!codeFile.renameTo(desFile)) {
5222 return false;
5223 }
5224 // Reset paths since the file has been renamed.
5225 codeFileName = desFile.getPath();
5226 resourceFileName = getResourcePathFromCodePath();
5227 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005228 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005229 // Failed setting permissions.
5230 return false;
5231 }
5232 return true;
5233 }
5234 }
5235
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005236 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005237 if (status != PackageManager.INSTALL_SUCCEEDED) {
5238 cleanUp();
5239 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005240 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005241 }
5242
5243 String getResourcePath() {
5244 return resourceFileName;
5245 }
5246
5247 String getResourcePathFromCodePath() {
5248 String codePath = getCodePath();
5249 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5250 String apkNameOnly = getApkName(codePath);
5251 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5252 } else {
5253 return codePath;
5254 }
5255 }
5256
5257 private boolean cleanUp() {
5258 boolean ret = true;
5259 String sourceDir = getCodePath();
5260 String publicSourceDir = getResourcePath();
5261 if (sourceDir != null) {
5262 File sourceFile = new File(sourceDir);
5263 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005264 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005265 ret = false;
5266 }
5267 // Delete application's code and resources
5268 sourceFile.delete();
5269 }
5270 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5271 final File publicSourceFile = new File(publicSourceDir);
5272 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005273 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005274 }
5275 if (publicSourceFile.exists()) {
5276 publicSourceFile.delete();
5277 }
5278 }
5279 return ret;
5280 }
5281
5282 void cleanUpResourcesLI() {
5283 String sourceDir = getCodePath();
5284 if (cleanUp() && mInstaller != null) {
5285 int retCode = mInstaller.rmdex(sourceDir);
5286 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005287 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005288 + " at location "
5289 + sourceDir + ", retcode=" + retCode);
5290 // we don't consider this to be a failure of the core package deletion
5291 }
5292 }
5293 }
5294
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005295 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005296 // TODO Do this in a more elegant way later on. for now just a hack
5297 if (!isFwdLocked(flags)) {
5298 final int filePermissions =
5299 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5300 |FileUtils.S_IROTH;
5301 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5302 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005303 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005304 getCodePath()
5305 + ". The return code was: " + retCode);
5306 // TODO Define new internal error
5307 return false;
5308 }
5309 return true;
5310 }
5311 return true;
5312 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005313
5314 boolean doPostDeleteLI(boolean delete) {
5315 cleanUpResourcesLI();
5316 return true;
5317 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005318 }
5319
5320 class SdInstallArgs extends InstallArgs {
5321 String cid;
5322 String cachePath;
5323 static final String RES_FILE_NAME = "pkg.apk";
5324
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005325 SdInstallArgs(InstallParams params) {
5326 super(params.packageURI, params.observer,
5327 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005328 }
5329
5330 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005331 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005332 // Extract cid from fullCodePath
5333 int eidx = fullCodePath.lastIndexOf("/");
5334 String subStr1 = fullCodePath.substring(0, eidx);
5335 int sidx = subStr1.lastIndexOf("/");
5336 cid = subStr1.substring(sidx+1, eidx);
5337 cachePath = subStr1;
5338 }
5339
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005340 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005341 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5342 this.cid = cid;
5343 }
5344
5345 SdInstallArgs(Uri packageURI, String cid) {
5346 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005347 this.cid = cid;
5348 }
5349
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005350 void createCopyFile() {
5351 cid = getTempContainerId();
5352 }
5353
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005354 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5355 return imcs.checkFreeStorage(true, packageURI);
5356 }
5357
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005358 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005359 if (temp) {
5360 createCopyFile();
5361 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005362 cachePath = imcs.copyResourceToContainer(
5363 packageURI, cid,
5364 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005365 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5366 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005367 }
5368
5369 @Override
5370 String getCodePath() {
5371 return cachePath + "/" + RES_FILE_NAME;
5372 }
5373
5374 @Override
5375 String getResourcePath() {
5376 return cachePath + "/" + RES_FILE_NAME;
5377 }
5378
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005379 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005380 if (status != PackageManager.INSTALL_SUCCEEDED) {
5381 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005382 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005383 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005384 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005385 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005386 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005387 if (cachePath == null) {
5388 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5389 }
5390 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005391 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005392 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005393 }
5394
5395 boolean doRename(int status, final String pkgName,
5396 String oldCodePath) {
5397 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005398 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005399 if (PackageHelper.isContainerMounted(cid)) {
5400 // Unmount the container
5401 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005402 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005403 return false;
5404 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005405 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005406 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005407 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5408 " which might be stale. Will try to clean up.");
5409 // Clean up the stale container and proceed to recreate.
5410 if (!PackageHelper.destroySdDir(newCacheId)) {
5411 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5412 return false;
5413 }
5414 // Successfully cleaned up stale container. Try to rename again.
5415 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5416 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5417 + " inspite of cleaning it up.");
5418 return false;
5419 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005420 }
5421 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005422 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005423 newCachePath = PackageHelper.mountSdDir(newCacheId,
5424 getEncryptKey(), Process.SYSTEM_UID);
5425 } else {
5426 newCachePath = PackageHelper.getSdDir(newCacheId);
5427 }
5428 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005429 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005430 return false;
5431 }
5432 Log.i(TAG, "Succesfully renamed " + cid +
5433 " at path: " + cachePath + " to " + newCacheId +
5434 " at new path: " + newCachePath);
5435 cid = newCacheId;
5436 cachePath = newCachePath;
5437 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005438 }
5439
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005440 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005441 if (status != PackageManager.INSTALL_SUCCEEDED) {
5442 cleanUp();
5443 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005444 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005445 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005446 PackageHelper.mountSdDir(cid,
5447 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005448 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005449 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005450 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005451 }
5452
5453 private void cleanUp() {
5454 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005455 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005456 }
5457
5458 void cleanUpResourcesLI() {
5459 String sourceFile = getCodePath();
5460 // Remove dex file
5461 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005462 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005463 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005464 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005465 + " at location "
5466 + sourceFile.toString() + ", retcode=" + retCode);
5467 // we don't consider this to be a failure of the core package deletion
5468 }
5469 }
5470 cleanUp();
5471 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005472
5473 boolean matchContainer(String app) {
5474 if (cid.startsWith(app)) {
5475 return true;
5476 }
5477 return false;
5478 }
5479
5480 String getPackageName() {
5481 int idx = cid.lastIndexOf("-");
5482 if (idx == -1) {
5483 return cid;
5484 }
5485 return cid.substring(0, idx);
5486 }
5487
5488 boolean doPostDeleteLI(boolean delete) {
5489 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005490 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005491 if (mounted) {
5492 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005493 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005494 }
5495 if (ret && delete) {
5496 cleanUpResourcesLI();
5497 }
5498 return ret;
5499 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005500 };
5501
5502 // Utility method used to create code paths based on package name and available index.
5503 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5504 String idxStr = "";
5505 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005506 // Fall back to default value of idx=1 if prefix is not
5507 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005508 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005509 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005510 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005511 if (subStr.endsWith(suffix)) {
5512 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005513 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005514 // If oldCodePath already contains prefix find out the
5515 // ending index to either increment or decrement.
5516 int sidx = subStr.lastIndexOf(prefix);
5517 if (sidx != -1) {
5518 subStr = subStr.substring(sidx + prefix.length());
5519 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005520 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5521 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005522 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005523 try {
5524 idx = Integer.parseInt(subStr);
5525 if (idx <= 1) {
5526 idx++;
5527 } else {
5528 idx--;
5529 }
5530 } catch(NumberFormatException e) {
5531 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005532 }
5533 }
5534 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005535 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005536 return prefix + idxStr;
5537 }
5538
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005539 // Utility method used to ignore ADD/REMOVE events
5540 // by directory observer.
5541 private static boolean ignoreCodePath(String fullPathStr) {
5542 String apkName = getApkName(fullPathStr);
5543 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5544 if (idx != -1 && ((idx+1) < apkName.length())) {
5545 // Make sure the package ends with a numeral
5546 String version = apkName.substring(idx+1);
5547 try {
5548 Integer.parseInt(version);
5549 return true;
5550 } catch (NumberFormatException e) {}
5551 }
5552 return false;
5553 }
5554
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005555 // Utility method that returns the relative package path with respect
5556 // to the installation directory. Like say for /data/data/com.test-1.apk
5557 // string com.test-1 is returned.
5558 static String getApkName(String codePath) {
5559 if (codePath == null) {
5560 return null;
5561 }
5562 int sidx = codePath.lastIndexOf("/");
5563 int eidx = codePath.lastIndexOf(".");
5564 if (eidx == -1) {
5565 eidx = codePath.length();
5566 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005567 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005568 return null;
5569 }
5570 return codePath.substring(sidx+1, eidx);
5571 }
5572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 class PackageInstalledInfo {
5574 String name;
5575 int uid;
5576 PackageParser.Package pkg;
5577 int returnCode;
5578 PackageRemovedInfo removedInfo;
5579 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 /*
5582 * Install a non-existing package.
5583 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005584 private void installNewPackageLI(PackageParser.Package pkg,
5585 int parseFlags,
5586 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005587 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005588 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005589 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005590
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005591 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005592 res.name = pkgName;
5593 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005594 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5595 // A package with the same name is already installed, though
5596 // it has been renamed to an older name. The package we
5597 // are trying to install should be installed as an update to
5598 // the existing one, but that has not been requested, so bail.
5599 Slog.w(TAG, "Attempt to re-install " + pkgName
5600 + " without first uninstalling package running as "
5601 + mSettings.mRenamedPackages.get(pkgName));
5602 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5603 return;
5604 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005605 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005607 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 + " without first uninstalling.");
5609 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5610 return;
5611 }
5612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005614 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005615 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005616 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005617 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5618 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5619 }
5620 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005621 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005622 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623 res);
5624 // delete the partially installed application. the data directory will have to be
5625 // restored if it was already existing
5626 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5627 // remove package from internal structures. Note that we want deletePackageX to
5628 // delete the package data and cache directories that it created in
5629 // scanPackageLocked, unless those directories existed before we even tried to
5630 // install.
5631 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005632 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5634 res.removedInfo);
5635 }
5636 }
5637 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005638
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005639 private void replacePackageLI(PackageParser.Package pkg,
5640 int parseFlags,
5641 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005642 String installerPackageName, PackageInstalledInfo res) {
5643
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005644 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005645 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 // First find the old package info and check signatures
5647 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005648 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005649 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005650 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5652 return;
5653 }
5654 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005655 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005656 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005657 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005659 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 }
5661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005663 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005664 PackageParser.Package pkg,
5665 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005666 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005667 PackageParser.Package newPackage = null;
5668 String pkgName = deletedPackage.packageName;
5669 boolean deletedPkg = true;
5670 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005671
Jacek Surazski65e13172009-04-28 15:26:38 +02005672 String oldInstallerPackageName = null;
5673 synchronized (mPackages) {
5674 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5675 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005678 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005679 res.removedInfo)) {
5680 // If the existing package was'nt successfully deleted
5681 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5682 deletedPkg = false;
5683 } else {
5684 // Successfully deleted the old package. Now proceed with re-installation
5685 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005686 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005688 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005689 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5690 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005691 }
5692 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005693 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005694 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 res);
5696 updatedSettings = true;
5697 }
5698 }
5699
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005700 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 // remove package from internal structures. Note that we want deletePackageX to
5702 // delete the package data and cache directories that it created in
5703 // scanPackageLocked, unless those directories existed before we even tried to
5704 // install.
5705 if(updatedSettings) {
5706 deletePackageLI(
5707 pkgName, true,
5708 PackageManager.DONT_DELETE_DATA,
5709 res.removedInfo);
5710 }
5711 // Since we failed to install the new package we need to restore the old
5712 // package that we deleted.
5713 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005714 File restoreFile = new File(deletedPackage.mPath);
5715 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005716 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005717 return;
5718 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005719 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005720 boolean oldOnSd = isExternal(deletedPackage);
5721 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5722 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5723 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5724 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5725 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5726 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5727 return;
5728 }
5729 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005730 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005731 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5732 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005733 mSettings.writeLP();
5734 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005735 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 }
5737 }
5738 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005741 PackageParser.Package pkg,
5742 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005743 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 PackageParser.Package newPackage = null;
5745 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005746 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005747 PackageParser.PARSE_IS_SYSTEM;
5748 String packageName = deletedPackage.packageName;
5749 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5750 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005751 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 return;
5753 }
5754 PackageParser.Package oldPkg;
5755 PackageSetting oldPkgSetting;
5756 synchronized (mPackages) {
5757 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005758 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005759 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5760 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005761 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 return;
5763 }
5764 }
5765 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5766 res.removedInfo.removedPackage = packageName;
5767 // Remove existing system package
5768 removePackageLI(oldPkg, true);
5769 synchronized (mPackages) {
5770 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5771 }
5772
5773 // Successfully disabled the old package. Now proceed with re-installation
5774 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5775 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005776 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005778 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5780 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5781 }
5782 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005783 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 updatedSettings = true;
5785 }
5786
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005787 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005788 // Re installation failed. Restore old information
5789 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005790 if (newPackage != null) {
5791 removePackageLI(newPackage, true);
5792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005793 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005794 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005796 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 // Restore the old system information in Settings
5798 synchronized(mPackages) {
5799 if(updatedSettings) {
5800 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005801 mSettings.setInstallerPackageName(packageName,
5802 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 }
5804 mSettings.writeLP();
5805 }
5806 }
5807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005808
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005809 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005810 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005811 int retCode;
5812 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5813 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5814 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005815 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005816 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5817 }
5818 }
5819 return PackageManager.INSTALL_SUCCEEDED;
5820 }
5821
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005822 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005823 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005824 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005825 synchronized (mPackages) {
5826 //write settings. the installStatus will be incomplete at this stage.
5827 //note that the new package setting would have already been
5828 //added to mPackages. It hasn't been persisted yet.
5829 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5830 mSettings.writeLP();
5831 }
5832
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005833 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005834 != PackageManager.INSTALL_SUCCEEDED) {
5835 // Discontinue if moving dex files failed.
5836 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005838 if((res.returnCode = setPermissionsLI(newPackage))
5839 != PackageManager.INSTALL_SUCCEEDED) {
5840 if (mInstaller != null) {
5841 mInstaller.rmdex(newPackage.mScanPath);
5842 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005843 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005845 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005848 updatePermissionsLP(newPackage.packageName, newPackage,
5849 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005850 res.name = pkgName;
5851 res.uid = newPackage.applicationInfo.uid;
5852 res.pkg = newPackage;
5853 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005854 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5856 //to update install status
5857 mSettings.writeLP();
5858 }
5859 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005860
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005861 private void installPackageLI(InstallArgs args,
5862 boolean newInstall, PackageInstalledInfo res) {
5863 int pFlags = args.flags;
5864 String installerPackageName = args.installerPackageName;
5865 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005866 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005867 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005868 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005869 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005870 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005871 // Result object to be returned
5872 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5873
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005874 // Retrieve PackageSettings and parse package
5875 int parseFlags = PackageParser.PARSE_CHATTY |
5876 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5877 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5878 parseFlags |= mDefParseFlags;
5879 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5880 pp.setSeparateProcesses(mSeparateProcesses);
5881 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5882 null, mMetrics, parseFlags);
5883 if (pkg == null) {
5884 res.returnCode = pp.getParseError();
5885 return;
5886 }
5887 String pkgName = res.name = pkg.packageName;
5888 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5889 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5890 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5891 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005892 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005893 }
5894 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5895 res.returnCode = pp.getParseError();
5896 return;
5897 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005898 // Get rid of all references to package scan path via parser.
5899 pp = null;
5900 String oldCodePath = null;
5901 boolean systemApp = false;
5902 synchronized (mPackages) {
5903 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005904 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5905 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005906 if (pkg.mOriginalPackages != null
5907 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005908 && mPackages.containsKey(oldName)) {
5909 // This package is derived from an original package,
5910 // and this device has been updating from that original
5911 // name. We must continue using the original name, so
5912 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005913 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005914 pkgName = pkg.packageName;
5915 replace = true;
5916 } else if (mPackages.containsKey(pkgName)) {
5917 // This package, under its official name, already exists
5918 // on the device; we should replace it.
5919 replace = true;
5920 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005921 }
5922 PackageSetting ps = mSettings.mPackages.get(pkgName);
5923 if (ps != null) {
5924 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5925 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5926 systemApp = (ps.pkg.applicationInfo.flags &
5927 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005928 }
5929 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005930 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005931
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005932 if (systemApp && onSd) {
5933 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005934 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005935 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5936 return;
5937 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005938
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005939 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5940 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5941 return;
5942 }
5943 // Set application objects path explicitly after the rename
5944 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005945 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005946 replacePackageLI(pkg, parseFlags, scanMode,
5947 installerPackageName, res);
5948 } else {
5949 installNewPackageLI(pkg, parseFlags, scanMode,
5950 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 }
5952 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005953
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005954 private int setPermissionsLI(PackageParser.Package newPackage) {
5955 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005956 int retCode = 0;
5957 // TODO Gross hack but fix later. Ideally move this to be a post installation
5958 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005959 if ((newPackage.applicationInfo.flags
5960 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5961 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005962 try {
5963 extractPublicFiles(newPackage, destResourceFile);
5964 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005965 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 -08005966 " forward-locked app.");
5967 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5968 } finally {
5969 //TODO clean up the extracted public files
5970 }
5971 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005972 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005973 newPackage.applicationInfo.uid);
5974 } else {
5975 final int filePermissions =
5976 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005977 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 newPackage.applicationInfo.uid);
5979 }
5980 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005981 // The permissions on the resource file was set when it was copied for
5982 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005986 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005987 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005989 // TODO Define new internal error
5990 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 }
5992 return PackageManager.INSTALL_SUCCEEDED;
5993 }
5994
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005995 private boolean isForwardLocked(PackageParser.Package pkg) {
5996 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 }
5998
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005999 private boolean isExternal(PackageParser.Package pkg) {
6000 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
6001 }
6002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006003 private void extractPublicFiles(PackageParser.Package newPackage,
6004 File publicZipFile) throws IOException {
6005 final ZipOutputStream publicZipOutStream =
6006 new ZipOutputStream(new FileOutputStream(publicZipFile));
6007 final ZipFile privateZip = new ZipFile(newPackage.mPath);
6008
6009 // Copy manifest, resources.arsc and res directory to public zip
6010
6011 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
6012 while (privateZipEntries.hasMoreElements()) {
6013 final ZipEntry zipEntry = privateZipEntries.nextElement();
6014 final String zipEntryName = zipEntry.getName();
6015 if ("AndroidManifest.xml".equals(zipEntryName)
6016 || "resources.arsc".equals(zipEntryName)
6017 || zipEntryName.startsWith("res/")) {
6018 try {
6019 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
6020 } catch (IOException e) {
6021 try {
6022 publicZipOutStream.close();
6023 throw e;
6024 } finally {
6025 publicZipFile.delete();
6026 }
6027 }
6028 }
6029 }
6030
6031 publicZipOutStream.close();
6032 FileUtils.setPermissions(
6033 publicZipFile.getAbsolutePath(),
6034 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6035 -1, -1);
6036 }
6037
6038 private static void copyZipEntry(ZipEntry zipEntry,
6039 ZipFile inZipFile,
6040 ZipOutputStream outZipStream) throws IOException {
6041 byte[] buffer = new byte[4096];
6042 int num;
6043
6044 ZipEntry newEntry;
6045 if (zipEntry.getMethod() == ZipEntry.STORED) {
6046 // Preserve the STORED method of the input entry.
6047 newEntry = new ZipEntry(zipEntry);
6048 } else {
6049 // Create a new entry so that the compressed len is recomputed.
6050 newEntry = new ZipEntry(zipEntry.getName());
6051 }
6052 outZipStream.putNextEntry(newEntry);
6053
6054 InputStream data = inZipFile.getInputStream(zipEntry);
6055 while ((num = data.read(buffer)) > 0) {
6056 outZipStream.write(buffer, 0, num);
6057 }
6058 outZipStream.flush();
6059 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 private void deleteTempPackageFiles() {
6062 FilenameFilter filter = new FilenameFilter() {
6063 public boolean accept(File dir, String name) {
6064 return name.startsWith("vmdl") && name.endsWith(".tmp");
6065 }
6066 };
6067 String tmpFilesList[] = mAppInstallDir.list(filter);
6068 if(tmpFilesList == null) {
6069 return;
6070 }
6071 for(int i = 0; i < tmpFilesList.length; i++) {
6072 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6073 tmpFile.delete();
6074 }
6075 }
6076
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006077 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 File tmpPackageFile;
6079 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006080 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006082 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083 return null;
6084 }
6085 try {
6086 FileUtils.setPermissions(
6087 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6088 -1, -1);
6089 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006090 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 return null;
6092 }
6093 return tmpPackageFile;
6094 }
6095
6096 public void deletePackage(final String packageName,
6097 final IPackageDeleteObserver observer,
6098 final int flags) {
6099 mContext.enforceCallingOrSelfPermission(
6100 android.Manifest.permission.DELETE_PACKAGES, null);
6101 // Queue up an async operation since the package deletion may take a little while.
6102 mHandler.post(new Runnable() {
6103 public void run() {
6104 mHandler.removeCallbacks(this);
6105 final boolean succeded = deletePackageX(packageName, true, true, flags);
6106 if (observer != null) {
6107 try {
6108 observer.packageDeleted(succeded);
6109 } catch (RemoteException e) {
6110 Log.i(TAG, "Observer no longer exists.");
6111 } //end catch
6112 } //end if
6113 } //end run
6114 });
6115 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 /**
6118 * This method is an internal method that could be get invoked either
6119 * to delete an installed package or to clean up a failed installation.
6120 * After deleting an installed package, a broadcast is sent to notify any
6121 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006122 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 * installation wouldn't have sent the initial broadcast either
6124 * The key steps in deleting a package are
6125 * deleting the package information in internal structures like mPackages,
6126 * deleting the packages base directories through installd
6127 * updating mSettings to reflect current status
6128 * persisting settings for later use
6129 * sending a broadcast if necessary
6130 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6132 boolean deleteCodeAndResources, int flags) {
6133 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006134 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006136 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6137 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6138 try {
6139 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006140 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006141 return false;
6142 }
6143 } catch (RemoteException e) {
6144 }
6145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006147 res = deletePackageLI(packageName, deleteCodeAndResources,
6148 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006152 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006153 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006154
6155 // If the removed package was a system update, the old system packaged
6156 // was re-enabled; we need to broadcast this information
6157 if (systemUpdate) {
6158 Bundle extras = new Bundle(1);
6159 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6160 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6161
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006162 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6163 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006165 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006166 // Force a gc here.
6167 Runtime.getRuntime().gc();
6168 // Delete the resources here after sending the broadcast to let
6169 // other processes clean up before deleting resources.
6170 if (info.args != null) {
6171 synchronized (mInstallLock) {
6172 info.args.doPostDeleteLI(deleteCodeAndResources);
6173 }
6174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006175 return res;
6176 }
6177
6178 static class PackageRemovedInfo {
6179 String removedPackage;
6180 int uid = -1;
6181 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006182 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006183 // Clean up resources deleted packages.
6184 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006185
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006186 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 Bundle extras = new Bundle(1);
6188 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6189 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6190 if (replacing) {
6191 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6192 }
6193 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006194 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006195 }
6196 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006197 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 }
6199 }
6200 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 /*
6203 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6204 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006205 * 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 -08006206 * delete a partially installed application.
6207 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006208 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 int flags) {
6210 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006211 if (outInfo != null) {
6212 outInfo.removedPackage = packageName;
6213 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006214 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 // Retrieve object to delete permissions for shared user later on
6216 PackageSetting deletedPs;
6217 synchronized (mPackages) {
6218 deletedPs = mSettings.mPackages.get(packageName);
6219 }
6220 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006221 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006223 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006225 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 + packageName + ", retcode=" + retCode);
6227 // we don't consider this to be a failure of the core package deletion
6228 }
6229 } else {
6230 //for emulator
6231 PackageParser.Package pkg = mPackages.get(packageName);
6232 File dataDir = new File(pkg.applicationInfo.dataDir);
6233 dataDir.delete();
6234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 }
6236 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006237 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006238 schedulePackageCleaning(packageName);
6239
6240 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6241 if (outInfo != null) {
6242 outInfo.removedUid = mSettings.removePackageLP(packageName);
6243 }
6244 if (deletedPs != null) {
6245 updatePermissionsLP(deletedPs.name, null, false, false);
6246 if (deletedPs.sharedUser != null) {
6247 // remove permissions associated with package
6248 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6249 }
6250 }
6251 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006252 // remove from preferred activities.
6253 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6254 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6255 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6256 removed.add(pa);
6257 }
6258 }
6259 for (PreferredActivity pa : removed) {
6260 mSettings.mPreferredActivities.removeFilter(pa);
6261 }
6262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006264 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 }
6266 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 /*
6269 * Tries to delete system package.
6270 */
6271 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006272 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006273 ApplicationInfo applicationInfo = p.applicationInfo;
6274 //applicable for non-partially installed applications only
6275 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006276 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 return false;
6278 }
6279 PackageSetting ps = null;
6280 // Confirm if the system package has been updated
6281 // An updated system app can be deleted. This will also have to restore
6282 // the system pkg from system partition
6283 synchronized (mPackages) {
6284 ps = mSettings.getDisabledSystemPkg(p.packageName);
6285 }
6286 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006287 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 return false;
6289 } else {
6290 Log.i(TAG, "Deleting system pkg from data partition");
6291 }
6292 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006293 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006294 boolean deleteCodeAndResources = false;
6295 if (ps.versionCode < p.mVersionCode) {
6296 // Delete code and resources for downgrades
6297 deleteCodeAndResources = true;
6298 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6299 flags &= ~PackageManager.DONT_DELETE_DATA;
6300 }
6301 } else {
6302 // Preserve data by setting flag
6303 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6304 flags |= PackageManager.DONT_DELETE_DATA;
6305 }
6306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6308 if (!ret) {
6309 return false;
6310 }
6311 synchronized (mPackages) {
6312 // Reinstate the old system package
6313 mSettings.enableSystemPackageLP(p.packageName);
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07006314 // Remove any native libraries.
6315 removeNativeBinariesLI(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 }
6317 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006318 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006320 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006322 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006323 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 return false;
6325 }
6326 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006327 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 mSettings.writeLP();
6329 }
6330 return true;
6331 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6334 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6335 ApplicationInfo applicationInfo = p.applicationInfo;
6336 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006337 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 return false;
6339 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006340 if (outInfo != null) {
6341 outInfo.uid = applicationInfo.uid;
6342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343
6344 // Delete package data from internal structures and also remove data if flag is set
6345 removePackageDataLI(p, outInfo, flags);
6346
6347 // Delete application code and resources
6348 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006349 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006350 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006351 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006352 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6353 PackageManager.INSTALL_FORWARD_LOCK : 0;
6354 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006355 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006356 }
6357 return true;
6358 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 /*
6361 * This method handles package deletion in general
6362 */
6363 private boolean deletePackageLI(String packageName,
6364 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6365 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006366 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 return false;
6368 }
6369 PackageParser.Package p;
6370 boolean dataOnly = false;
6371 synchronized (mPackages) {
6372 p = mPackages.get(packageName);
6373 if (p == null) {
6374 //this retrieves partially installed apps
6375 dataOnly = true;
6376 PackageSetting ps = mSettings.mPackages.get(packageName);
6377 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006378 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006379 return false;
6380 }
6381 p = ps.pkg;
6382 }
6383 }
6384 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006385 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 return false;
6387 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 if (dataOnly) {
6390 // Delete application data first
6391 removePackageDataLI(p, outInfo, flags);
6392 return true;
6393 }
6394 // At this point the package should have ApplicationInfo associated with it
6395 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006396 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006397 return false;
6398 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006399 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6401 Log.i(TAG, "Removing system package:"+p.packageName);
6402 // When an updated system application is deleted we delete the existing resources as well and
6403 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006404 ret = deleteSystemPackageLI(p, flags, outInfo);
6405 } else {
6406 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006407 // Kill application pre-emptively especially for apps on sd.
6408 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006409 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006411 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 public void clearApplicationUserData(final String packageName,
6415 final IPackageDataObserver observer) {
6416 mContext.enforceCallingOrSelfPermission(
6417 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6418 // Queue up an async operation since the package deletion may take a little while.
6419 mHandler.post(new Runnable() {
6420 public void run() {
6421 mHandler.removeCallbacks(this);
6422 final boolean succeeded;
6423 synchronized (mInstallLock) {
6424 succeeded = clearApplicationUserDataLI(packageName);
6425 }
6426 if (succeeded) {
6427 // invoke DeviceStorageMonitor's update method to clear any notifications
6428 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6429 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6430 if (dsm != null) {
6431 dsm.updateMemory();
6432 }
6433 }
6434 if(observer != null) {
6435 try {
6436 observer.onRemoveCompleted(packageName, succeeded);
6437 } catch (RemoteException e) {
6438 Log.i(TAG, "Observer no longer exists.");
6439 }
6440 } //end if observer
6441 } //end run
6442 });
6443 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 private boolean clearApplicationUserDataLI(String packageName) {
6446 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006447 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 return false;
6449 }
6450 PackageParser.Package p;
6451 boolean dataOnly = false;
6452 synchronized (mPackages) {
6453 p = mPackages.get(packageName);
6454 if(p == null) {
6455 dataOnly = true;
6456 PackageSetting ps = mSettings.mPackages.get(packageName);
6457 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006458 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 return false;
6460 }
6461 p = ps.pkg;
6462 }
6463 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006464 boolean useEncryptedFSDir = false;
6465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006466 if(!dataOnly) {
6467 //need to check this only for fully installed applications
6468 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006469 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 return false;
6471 }
6472 final ApplicationInfo applicationInfo = p.applicationInfo;
6473 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006474 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 return false;
6476 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006477 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 }
6479 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006480 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006482 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 + packageName);
6484 return false;
6485 }
6486 }
6487 return true;
6488 }
6489
6490 public void deleteApplicationCacheFiles(final String packageName,
6491 final IPackageDataObserver observer) {
6492 mContext.enforceCallingOrSelfPermission(
6493 android.Manifest.permission.DELETE_CACHE_FILES, null);
6494 // Queue up an async operation since the package deletion may take a little while.
6495 mHandler.post(new Runnable() {
6496 public void run() {
6497 mHandler.removeCallbacks(this);
6498 final boolean succeded;
6499 synchronized (mInstallLock) {
6500 succeded = deleteApplicationCacheFilesLI(packageName);
6501 }
6502 if(observer != null) {
6503 try {
6504 observer.onRemoveCompleted(packageName, succeded);
6505 } catch (RemoteException e) {
6506 Log.i(TAG, "Observer no longer exists.");
6507 }
6508 } //end if observer
6509 } //end run
6510 });
6511 }
6512
6513 private boolean deleteApplicationCacheFilesLI(String packageName) {
6514 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006515 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516 return false;
6517 }
6518 PackageParser.Package p;
6519 synchronized (mPackages) {
6520 p = mPackages.get(packageName);
6521 }
6522 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006523 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 return false;
6525 }
6526 final ApplicationInfo applicationInfo = p.applicationInfo;
6527 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006528 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 return false;
6530 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006531 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006533 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006534 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006535 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 + packageName);
6537 return false;
6538 }
6539 }
6540 return true;
6541 }
6542
6543 public void getPackageSizeInfo(final String packageName,
6544 final IPackageStatsObserver observer) {
6545 mContext.enforceCallingOrSelfPermission(
6546 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6547 // Queue up an async operation since the package deletion may take a little while.
6548 mHandler.post(new Runnable() {
6549 public void run() {
6550 mHandler.removeCallbacks(this);
6551 PackageStats lStats = new PackageStats(packageName);
6552 final boolean succeded;
6553 synchronized (mInstallLock) {
6554 succeded = getPackageSizeInfoLI(packageName, lStats);
6555 }
6556 if(observer != null) {
6557 try {
6558 observer.onGetStatsCompleted(lStats, succeded);
6559 } catch (RemoteException e) {
6560 Log.i(TAG, "Observer no longer exists.");
6561 }
6562 } //end if observer
6563 } //end run
6564 });
6565 }
6566
6567 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6568 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006569 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006570 return false;
6571 }
6572 PackageParser.Package p;
6573 boolean dataOnly = false;
6574 synchronized (mPackages) {
6575 p = mPackages.get(packageName);
6576 if(p == null) {
6577 dataOnly = true;
6578 PackageSetting ps = mSettings.mPackages.get(packageName);
6579 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006580 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 return false;
6582 }
6583 p = ps.pkg;
6584 }
6585 }
6586 String publicSrcDir = null;
6587 if(!dataOnly) {
6588 final ApplicationInfo applicationInfo = p.applicationInfo;
6589 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006590 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006591 return false;
6592 }
6593 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6594 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006595 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 if (mInstaller != null) {
6597 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006598 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006599 if (res < 0) {
6600 return false;
6601 } else {
6602 return true;
6603 }
6604 }
6605 return true;
6606 }
6607
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 public void addPackageToPreferred(String packageName) {
6610 mContext.enforceCallingOrSelfPermission(
6611 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006612 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 }
6614
6615 public void removePackageFromPreferred(String packageName) {
6616 mContext.enforceCallingOrSelfPermission(
6617 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006618 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006619 }
6620
6621 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006622 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006623 }
6624
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006625 int getUidTargetSdkVersionLockedLP(int uid) {
6626 Object obj = mSettings.getUserIdLP(uid);
6627 if (obj instanceof SharedUserSetting) {
6628 SharedUserSetting sus = (SharedUserSetting)obj;
6629 final int N = sus.packages.size();
6630 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6631 Iterator<PackageSetting> it = sus.packages.iterator();
6632 int i=0;
6633 while (it.hasNext()) {
6634 PackageSetting ps = it.next();
6635 if (ps.pkg != null) {
6636 int v = ps.pkg.applicationInfo.targetSdkVersion;
6637 if (v < vers) vers = v;
6638 }
6639 }
6640 return vers;
6641 } else if (obj instanceof PackageSetting) {
6642 PackageSetting ps = (PackageSetting)obj;
6643 if (ps.pkg != null) {
6644 return ps.pkg.applicationInfo.targetSdkVersion;
6645 }
6646 }
6647 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6648 }
6649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 public void addPreferredActivity(IntentFilter filter, int match,
6651 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006652 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006653 if (mContext.checkCallingOrSelfPermission(
6654 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6655 != PackageManager.PERMISSION_GRANTED) {
6656 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6657 < Build.VERSION_CODES.FROYO) {
6658 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6659 + Binder.getCallingUid());
6660 return;
6661 }
6662 mContext.enforceCallingOrSelfPermission(
6663 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6664 }
6665
6666 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6668 mSettings.mPreferredActivities.addFilter(
6669 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006670 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 }
6672 }
6673
Satish Sampath8dbe6122009-06-02 23:35:54 +01006674 public void replacePreferredActivity(IntentFilter filter, int match,
6675 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006676 if (filter.countActions() != 1) {
6677 throw new IllegalArgumentException(
6678 "replacePreferredActivity expects filter to have only 1 action.");
6679 }
6680 if (filter.countCategories() != 1) {
6681 throw new IllegalArgumentException(
6682 "replacePreferredActivity expects filter to have only 1 category.");
6683 }
6684 if (filter.countDataAuthorities() != 0
6685 || filter.countDataPaths() != 0
6686 || filter.countDataSchemes() != 0
6687 || filter.countDataTypes() != 0) {
6688 throw new IllegalArgumentException(
6689 "replacePreferredActivity expects filter to have no data authorities, " +
6690 "paths, schemes or types.");
6691 }
6692 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006693 if (mContext.checkCallingOrSelfPermission(
6694 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6695 != PackageManager.PERMISSION_GRANTED) {
6696 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6697 < Build.VERSION_CODES.FROYO) {
6698 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6699 + Binder.getCallingUid());
6700 return;
6701 }
6702 mContext.enforceCallingOrSelfPermission(
6703 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6704 }
6705
Satish Sampath8dbe6122009-06-02 23:35:54 +01006706 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6707 String action = filter.getAction(0);
6708 String category = filter.getCategory(0);
6709 while (it.hasNext()) {
6710 PreferredActivity pa = it.next();
6711 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6712 it.remove();
6713 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6714 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6715 }
6716 }
6717 addPreferredActivity(filter, match, set, activity);
6718 }
6719 }
6720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006721 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006723 int uid = Binder.getCallingUid();
6724 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006725 if (pkg == null || pkg.applicationInfo.uid != uid) {
6726 if (mContext.checkCallingOrSelfPermission(
6727 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6728 != PackageManager.PERMISSION_GRANTED) {
6729 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6730 < Build.VERSION_CODES.FROYO) {
6731 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6732 + Binder.getCallingUid());
6733 return;
6734 }
6735 mContext.enforceCallingOrSelfPermission(
6736 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6737 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006738 }
6739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006741 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006742 }
6743 }
6744 }
6745
6746 boolean clearPackagePreferredActivitiesLP(String packageName) {
6747 boolean changed = false;
6748 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6749 while (it.hasNext()) {
6750 PreferredActivity pa = it.next();
6751 if (pa.mActivity.getPackageName().equals(packageName)) {
6752 it.remove();
6753 changed = true;
6754 }
6755 }
6756 return changed;
6757 }
6758
6759 public int getPreferredActivities(List<IntentFilter> outFilters,
6760 List<ComponentName> outActivities, String packageName) {
6761
6762 int num = 0;
6763 synchronized (mPackages) {
6764 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6765 while (it.hasNext()) {
6766 PreferredActivity pa = it.next();
6767 if (packageName == null
6768 || pa.mActivity.getPackageName().equals(packageName)) {
6769 if (outFilters != null) {
6770 outFilters.add(new IntentFilter(pa));
6771 }
6772 if (outActivities != null) {
6773 outActivities.add(pa.mActivity);
6774 }
6775 }
6776 }
6777 }
6778
6779 return num;
6780 }
6781
6782 public void setApplicationEnabledSetting(String appPackageName,
6783 int newState, int flags) {
6784 setEnabledSetting(appPackageName, null, newState, flags);
6785 }
6786
6787 public void setComponentEnabledSetting(ComponentName componentName,
6788 int newState, int flags) {
6789 setEnabledSetting(componentName.getPackageName(),
6790 componentName.getClassName(), newState, flags);
6791 }
6792
6793 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006794 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006795 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6796 || newState == COMPONENT_ENABLED_STATE_ENABLED
6797 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6798 throw new IllegalArgumentException("Invalid new component state: "
6799 + newState);
6800 }
6801 PackageSetting pkgSetting;
6802 final int uid = Binder.getCallingUid();
6803 final int permission = mContext.checkCallingPermission(
6804 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6805 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006806 boolean sendNow = false;
6807 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006808 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006810 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006812 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006814 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006816 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006817 }
6818 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006819 "Unknown component: " + packageName
6820 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006821 }
6822 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6823 throw new SecurityException(
6824 "Permission Denial: attempt to change component state from pid="
6825 + Binder.getCallingPid()
6826 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6827 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006828 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006829 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006830 if (pkgSetting.enabled == newState) {
6831 // Nothing to do
6832 return;
6833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006834 pkgSetting.enabled = newState;
6835 } else {
6836 // We're dealing with a component level state change
6837 switch (newState) {
6838 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006839 if (!pkgSetting.enableComponentLP(className)) {
6840 return;
6841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006842 break;
6843 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006844 if (!pkgSetting.disableComponentLP(className)) {
6845 return;
6846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 break;
6848 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006849 if (!pkgSetting.restoreComponentLP(className)) {
6850 return;
6851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006852 break;
6853 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006854 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006855 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006856 }
6857 }
6858 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006859 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006860 components = mPendingBroadcasts.get(packageName);
6861 boolean newPackage = components == null;
6862 if (newPackage) {
6863 components = new ArrayList<String>();
6864 }
6865 if (!components.contains(componentName)) {
6866 components.add(componentName);
6867 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006868 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6869 sendNow = true;
6870 // Purge entry from pending broadcast list if another one exists already
6871 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006872 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006873 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006874 if (newPackage) {
6875 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006876 }
6877 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6878 // Schedule a message
6879 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6880 }
6881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006882 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006884 long callingId = Binder.clearCallingIdentity();
6885 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006886 if (sendNow) {
6887 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006888 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006890 } finally {
6891 Binder.restoreCallingIdentity(callingId);
6892 }
6893 }
6894
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006895 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006896 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6897 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6898 + " components=" + componentNames);
6899 Bundle extras = new Bundle(4);
6900 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6901 String nameList[] = new String[componentNames.size()];
6902 componentNames.toArray(nameList);
6903 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006904 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6905 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006906 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006907 }
6908
Jacek Surazski65e13172009-04-28 15:26:38 +02006909 public String getInstallerPackageName(String packageName) {
6910 synchronized (mPackages) {
6911 PackageSetting pkg = mSettings.mPackages.get(packageName);
6912 if (pkg == null) {
6913 throw new IllegalArgumentException("Unknown package: " + packageName);
6914 }
6915 return pkg.installerPackageName;
6916 }
6917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006919 public int getApplicationEnabledSetting(String appPackageName) {
6920 synchronized (mPackages) {
6921 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6922 if (pkg == null) {
6923 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6924 }
6925 return pkg.enabled;
6926 }
6927 }
6928
6929 public int getComponentEnabledSetting(ComponentName componentName) {
6930 synchronized (mPackages) {
6931 final String packageNameStr = componentName.getPackageName();
6932 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6933 if (pkg == null) {
6934 throw new IllegalArgumentException("Unknown component: " + componentName);
6935 }
6936 final String classNameStr = componentName.getClassName();
6937 return pkg.currentEnabledStateLP(classNameStr);
6938 }
6939 }
6940
6941 public void enterSafeMode() {
6942 if (!mSystemReady) {
6943 mSafeMode = true;
6944 }
6945 }
6946
6947 public void systemReady() {
6948 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006949
6950 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006951 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006952 mContext.getContentResolver(),
6953 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006954 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006955 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006956 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958 }
6959
6960 public boolean isSafeMode() {
6961 return mSafeMode;
6962 }
6963
6964 public boolean hasSystemUidErrors() {
6965 return mHasSystemUidErrors;
6966 }
6967
6968 static String arrayToString(int[] array) {
6969 StringBuffer buf = new StringBuffer(128);
6970 buf.append('[');
6971 if (array != null) {
6972 for (int i=0; i<array.length; i++) {
6973 if (i > 0) buf.append(", ");
6974 buf.append(array[i]);
6975 }
6976 }
6977 buf.append(']');
6978 return buf.toString();
6979 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006981 @Override
6982 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6983 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6984 != PackageManager.PERMISSION_GRANTED) {
6985 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6986 + Binder.getCallingPid()
6987 + ", uid=" + Binder.getCallingUid()
6988 + " without permission "
6989 + android.Manifest.permission.DUMP);
6990 return;
6991 }
6992
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006993 String packageName = null;
6994
6995 int opti = 0;
6996 while (opti < args.length) {
6997 String opt = args[opti];
6998 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6999 break;
7000 }
7001 opti++;
7002 if ("-a".equals(opt)) {
7003 // Right now we only know how to print all.
7004 } else if ("-h".equals(opt)) {
7005 pw.println("Package manager dump options:");
7006 pw.println(" [-h] [cmd] ...");
7007 pw.println(" cmd may be one of:");
7008 pw.println(" [package.name]: info about given package");
7009 return;
7010 } else {
7011 pw.println("Unknown argument: " + opt + "; use -h for help");
7012 }
7013 }
7014
7015 // Is the caller requesting to dump a particular piece of data?
7016 if (opti < args.length) {
7017 String cmd = args[opti];
7018 opti++;
7019 // Is this a package name?
7020 if ("android".equals(cmd) || cmd.contains(".")) {
7021 packageName = cmd;
7022 }
7023 }
7024
7025 boolean printedTitle = false;
7026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007028 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
7029 printedTitle = true;
7030 }
7031 if (mReceivers.dump(pw, printedTitle
7032 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7033 " ", packageName)) {
7034 printedTitle = true;
7035 }
7036 if (mServices.dump(pw, printedTitle
7037 ? "\nService Resolver Table:" : "Service Resolver Table:",
7038 " ", packageName)) {
7039 printedTitle = true;
7040 }
7041 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7042 ? "\nPreferred Activities:" : "Preferred Activities:",
7043 " ", packageName)) {
7044 printedTitle = true;
7045 }
7046 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007047 {
7048 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007049 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7050 continue;
7051 }
7052 if (!printedSomething) {
7053 if (printedTitle) pw.println(" ");
7054 pw.println("Permissions:");
7055 printedSomething = true;
7056 printedTitle = true;
7057 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007058 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7059 pw.print(Integer.toHexString(System.identityHashCode(p)));
7060 pw.println("):");
7061 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7062 pw.print(" uid="); pw.print(p.uid);
7063 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007064 pw.print(" type="); pw.print(p.type);
7065 pw.print(" prot="); pw.println(p.protectionLevel);
7066 if (p.packageSetting != null) {
7067 pw.print(" packageSetting="); pw.println(p.packageSetting);
7068 }
7069 if (p.perm != null) {
7070 pw.print(" perm="); pw.println(p.perm);
7071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007072 }
7073 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007074 printedSomething = false;
7075 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007076 {
7077 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007078 if (packageName != null && !packageName.equals(ps.realName)
7079 && !packageName.equals(ps.name)) {
7080 continue;
7081 }
7082 if (!printedSomething) {
7083 if (printedTitle) pw.println(" ");
7084 pw.println("Packages:");
7085 printedSomething = true;
7086 printedTitle = true;
7087 }
7088 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007089 pw.print(" Package [");
7090 pw.print(ps.realName != null ? ps.realName : ps.name);
7091 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007092 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7093 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007094 if (ps.realName != null) {
7095 pw.print(" compat name="); pw.println(ps.name);
7096 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007097 pw.print(" userId="); pw.print(ps.userId);
7098 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7099 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7100 pw.print(" pkg="); pw.println(ps.pkg);
7101 pw.print(" codePath="); pw.println(ps.codePathString);
7102 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007103 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007104 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007105 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007106 pw.print(" supportsScreens=[");
7107 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007108 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007109 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007110 if (!first) pw.print(", ");
7111 first = false;
7112 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007114 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007115 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007116 if (!first) pw.print(", ");
7117 first = false;
7118 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007119 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007120 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007121 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007122 if (!first) pw.print(", ");
7123 first = false;
7124 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007125 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007126 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007127 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007128 if (!first) pw.print(", ");
7129 first = false;
7130 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007131 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007132 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007133 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7134 if (!first) pw.print(", ");
7135 first = false;
7136 pw.print("anyDensity");
7137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007138 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007139 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007140 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7141 pw.print(" signatures="); pw.println(ps.signatures);
7142 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007143 pw.print(" haveGids="); pw.println(ps.haveGids);
7144 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007145 pw.print(" installStatus="); pw.print(ps.installStatus);
7146 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007147 if (ps.disabledComponents.size() > 0) {
7148 pw.println(" disabledComponents:");
7149 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007150 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007151 }
7152 }
7153 if (ps.enabledComponents.size() > 0) {
7154 pw.println(" enabledComponents:");
7155 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007156 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007157 }
7158 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007159 if (ps.grantedPermissions.size() > 0) {
7160 pw.println(" grantedPermissions:");
7161 for (String s : ps.grantedPermissions) {
7162 pw.print(" "); pw.println(s);
7163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007165 }
7166 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007167 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007168 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007169 for (HashMap.Entry<String, String> e
7170 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007171 if (packageName != null && !packageName.equals(e.getKey())
7172 && !packageName.equals(e.getValue())) {
7173 continue;
7174 }
7175 if (!printedSomething) {
7176 if (printedTitle) pw.println(" ");
7177 pw.println("Renamed packages:");
7178 printedSomething = true;
7179 printedTitle = true;
7180 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007181 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7182 pw.println(e.getValue());
7183 }
7184 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007185 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007186 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007187 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007188 if (packageName != null && !packageName.equals(ps.realName)
7189 && !packageName.equals(ps.name)) {
7190 continue;
7191 }
7192 if (!printedSomething) {
7193 if (printedTitle) pw.println(" ");
7194 pw.println("Hidden system packages:");
7195 printedSomething = true;
7196 printedTitle = true;
7197 }
7198 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007199 pw.print(ps.realName != null ? ps.realName : ps.name);
7200 pw.print("] (");
7201 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7202 pw.println("):");
7203 if (ps.realName != null) {
7204 pw.print(" compat name="); pw.println(ps.name);
7205 }
7206 pw.print(" userId="); pw.println(ps.userId);
7207 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7208 pw.print(" codePath="); pw.println(ps.codePathString);
7209 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7210 }
7211 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007212 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007213 {
7214 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007215 if (packageName != null && su != packageSharedUser) {
7216 continue;
7217 }
7218 if (!printedSomething) {
7219 if (printedTitle) pw.println(" ");
7220 pw.println("Shared users:");
7221 printedSomething = true;
7222 printedTitle = true;
7223 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007224 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7225 pw.print(Integer.toHexString(System.identityHashCode(su)));
7226 pw.println("):");
7227 pw.print(" userId="); pw.print(su.userId);
7228 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007229 pw.println(" grantedPermissions:");
7230 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007231 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007233 }
7234 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007235
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007236 if (packageName == null) {
7237 if (printedTitle) pw.println(" ");
7238 printedTitle = true;
7239 pw.println("Settings parse messages:");
7240 pw.println(mSettings.mReadMessages.toString());
7241
7242 pw.println(" ");
7243 pw.println("Package warning messages:");
7244 File fname = getSettingsProblemFile();
7245 FileInputStream in;
7246 try {
7247 in = new FileInputStream(fname);
7248 int avail = in.available();
7249 byte[] data = new byte[avail];
7250 in.read(data);
7251 pw.println(new String(data));
7252 } catch (FileNotFoundException e) {
7253 } catch (IOException e) {
7254 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007256 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007257
7258 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007259 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007260 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007261 if (packageName != null && !packageName.equals(p.info.packageName)) {
7262 continue;
7263 }
7264 if (!printedSomething) {
7265 if (printedTitle) pw.println(" ");
7266 pw.println("Registered ContentProviders:");
7267 printedSomething = true;
7268 printedTitle = true;
7269 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007270 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007271 pw.println(p.toString());
7272 }
7273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007274 }
7275
7276 static final class BasePermission {
7277 final static int TYPE_NORMAL = 0;
7278 final static int TYPE_BUILTIN = 1;
7279 final static int TYPE_DYNAMIC = 2;
7280
7281 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007282 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007283 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007285 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007286 PackageParser.Permission perm;
7287 PermissionInfo pendingInfo;
7288 int uid;
7289 int[] gids;
7290
7291 BasePermission(String _name, String _sourcePackage, int _type) {
7292 name = _name;
7293 sourcePackage = _sourcePackage;
7294 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007295 // Default to most conservative protection level.
7296 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7297 }
7298
7299 public String toString() {
7300 return "BasePermission{"
7301 + Integer.toHexString(System.identityHashCode(this))
7302 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007303 }
7304 }
7305
7306 static class PackageSignatures {
7307 private Signature[] mSignatures;
7308
7309 PackageSignatures(Signature[] sigs) {
7310 assignSignatures(sigs);
7311 }
7312
7313 PackageSignatures() {
7314 }
7315
7316 void writeXml(XmlSerializer serializer, String tagName,
7317 ArrayList<Signature> pastSignatures) throws IOException {
7318 if (mSignatures == null) {
7319 return;
7320 }
7321 serializer.startTag(null, tagName);
7322 serializer.attribute(null, "count",
7323 Integer.toString(mSignatures.length));
7324 for (int i=0; i<mSignatures.length; i++) {
7325 serializer.startTag(null, "cert");
7326 final Signature sig = mSignatures[i];
7327 final int sigHash = sig.hashCode();
7328 final int numPast = pastSignatures.size();
7329 int j;
7330 for (j=0; j<numPast; j++) {
7331 Signature pastSig = pastSignatures.get(j);
7332 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7333 serializer.attribute(null, "index", Integer.toString(j));
7334 break;
7335 }
7336 }
7337 if (j >= numPast) {
7338 pastSignatures.add(sig);
7339 serializer.attribute(null, "index", Integer.toString(numPast));
7340 serializer.attribute(null, "key", sig.toCharsString());
7341 }
7342 serializer.endTag(null, "cert");
7343 }
7344 serializer.endTag(null, tagName);
7345 }
7346
7347 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7348 throws IOException, XmlPullParserException {
7349 String countStr = parser.getAttributeValue(null, "count");
7350 if (countStr == null) {
7351 reportSettingsProblem(Log.WARN,
7352 "Error in package manager settings: <signatures> has"
7353 + " no count at " + parser.getPositionDescription());
7354 XmlUtils.skipCurrentTag(parser);
7355 }
7356 final int count = Integer.parseInt(countStr);
7357 mSignatures = new Signature[count];
7358 int pos = 0;
7359
7360 int outerDepth = parser.getDepth();
7361 int type;
7362 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7363 && (type != XmlPullParser.END_TAG
7364 || parser.getDepth() > outerDepth)) {
7365 if (type == XmlPullParser.END_TAG
7366 || type == XmlPullParser.TEXT) {
7367 continue;
7368 }
7369
7370 String tagName = parser.getName();
7371 if (tagName.equals("cert")) {
7372 if (pos < count) {
7373 String index = parser.getAttributeValue(null, "index");
7374 if (index != null) {
7375 try {
7376 int idx = Integer.parseInt(index);
7377 String key = parser.getAttributeValue(null, "key");
7378 if (key == null) {
7379 if (idx >= 0 && idx < pastSignatures.size()) {
7380 Signature sig = pastSignatures.get(idx);
7381 if (sig != null) {
7382 mSignatures[pos] = pastSignatures.get(idx);
7383 pos++;
7384 } else {
7385 reportSettingsProblem(Log.WARN,
7386 "Error in package manager settings: <cert> "
7387 + "index " + index + " is not defined at "
7388 + parser.getPositionDescription());
7389 }
7390 } else {
7391 reportSettingsProblem(Log.WARN,
7392 "Error in package manager settings: <cert> "
7393 + "index " + index + " is out of bounds at "
7394 + parser.getPositionDescription());
7395 }
7396 } else {
7397 while (pastSignatures.size() <= idx) {
7398 pastSignatures.add(null);
7399 }
7400 Signature sig = new Signature(key);
7401 pastSignatures.set(idx, sig);
7402 mSignatures[pos] = sig;
7403 pos++;
7404 }
7405 } catch (NumberFormatException e) {
7406 reportSettingsProblem(Log.WARN,
7407 "Error in package manager settings: <cert> "
7408 + "index " + index + " is not a number at "
7409 + parser.getPositionDescription());
7410 }
7411 } else {
7412 reportSettingsProblem(Log.WARN,
7413 "Error in package manager settings: <cert> has"
7414 + " no index at " + parser.getPositionDescription());
7415 }
7416 } else {
7417 reportSettingsProblem(Log.WARN,
7418 "Error in package manager settings: too "
7419 + "many <cert> tags, expected " + count
7420 + " at " + parser.getPositionDescription());
7421 }
7422 } else {
7423 reportSettingsProblem(Log.WARN,
7424 "Unknown element under <cert>: "
7425 + parser.getName());
7426 }
7427 XmlUtils.skipCurrentTag(parser);
7428 }
7429
7430 if (pos < count) {
7431 // Should never happen -- there is an error in the written
7432 // settings -- but if it does we don't want to generate
7433 // a bad array.
7434 Signature[] newSigs = new Signature[pos];
7435 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7436 mSignatures = newSigs;
7437 }
7438 }
7439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007440 private void assignSignatures(Signature[] sigs) {
7441 if (sigs == null) {
7442 mSignatures = null;
7443 return;
7444 }
7445 mSignatures = new Signature[sigs.length];
7446 for (int i=0; i<sigs.length; i++) {
7447 mSignatures[i] = sigs[i];
7448 }
7449 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007451 @Override
7452 public String toString() {
7453 StringBuffer buf = new StringBuffer(128);
7454 buf.append("PackageSignatures{");
7455 buf.append(Integer.toHexString(System.identityHashCode(this)));
7456 buf.append(" [");
7457 if (mSignatures != null) {
7458 for (int i=0; i<mSignatures.length; i++) {
7459 if (i > 0) buf.append(", ");
7460 buf.append(Integer.toHexString(
7461 System.identityHashCode(mSignatures[i])));
7462 }
7463 }
7464 buf.append("]}");
7465 return buf.toString();
7466 }
7467 }
7468
7469 static class PreferredActivity extends IntentFilter {
7470 final int mMatch;
7471 final String[] mSetPackages;
7472 final String[] mSetClasses;
7473 final String[] mSetComponents;
7474 final ComponentName mActivity;
7475 final String mShortActivity;
7476 String mParseError;
7477
7478 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7479 ComponentName activity) {
7480 super(filter);
7481 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7482 mActivity = activity;
7483 mShortActivity = activity.flattenToShortString();
7484 mParseError = null;
7485 if (set != null) {
7486 final int N = set.length;
7487 String[] myPackages = new String[N];
7488 String[] myClasses = new String[N];
7489 String[] myComponents = new String[N];
7490 for (int i=0; i<N; i++) {
7491 ComponentName cn = set[i];
7492 if (cn == null) {
7493 mSetPackages = null;
7494 mSetClasses = null;
7495 mSetComponents = null;
7496 return;
7497 }
7498 myPackages[i] = cn.getPackageName().intern();
7499 myClasses[i] = cn.getClassName().intern();
7500 myComponents[i] = cn.flattenToShortString().intern();
7501 }
7502 mSetPackages = myPackages;
7503 mSetClasses = myClasses;
7504 mSetComponents = myComponents;
7505 } else {
7506 mSetPackages = null;
7507 mSetClasses = null;
7508 mSetComponents = null;
7509 }
7510 }
7511
7512 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7513 IOException {
7514 mShortActivity = parser.getAttributeValue(null, "name");
7515 mActivity = ComponentName.unflattenFromString(mShortActivity);
7516 if (mActivity == null) {
7517 mParseError = "Bad activity name " + mShortActivity;
7518 }
7519 String matchStr = parser.getAttributeValue(null, "match");
7520 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7521 String setCountStr = parser.getAttributeValue(null, "set");
7522 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7523
7524 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7525 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7526 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7527
7528 int setPos = 0;
7529
7530 int outerDepth = parser.getDepth();
7531 int type;
7532 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7533 && (type != XmlPullParser.END_TAG
7534 || parser.getDepth() > outerDepth)) {
7535 if (type == XmlPullParser.END_TAG
7536 || type == XmlPullParser.TEXT) {
7537 continue;
7538 }
7539
7540 String tagName = parser.getName();
7541 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7542 // + parser.getDepth() + " tag=" + tagName);
7543 if (tagName.equals("set")) {
7544 String name = parser.getAttributeValue(null, "name");
7545 if (name == null) {
7546 if (mParseError == null) {
7547 mParseError = "No name in set tag in preferred activity "
7548 + mShortActivity;
7549 }
7550 } else if (setPos >= setCount) {
7551 if (mParseError == null) {
7552 mParseError = "Too many set tags in preferred activity "
7553 + mShortActivity;
7554 }
7555 } else {
7556 ComponentName cn = ComponentName.unflattenFromString(name);
7557 if (cn == null) {
7558 if (mParseError == null) {
7559 mParseError = "Bad set name " + name + " in preferred activity "
7560 + mShortActivity;
7561 }
7562 } else {
7563 myPackages[setPos] = cn.getPackageName();
7564 myClasses[setPos] = cn.getClassName();
7565 myComponents[setPos] = name;
7566 setPos++;
7567 }
7568 }
7569 XmlUtils.skipCurrentTag(parser);
7570 } else if (tagName.equals("filter")) {
7571 //Log.i(TAG, "Starting to parse filter...");
7572 readFromXml(parser);
7573 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7574 // + parser.getDepth() + " tag=" + parser.getName());
7575 } else {
7576 reportSettingsProblem(Log.WARN,
7577 "Unknown element under <preferred-activities>: "
7578 + parser.getName());
7579 XmlUtils.skipCurrentTag(parser);
7580 }
7581 }
7582
7583 if (setPos != setCount) {
7584 if (mParseError == null) {
7585 mParseError = "Not enough set tags (expected " + setCount
7586 + " but found " + setPos + ") in " + mShortActivity;
7587 }
7588 }
7589
7590 mSetPackages = myPackages;
7591 mSetClasses = myClasses;
7592 mSetComponents = myComponents;
7593 }
7594
7595 public void writeToXml(XmlSerializer serializer) throws IOException {
7596 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7597 serializer.attribute(null, "name", mShortActivity);
7598 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7599 serializer.attribute(null, "set", Integer.toString(NS));
7600 for (int s=0; s<NS; s++) {
7601 serializer.startTag(null, "set");
7602 serializer.attribute(null, "name", mSetComponents[s]);
7603 serializer.endTag(null, "set");
7604 }
7605 serializer.startTag(null, "filter");
7606 super.writeToXml(serializer);
7607 serializer.endTag(null, "filter");
7608 }
7609
7610 boolean sameSet(List<ResolveInfo> query, int priority) {
7611 if (mSetPackages == null) return false;
7612 final int NQ = query.size();
7613 final int NS = mSetPackages.length;
7614 int numMatch = 0;
7615 for (int i=0; i<NQ; i++) {
7616 ResolveInfo ri = query.get(i);
7617 if (ri.priority != priority) continue;
7618 ActivityInfo ai = ri.activityInfo;
7619 boolean good = false;
7620 for (int j=0; j<NS; j++) {
7621 if (mSetPackages[j].equals(ai.packageName)
7622 && mSetClasses[j].equals(ai.name)) {
7623 numMatch++;
7624 good = true;
7625 break;
7626 }
7627 }
7628 if (!good) return false;
7629 }
7630 return numMatch == NS;
7631 }
7632 }
7633
7634 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007635 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007637 HashSet<String> grantedPermissions = new HashSet<String>();
7638 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007640 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007641 setFlags(pkgFlags);
7642 }
7643
7644 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007645 this.pkgFlags = pkgFlags & (
7646 ApplicationInfo.FLAG_SYSTEM |
7647 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007648 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007649 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007650 }
7651 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007653 /**
7654 * Settings base class for pending and resolved classes.
7655 */
7656 static class PackageSettingBase extends GrantedPermissions {
7657 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007658 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007659 File codePath;
7660 String codePathString;
7661 File resourcePath;
7662 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007663 private long timeStamp;
7664 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007665 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007666
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007667 boolean uidError;
7668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007669 PackageSignatures signatures = new PackageSignatures();
7670
7671 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007672 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007674 /* Explicitly disabled components */
7675 HashSet<String> disabledComponents = new HashSet<String>(0);
7676 /* Explicitly enabled components */
7677 HashSet<String> enabledComponents = new HashSet<String>(0);
7678 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7679 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007680
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007681 PackageSettingBase origPackage;
7682
Jacek Surazski65e13172009-04-28 15:26:38 +02007683 /* package name of the app that installed this package */
7684 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007685
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007686 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007687 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 super(pkgFlags);
7689 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007690 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007691 init(codePath, resourcePath, pVersionCode);
7692 }
7693
7694 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007695 this.codePath = codePath;
7696 this.codePathString = codePath.toString();
7697 this.resourcePath = resourcePath;
7698 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007699 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007700 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007701
Jacek Surazski65e13172009-04-28 15:26:38 +02007702 public void setInstallerPackageName(String packageName) {
7703 installerPackageName = packageName;
7704 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007705
Jacek Surazski65e13172009-04-28 15:26:38 +02007706 String getInstallerPackageName() {
7707 return installerPackageName;
7708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710 public void setInstallStatus(int newStatus) {
7711 installStatus = newStatus;
7712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 public int getInstallStatus() {
7715 return installStatus;
7716 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 public void setTimeStamp(long newStamp) {
7719 if (newStamp != timeStamp) {
7720 timeStamp = newStamp;
7721 timeStampString = Long.toString(newStamp);
7722 }
7723 }
7724
7725 public void setTimeStamp(long newStamp, String newStampStr) {
7726 timeStamp = newStamp;
7727 timeStampString = newStampStr;
7728 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 public long getTimeStamp() {
7731 return timeStamp;
7732 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007734 public String getTimeStampStr() {
7735 return timeStampString;
7736 }
7737
7738 public void copyFrom(PackageSettingBase base) {
7739 grantedPermissions = base.grantedPermissions;
7740 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007742 timeStamp = base.timeStamp;
7743 timeStampString = base.timeStampString;
7744 signatures = base.signatures;
7745 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007746 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747 disabledComponents = base.disabledComponents;
7748 enabledComponents = base.enabledComponents;
7749 enabled = base.enabled;
7750 installStatus = base.installStatus;
7751 }
7752
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007753 boolean enableComponentLP(String componentClassName) {
7754 boolean changed = disabledComponents.remove(componentClassName);
7755 changed |= enabledComponents.add(componentClassName);
7756 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007757 }
7758
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007759 boolean disableComponentLP(String componentClassName) {
7760 boolean changed = enabledComponents.remove(componentClassName);
7761 changed |= disabledComponents.add(componentClassName);
7762 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 }
7764
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007765 boolean restoreComponentLP(String componentClassName) {
7766 boolean changed = enabledComponents.remove(componentClassName);
7767 changed |= disabledComponents.remove(componentClassName);
7768 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007769 }
7770
7771 int currentEnabledStateLP(String componentName) {
7772 if (enabledComponents.contains(componentName)) {
7773 return COMPONENT_ENABLED_STATE_ENABLED;
7774 } else if (disabledComponents.contains(componentName)) {
7775 return COMPONENT_ENABLED_STATE_DISABLED;
7776 } else {
7777 return COMPONENT_ENABLED_STATE_DEFAULT;
7778 }
7779 }
7780 }
7781
7782 /**
7783 * Settings data for a particular package we know about.
7784 */
7785 static final class PackageSetting extends PackageSettingBase {
7786 int userId;
7787 PackageParser.Package pkg;
7788 SharedUserSetting sharedUser;
7789
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007790 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007791 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007792 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 @Override
7796 public String toString() {
7797 return "PackageSetting{"
7798 + Integer.toHexString(System.identityHashCode(this))
7799 + " " + name + "/" + userId + "}";
7800 }
7801 }
7802
7803 /**
7804 * Settings data for a particular shared user ID we know about.
7805 */
7806 static final class SharedUserSetting extends GrantedPermissions {
7807 final String name;
7808 int userId;
7809 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7810 final PackageSignatures signatures = new PackageSignatures();
7811
7812 SharedUserSetting(String _name, int _pkgFlags) {
7813 super(_pkgFlags);
7814 name = _name;
7815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 @Override
7818 public String toString() {
7819 return "SharedUserSetting{"
7820 + Integer.toHexString(System.identityHashCode(this))
7821 + " " + name + "/" + userId + "}";
7822 }
7823 }
7824
7825 /**
7826 * Holds information about dynamic settings.
7827 */
7828 private static final class Settings {
7829 private final File mSettingsFilename;
7830 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007831 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007832 private final HashMap<String, PackageSetting> mPackages =
7833 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007834 // List of replaced system applications
7835 final HashMap<String, PackageSetting> mDisabledSysPackages =
7836 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007837
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007838 // These are the last platform API version we were using for
7839 // the apps installed on internal and external storage. It is
7840 // used to grant newer permissions one time during a system upgrade.
7841 int mInternalSdkPlatform;
7842 int mExternalSdkPlatform;
7843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844 // The user's preferred activities associated with particular intent
7845 // filters.
7846 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7847 new IntentResolver<PreferredActivity, PreferredActivity>() {
7848 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007849 protected String packageForFilter(PreferredActivity filter) {
7850 return filter.mActivity.getPackageName();
7851 }
7852 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007853 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007854 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007855 out.print(prefix); out.print(
7856 Integer.toHexString(System.identityHashCode(filter)));
7857 out.print(' ');
7858 out.print(filter.mActivity.flattenToShortString());
7859 out.print(" match=0x");
7860 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007862 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007863 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007864 out.print(prefix); out.print(" ");
7865 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007866 }
7867 }
7868 }
7869 };
7870 private final HashMap<String, SharedUserSetting> mSharedUsers =
7871 new HashMap<String, SharedUserSetting>();
7872 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7873 private final SparseArray<Object> mOtherUserIds =
7874 new SparseArray<Object>();
7875
7876 // For reading/writing settings file.
7877 private final ArrayList<Signature> mPastSignatures =
7878 new ArrayList<Signature>();
7879
7880 // Mapping from permission names to info about them.
7881 final HashMap<String, BasePermission> mPermissions =
7882 new HashMap<String, BasePermission>();
7883
7884 // Mapping from permission tree names to info about them.
7885 final HashMap<String, BasePermission> mPermissionTrees =
7886 new HashMap<String, BasePermission>();
7887
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007888 // Packages that have been uninstalled and still need their external
7889 // storage data deleted.
7890 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7891
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007892 // Packages that have been renamed since they were first installed.
7893 // Keys are the new names of the packages, values are the original
7894 // names. The packages appear everwhere else under their original
7895 // names.
7896 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007898 private final StringBuilder mReadMessages = new StringBuilder();
7899
7900 private static final class PendingPackage extends PackageSettingBase {
7901 final int sharedId;
7902
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007903 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007904 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007905 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 this.sharedId = sharedId;
7907 }
7908 }
7909 private final ArrayList<PendingPackage> mPendingPackages
7910 = new ArrayList<PendingPackage>();
7911
7912 Settings() {
7913 File dataDir = Environment.getDataDirectory();
7914 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007915 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7916 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007917 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007918 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919 FileUtils.setPermissions(systemDir.toString(),
7920 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7921 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7922 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007923 FileUtils.setPermissions(systemSecureDir.toString(),
7924 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7925 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7926 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007927 mSettingsFilename = new File(systemDir, "packages.xml");
7928 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007929 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007930 }
7931
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007932 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007933 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007934 int pkgFlags, boolean create, boolean add) {
7935 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007936 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007937 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007938 return p;
7939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007940
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007941 PackageSetting peekPackageLP(String name) {
7942 return mPackages.get(name);
7943 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007944 PackageSetting p = mPackages.get(name);
7945 if (p != null && p.codePath.getPath().equals(codePath)) {
7946 return p;
7947 }
7948 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007949 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007950 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007952 void setInstallStatus(String pkgName, int status) {
7953 PackageSetting p = mPackages.get(pkgName);
7954 if(p != null) {
7955 if(p.getInstallStatus() != status) {
7956 p.setInstallStatus(status);
7957 }
7958 }
7959 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007960
Jacek Surazski65e13172009-04-28 15:26:38 +02007961 void setInstallerPackageName(String pkgName,
7962 String installerPkgName) {
7963 PackageSetting p = mPackages.get(pkgName);
7964 if(p != null) {
7965 p.setInstallerPackageName(installerPkgName);
7966 }
7967 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007968
Jacek Surazski65e13172009-04-28 15:26:38 +02007969 String getInstallerPackageName(String pkgName) {
7970 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007971 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007972 }
7973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 int getInstallStatus(String pkgName) {
7975 PackageSetting p = mPackages.get(pkgName);
7976 if(p != null) {
7977 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 return -1;
7980 }
7981
7982 SharedUserSetting getSharedUserLP(String name,
7983 int pkgFlags, boolean create) {
7984 SharedUserSetting s = mSharedUsers.get(name);
7985 if (s == null) {
7986 if (!create) {
7987 return null;
7988 }
7989 s = new SharedUserSetting(name, pkgFlags);
7990 if (MULTIPLE_APPLICATION_UIDS) {
7991 s.userId = newUserIdLP(s);
7992 } else {
7993 s.userId = FIRST_APPLICATION_UID;
7994 }
7995 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7996 // < 0 means we couldn't assign a userid; fall out and return
7997 // s, which is currently null
7998 if (s.userId >= 0) {
7999 mSharedUsers.put(name, s);
8000 }
8001 }
8002
8003 return s;
8004 }
8005
8006 int disableSystemPackageLP(String name) {
8007 PackageSetting p = mPackages.get(name);
8008 if(p == null) {
8009 Log.w(TAG, "Package:"+name+" is not an installed package");
8010 return -1;
8011 }
8012 PackageSetting dp = mDisabledSysPackages.get(name);
8013 // always make sure the system package code and resource paths dont change
8014 if(dp == null) {
8015 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8016 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8017 }
8018 mDisabledSysPackages.put(name, p);
8019 }
8020 return removePackageLP(name);
8021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008023 PackageSetting enableSystemPackageLP(String name) {
8024 PackageSetting p = mDisabledSysPackages.get(name);
8025 if(p == null) {
8026 Log.w(TAG, "Package:"+name+" is not disabled");
8027 return null;
8028 }
8029 // Reset flag in ApplicationInfo object
8030 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8031 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8032 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008033 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008034 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 mDisabledSysPackages.remove(name);
8036 return ret;
8037 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008038
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008039 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008040 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008041 PackageSetting p = mPackages.get(name);
8042 if (p != null) {
8043 if (p.userId == uid) {
8044 return p;
8045 }
8046 reportSettingsProblem(Log.ERROR,
8047 "Adding duplicate package, keeping first: " + name);
8048 return null;
8049 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008050 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008051 p.userId = uid;
8052 if (addUserIdLP(uid, p, name)) {
8053 mPackages.put(name, p);
8054 return p;
8055 }
8056 return null;
8057 }
8058
8059 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8060 SharedUserSetting s = mSharedUsers.get(name);
8061 if (s != null) {
8062 if (s.userId == uid) {
8063 return s;
8064 }
8065 reportSettingsProblem(Log.ERROR,
8066 "Adding duplicate shared user, keeping first: " + name);
8067 return null;
8068 }
8069 s = new SharedUserSetting(name, pkgFlags);
8070 s.userId = uid;
8071 if (addUserIdLP(uid, s, name)) {
8072 mSharedUsers.put(name, s);
8073 return s;
8074 }
8075 return null;
8076 }
8077
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008078 // Transfer ownership of permissions from one package to another.
8079 private void transferPermissions(String origPkg, String newPkg) {
8080 // Transfer ownership of permissions to the new package.
8081 for (int i=0; i<2; i++) {
8082 HashMap<String, BasePermission> permissions =
8083 i == 0 ? mPermissionTrees : mPermissions;
8084 for (BasePermission bp : permissions.values()) {
8085 if (origPkg.equals(bp.sourcePackage)) {
8086 if (DEBUG_UPGRADE) Log.v(TAG,
8087 "Moving permission " + bp.name
8088 + " from pkg " + bp.sourcePackage
8089 + " to " + newPkg);
8090 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008091 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008092 bp.perm = null;
8093 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008094 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008095 }
8096 bp.uid = 0;
8097 bp.gids = null;
8098 }
8099 }
8100 }
8101 }
8102
8103 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008104 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008105 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008106 PackageSetting p = mPackages.get(name);
8107 if (p != null) {
8108 if (!p.codePath.equals(codePath)) {
8109 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008110 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008111 // This is an updated system app with versions in both system
8112 // and data partition. Just let the most recent version
8113 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008114 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008115 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008116 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008117 // Just a change in the code path is not an issue, but
8118 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008119 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008120 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008121 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008122 }
8123 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008124 reportSettingsProblem(Log.WARN,
8125 "Package " + name + " shared user changed from "
8126 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8127 + " to "
8128 + (sharedUser != null ? sharedUser.name : "<nothing>")
8129 + "; replacing with new");
8130 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008131 } else {
8132 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8133 // If what we are scanning is a system package, then
8134 // make it so, regardless of whether it was previously
8135 // installed only in the data partition.
8136 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138 }
8139 }
8140 if (p == null) {
8141 // Create a new PackageSettings entry. this can end up here because
8142 // of code path mismatch or user id mismatch of an updated system partition
8143 if (!create) {
8144 return null;
8145 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008146 if (origPackage != null) {
8147 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008148 p = new PackageSetting(origPackage.name, name, codePath,
8149 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008150 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8151 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008152 // Note that we will retain the new package's signature so
8153 // that we can keep its data.
8154 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008155 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008156 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008157 p.sharedUser = origPackage.sharedUser;
8158 p.userId = origPackage.userId;
8159 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008160 mRenamedPackages.put(name, origPackage.name);
8161 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008162 // Update new package state.
8163 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008164 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008165 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008166 p.setTimeStamp(codePath.lastModified());
8167 p.sharedUser = sharedUser;
8168 if (sharedUser != null) {
8169 p.userId = sharedUser.userId;
8170 } else if (MULTIPLE_APPLICATION_UIDS) {
8171 // Clone the setting here for disabled system packages
8172 PackageSetting dis = mDisabledSysPackages.get(name);
8173 if (dis != null) {
8174 // For disabled packages a new setting is created
8175 // from the existing user id. This still has to be
8176 // added to list of user id's
8177 // Copy signatures from previous setting
8178 if (dis.signatures.mSignatures != null) {
8179 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8180 }
8181 p.userId = dis.userId;
8182 // Clone permissions
8183 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008184 // Clone component info
8185 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8186 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8187 // Add new setting to list of user ids
8188 addUserIdLP(p.userId, p, name);
8189 } else {
8190 // Assign new user id
8191 p.userId = newUserIdLP(p);
8192 }
8193 } else {
8194 p.userId = FIRST_APPLICATION_UID;
8195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008196 }
8197 if (p.userId < 0) {
8198 reportSettingsProblem(Log.WARN,
8199 "Package " + name + " could not be assigned a valid uid");
8200 return null;
8201 }
8202 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008203 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008204 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008205 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008206 }
8207 }
8208 return p;
8209 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008210
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008211 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008212 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008213 String codePath = pkg.applicationInfo.sourceDir;
8214 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008215 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008216 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008217 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008218 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008219 p.codePath = new File(codePath);
8220 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008221 }
8222 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008223 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008224 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008225 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008226 p.resourcePath = new File(resourcePath);
8227 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008228 }
8229 // Update version code if needed
8230 if (pkg.mVersionCode != p.versionCode) {
8231 p.versionCode = pkg.mVersionCode;
8232 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008233 // Update signatures if needed.
8234 if (p.signatures.mSignatures == null) {
8235 p.signatures.assignSignatures(pkg.mSignatures);
8236 }
8237 // If this app defines a shared user id initialize
8238 // the shared user signatures as well.
8239 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8240 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8241 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008242 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8243 }
8244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008245 // Utility method that adds a PackageSetting to mPackages and
8246 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008247 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008248 SharedUserSetting sharedUser) {
8249 mPackages.put(name, p);
8250 if (sharedUser != null) {
8251 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8252 reportSettingsProblem(Log.ERROR,
8253 "Package " + p.name + " was user "
8254 + p.sharedUser + " but is now " + sharedUser
8255 + "; I am not changing its files so it will probably fail!");
8256 p.sharedUser.packages.remove(p);
8257 } else if (p.userId != sharedUser.userId) {
8258 reportSettingsProblem(Log.ERROR,
8259 "Package " + p.name + " was user id " + p.userId
8260 + " but is now user " + sharedUser
8261 + " with id " + sharedUser.userId
8262 + "; I am not changing its files so it will probably fail!");
8263 }
8264
8265 sharedUser.packages.add(p);
8266 p.sharedUser = sharedUser;
8267 p.userId = sharedUser.userId;
8268 }
8269 }
8270
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008271 /*
8272 * Update the shared user setting when a package using
8273 * specifying the shared user id is removed. The gids
8274 * associated with each permission of the deleted package
8275 * are removed from the shared user's gid list only if its
8276 * not in use by other permissions of packages in the
8277 * shared user setting.
8278 */
8279 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008280 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008281 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 return;
8283 }
8284 // No sharedUserId
8285 if (deletedPs.sharedUser == null) {
8286 return;
8287 }
8288 SharedUserSetting sus = deletedPs.sharedUser;
8289 // Update permissions
8290 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8291 boolean used = false;
8292 if (!sus.grantedPermissions.contains (eachPerm)) {
8293 continue;
8294 }
8295 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008296 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008297 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008298 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008299 used = true;
8300 break;
8301 }
8302 }
8303 if (!used) {
8304 // can safely delete this permission from list
8305 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008306 }
8307 }
8308 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008309 int newGids[] = globalGids;
8310 for (String eachPerm : sus.grantedPermissions) {
8311 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008312 if (bp != null) {
8313 newGids = appendInts(newGids, bp.gids);
8314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008315 }
8316 sus.gids = newGids;
8317 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008319 private int removePackageLP(String name) {
8320 PackageSetting p = mPackages.get(name);
8321 if (p != null) {
8322 mPackages.remove(name);
8323 if (p.sharedUser != null) {
8324 p.sharedUser.packages.remove(p);
8325 if (p.sharedUser.packages.size() == 0) {
8326 mSharedUsers.remove(p.sharedUser.name);
8327 removeUserIdLP(p.sharedUser.userId);
8328 return p.sharedUser.userId;
8329 }
8330 } else {
8331 removeUserIdLP(p.userId);
8332 return p.userId;
8333 }
8334 }
8335 return -1;
8336 }
8337
8338 private boolean addUserIdLP(int uid, Object obj, Object name) {
8339 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8340 return false;
8341 }
8342
8343 if (uid >= FIRST_APPLICATION_UID) {
8344 int N = mUserIds.size();
8345 final int index = uid - FIRST_APPLICATION_UID;
8346 while (index >= N) {
8347 mUserIds.add(null);
8348 N++;
8349 }
8350 if (mUserIds.get(index) != null) {
8351 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008352 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008353 + " name=" + name);
8354 return false;
8355 }
8356 mUserIds.set(index, obj);
8357 } else {
8358 if (mOtherUserIds.get(uid) != null) {
8359 reportSettingsProblem(Log.ERROR,
8360 "Adding duplicate shared id: " + uid
8361 + " name=" + name);
8362 return false;
8363 }
8364 mOtherUserIds.put(uid, obj);
8365 }
8366 return true;
8367 }
8368
8369 public Object getUserIdLP(int uid) {
8370 if (uid >= FIRST_APPLICATION_UID) {
8371 int N = mUserIds.size();
8372 final int index = uid - FIRST_APPLICATION_UID;
8373 return index < N ? mUserIds.get(index) : null;
8374 } else {
8375 return mOtherUserIds.get(uid);
8376 }
8377 }
8378
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008379 private Set<String> findPackagesWithFlag(int flag) {
8380 Set<String> ret = new HashSet<String>();
8381 for (PackageSetting ps : mPackages.values()) {
8382 // Has to match atleast all the flag bits set on flag
8383 if ((ps.pkgFlags & flag) == flag) {
8384 ret.add(ps.name);
8385 }
8386 }
8387 return ret;
8388 }
8389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008390 private void removeUserIdLP(int uid) {
8391 if (uid >= FIRST_APPLICATION_UID) {
8392 int N = mUserIds.size();
8393 final int index = uid - FIRST_APPLICATION_UID;
8394 if (index < N) mUserIds.set(index, null);
8395 } else {
8396 mOtherUserIds.remove(uid);
8397 }
8398 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008400 void writeLP() {
8401 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8402
8403 // Keep the old settings around until we know the new ones have
8404 // been successfully written.
8405 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008406 // Presence of backup settings file indicates that we failed
8407 // to persist settings earlier. So preserve the older
8408 // backup for future reference since the current settings
8409 // might have been corrupted.
8410 if (!mBackupSettingsFilename.exists()) {
8411 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008412 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008413 return;
8414 }
8415 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008416 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008417 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008419 }
8420
8421 mPastSignatures.clear();
8422
8423 try {
8424 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8425
8426 //XmlSerializer serializer = XmlUtils.serializerInstance();
8427 XmlSerializer serializer = new FastXmlSerializer();
8428 serializer.setOutput(str, "utf-8");
8429 serializer.startDocument(null, true);
8430 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8431
8432 serializer.startTag(null, "packages");
8433
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008434 serializer.startTag(null, "last-platform-version");
8435 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8436 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8437 serializer.endTag(null, "last-platform-version");
8438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008439 serializer.startTag(null, "permission-trees");
8440 for (BasePermission bp : mPermissionTrees.values()) {
8441 writePermission(serializer, bp);
8442 }
8443 serializer.endTag(null, "permission-trees");
8444
8445 serializer.startTag(null, "permissions");
8446 for (BasePermission bp : mPermissions.values()) {
8447 writePermission(serializer, bp);
8448 }
8449 serializer.endTag(null, "permissions");
8450
8451 for (PackageSetting pkg : mPackages.values()) {
8452 writePackage(serializer, pkg);
8453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008455 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8456 writeDisabledSysPackage(serializer, pkg);
8457 }
8458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008459 serializer.startTag(null, "preferred-activities");
8460 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8461 serializer.startTag(null, "item");
8462 pa.writeToXml(serializer);
8463 serializer.endTag(null, "item");
8464 }
8465 serializer.endTag(null, "preferred-activities");
8466
8467 for (SharedUserSetting usr : mSharedUsers.values()) {
8468 serializer.startTag(null, "shared-user");
8469 serializer.attribute(null, "name", usr.name);
8470 serializer.attribute(null, "userId",
8471 Integer.toString(usr.userId));
8472 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8473 serializer.startTag(null, "perms");
8474 for (String name : usr.grantedPermissions) {
8475 serializer.startTag(null, "item");
8476 serializer.attribute(null, "name", name);
8477 serializer.endTag(null, "item");
8478 }
8479 serializer.endTag(null, "perms");
8480 serializer.endTag(null, "shared-user");
8481 }
8482
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008483 if (mPackagesToBeCleaned.size() > 0) {
8484 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8485 serializer.startTag(null, "cleaning-package");
8486 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8487 serializer.endTag(null, "cleaning-package");
8488 }
8489 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008490
8491 if (mRenamedPackages.size() > 0) {
8492 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8493 serializer.startTag(null, "renamed-package");
8494 serializer.attribute(null, "new", e.getKey());
8495 serializer.attribute(null, "old", e.getValue());
8496 serializer.endTag(null, "renamed-package");
8497 }
8498 }
8499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008500 serializer.endTag(null, "packages");
8501
8502 serializer.endDocument();
8503
8504 str.flush();
8505 str.close();
8506
8507 // New settings successfully written, old ones are no longer
8508 // needed.
8509 mBackupSettingsFilename.delete();
8510 FileUtils.setPermissions(mSettingsFilename.toString(),
8511 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8512 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8513 |FileUtils.S_IROTH,
8514 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008515
8516 // Write package list file now, use a JournaledFile.
8517 //
8518 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8519 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8520
8521 str = new FileOutputStream(journal.chooseForWrite());
8522 try {
8523 StringBuilder sb = new StringBuilder();
8524 for (PackageSetting pkg : mPackages.values()) {
8525 ApplicationInfo ai = pkg.pkg.applicationInfo;
8526 String dataPath = ai.dataDir;
8527 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8528
8529 // Avoid any application that has a space in its path
8530 // or that is handled by the system.
8531 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8532 continue;
8533
8534 // we store on each line the following information for now:
8535 //
8536 // pkgName - package name
8537 // userId - application-specific user id
8538 // debugFlag - 0 or 1 if the package is debuggable.
8539 // dataPath - path to package's data path
8540 //
8541 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8542 //
8543 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8544 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8545 // system/core/run-as/run-as.c
8546 //
8547 sb.setLength(0);
8548 sb.append(ai.packageName);
8549 sb.append(" ");
8550 sb.append((int)ai.uid);
8551 sb.append(isDebug ? " 1 " : " 0 ");
8552 sb.append(dataPath);
8553 sb.append("\n");
8554 str.write(sb.toString().getBytes());
8555 }
8556 str.flush();
8557 str.close();
8558 journal.commit();
8559 }
8560 catch (Exception e) {
8561 journal.rollback();
8562 }
8563
8564 FileUtils.setPermissions(mPackageListFilename.toString(),
8565 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8566 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8567 |FileUtils.S_IROTH,
8568 -1, -1);
8569
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008570 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008571
8572 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008573 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 -08008574 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008575 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 -08008576 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008577 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008578 if (mSettingsFilename.exists()) {
8579 if (!mSettingsFilename.delete()) {
8580 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8581 }
8582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008583 //Debug.stopMethodTracing();
8584 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008585
8586 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008587 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008588 serializer.startTag(null, "updated-package");
8589 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008590 if (pkg.realName != null) {
8591 serializer.attribute(null, "realName", pkg.realName);
8592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 serializer.attribute(null, "codePath", pkg.codePathString);
8594 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008595 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8597 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8598 }
8599 if (pkg.sharedUser == null) {
8600 serializer.attribute(null, "userId",
8601 Integer.toString(pkg.userId));
8602 } else {
8603 serializer.attribute(null, "sharedUserId",
8604 Integer.toString(pkg.userId));
8605 }
8606 serializer.startTag(null, "perms");
8607 if (pkg.sharedUser == null) {
8608 // If this is a shared user, the permissions will
8609 // be written there. We still need to write an
8610 // empty permissions list so permissionsFixed will
8611 // be set.
8612 for (final String name : pkg.grantedPermissions) {
8613 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008614 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008615 // We only need to write signature or system permissions but this wont
8616 // match the semantics of grantedPermissions. So write all permissions.
8617 serializer.startTag(null, "item");
8618 serializer.attribute(null, "name", name);
8619 serializer.endTag(null, "item");
8620 }
8621 }
8622 }
8623 serializer.endTag(null, "perms");
8624 serializer.endTag(null, "updated-package");
8625 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008626
8627 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008628 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629 serializer.startTag(null, "package");
8630 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008631 if (pkg.realName != null) {
8632 serializer.attribute(null, "realName", pkg.realName);
8633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634 serializer.attribute(null, "codePath", pkg.codePathString);
8635 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8636 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8637 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008638 serializer.attribute(null, "flags",
8639 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008641 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008642 if (pkg.sharedUser == null) {
8643 serializer.attribute(null, "userId",
8644 Integer.toString(pkg.userId));
8645 } else {
8646 serializer.attribute(null, "sharedUserId",
8647 Integer.toString(pkg.userId));
8648 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008649 if (pkg.uidError) {
8650 serializer.attribute(null, "uidError", "true");
8651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008652 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8653 serializer.attribute(null, "enabled",
8654 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8655 ? "true" : "false");
8656 }
8657 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8658 serializer.attribute(null, "installStatus", "false");
8659 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008660 if (pkg.installerPackageName != null) {
8661 serializer.attribute(null, "installer", pkg.installerPackageName);
8662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8664 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8665 serializer.startTag(null, "perms");
8666 if (pkg.sharedUser == null) {
8667 // If this is a shared user, the permissions will
8668 // be written there. We still need to write an
8669 // empty permissions list so permissionsFixed will
8670 // be set.
8671 for (final String name : pkg.grantedPermissions) {
8672 serializer.startTag(null, "item");
8673 serializer.attribute(null, "name", name);
8674 serializer.endTag(null, "item");
8675 }
8676 }
8677 serializer.endTag(null, "perms");
8678 }
8679 if (pkg.disabledComponents.size() > 0) {
8680 serializer.startTag(null, "disabled-components");
8681 for (final String name : pkg.disabledComponents) {
8682 serializer.startTag(null, "item");
8683 serializer.attribute(null, "name", name);
8684 serializer.endTag(null, "item");
8685 }
8686 serializer.endTag(null, "disabled-components");
8687 }
8688 if (pkg.enabledComponents.size() > 0) {
8689 serializer.startTag(null, "enabled-components");
8690 for (final String name : pkg.enabledComponents) {
8691 serializer.startTag(null, "item");
8692 serializer.attribute(null, "name", name);
8693 serializer.endTag(null, "item");
8694 }
8695 serializer.endTag(null, "enabled-components");
8696 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008698 serializer.endTag(null, "package");
8699 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008701 void writePermission(XmlSerializer serializer, BasePermission bp)
8702 throws XmlPullParserException, java.io.IOException {
8703 if (bp.type != BasePermission.TYPE_BUILTIN
8704 && bp.sourcePackage != null) {
8705 serializer.startTag(null, "item");
8706 serializer.attribute(null, "name", bp.name);
8707 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008708 if (bp.protectionLevel !=
8709 PermissionInfo.PROTECTION_NORMAL) {
8710 serializer.attribute(null, "protection",
8711 Integer.toString(bp.protectionLevel));
8712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008713 if (DEBUG_SETTINGS) Log.v(TAG,
8714 "Writing perm: name=" + bp.name + " type=" + bp.type);
8715 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8716 PermissionInfo pi = bp.perm != null ? bp.perm.info
8717 : bp.pendingInfo;
8718 if (pi != null) {
8719 serializer.attribute(null, "type", "dynamic");
8720 if (pi.icon != 0) {
8721 serializer.attribute(null, "icon",
8722 Integer.toString(pi.icon));
8723 }
8724 if (pi.nonLocalizedLabel != null) {
8725 serializer.attribute(null, "label",
8726 pi.nonLocalizedLabel.toString());
8727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008728 }
8729 }
8730 serializer.endTag(null, "item");
8731 }
8732 }
8733
8734 String getReadMessagesLP() {
8735 return mReadMessages.toString();
8736 }
8737
Oscar Montemayora8529f62009-11-18 10:14:20 -08008738 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008739 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8740 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008741 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008742 while(its.hasNext()) {
8743 String key = its.next();
8744 PackageSetting ps = mPackages.get(key);
8745 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008746 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008747 }
8748 }
8749 return ret;
8750 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008752 boolean readLP() {
8753 FileInputStream str = null;
8754 if (mBackupSettingsFilename.exists()) {
8755 try {
8756 str = new FileInputStream(mBackupSettingsFilename);
8757 mReadMessages.append("Reading from backup settings file\n");
8758 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008759 if (mSettingsFilename.exists()) {
8760 // If both the backup and settings file exist, we
8761 // ignore the settings since it might have been
8762 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008763 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008764 mSettingsFilename.delete();
8765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766 } catch (java.io.IOException e) {
8767 // We'll try for the normal settings file.
8768 }
8769 }
8770
8771 mPastSignatures.clear();
8772
8773 try {
8774 if (str == null) {
8775 if (!mSettingsFilename.exists()) {
8776 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008777 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008778 return false;
8779 }
8780 str = new FileInputStream(mSettingsFilename);
8781 }
8782 XmlPullParser parser = Xml.newPullParser();
8783 parser.setInput(str, null);
8784
8785 int type;
8786 while ((type=parser.next()) != XmlPullParser.START_TAG
8787 && type != XmlPullParser.END_DOCUMENT) {
8788 ;
8789 }
8790
8791 if (type != XmlPullParser.START_TAG) {
8792 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008793 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008794 return false;
8795 }
8796
8797 int outerDepth = parser.getDepth();
8798 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8799 && (type != XmlPullParser.END_TAG
8800 || parser.getDepth() > outerDepth)) {
8801 if (type == XmlPullParser.END_TAG
8802 || type == XmlPullParser.TEXT) {
8803 continue;
8804 }
8805
8806 String tagName = parser.getName();
8807 if (tagName.equals("package")) {
8808 readPackageLP(parser);
8809 } else if (tagName.equals("permissions")) {
8810 readPermissionsLP(mPermissions, parser);
8811 } else if (tagName.equals("permission-trees")) {
8812 readPermissionsLP(mPermissionTrees, parser);
8813 } else if (tagName.equals("shared-user")) {
8814 readSharedUserLP(parser);
8815 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008816 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008817 } else if (tagName.equals("preferred-activities")) {
8818 readPreferredActivitiesLP(parser);
8819 } else if(tagName.equals("updated-package")) {
8820 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008821 } else if (tagName.equals("cleaning-package")) {
8822 String name = parser.getAttributeValue(null, "name");
8823 if (name != null) {
8824 mPackagesToBeCleaned.add(name);
8825 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008826 } else if (tagName.equals("renamed-package")) {
8827 String nname = parser.getAttributeValue(null, "new");
8828 String oname = parser.getAttributeValue(null, "old");
8829 if (nname != null && oname != null) {
8830 mRenamedPackages.put(nname, oname);
8831 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008832 } else if (tagName.equals("last-platform-version")) {
8833 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8834 try {
8835 String internal = parser.getAttributeValue(null, "internal");
8836 if (internal != null) {
8837 mInternalSdkPlatform = Integer.parseInt(internal);
8838 }
8839 String external = parser.getAttributeValue(null, "external");
8840 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008841 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008842 }
8843 } catch (NumberFormatException e) {
8844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008846 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008847 + parser.getName());
8848 XmlUtils.skipCurrentTag(parser);
8849 }
8850 }
8851
8852 str.close();
8853
8854 } catch(XmlPullParserException e) {
8855 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008856 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008857
8858 } catch(java.io.IOException e) {
8859 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008860 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008861
8862 }
8863
8864 int N = mPendingPackages.size();
8865 for (int i=0; i<N; i++) {
8866 final PendingPackage pp = mPendingPackages.get(i);
8867 Object idObj = getUserIdLP(pp.sharedId);
8868 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008869 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008870 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008871 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008872 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008873 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008874 + pp.name);
8875 continue;
8876 }
8877 p.copyFrom(pp);
8878 } else if (idObj != null) {
8879 String msg = "Bad package setting: package " + pp.name
8880 + " has shared uid " + pp.sharedId
8881 + " that is not a shared uid\n";
8882 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008883 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008884 } else {
8885 String msg = "Bad package setting: package " + pp.name
8886 + " has shared uid " + pp.sharedId
8887 + " that is not defined\n";
8888 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008889 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008890 }
8891 }
8892 mPendingPackages.clear();
8893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008894 mReadMessages.append("Read completed successfully: "
8895 + mPackages.size() + " packages, "
8896 + mSharedUsers.size() + " shared uids\n");
8897
8898 return true;
8899 }
8900
8901 private int readInt(XmlPullParser parser, String ns, String name,
8902 int defValue) {
8903 String v = parser.getAttributeValue(ns, name);
8904 try {
8905 if (v == null) {
8906 return defValue;
8907 }
8908 return Integer.parseInt(v);
8909 } catch (NumberFormatException e) {
8910 reportSettingsProblem(Log.WARN,
8911 "Error in package manager settings: attribute " +
8912 name + " has bad integer value " + v + " at "
8913 + parser.getPositionDescription());
8914 }
8915 return defValue;
8916 }
8917
8918 private void readPermissionsLP(HashMap<String, BasePermission> out,
8919 XmlPullParser parser)
8920 throws IOException, XmlPullParserException {
8921 int outerDepth = parser.getDepth();
8922 int type;
8923 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8924 && (type != XmlPullParser.END_TAG
8925 || parser.getDepth() > outerDepth)) {
8926 if (type == XmlPullParser.END_TAG
8927 || type == XmlPullParser.TEXT) {
8928 continue;
8929 }
8930
8931 String tagName = parser.getName();
8932 if (tagName.equals("item")) {
8933 String name = parser.getAttributeValue(null, "name");
8934 String sourcePackage = parser.getAttributeValue(null, "package");
8935 String ptype = parser.getAttributeValue(null, "type");
8936 if (name != null && sourcePackage != null) {
8937 boolean dynamic = "dynamic".equals(ptype);
8938 BasePermission bp = new BasePermission(name, sourcePackage,
8939 dynamic
8940 ? BasePermission.TYPE_DYNAMIC
8941 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008942 bp.protectionLevel = readInt(parser, null, "protection",
8943 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 if (dynamic) {
8945 PermissionInfo pi = new PermissionInfo();
8946 pi.packageName = sourcePackage.intern();
8947 pi.name = name.intern();
8948 pi.icon = readInt(parser, null, "icon", 0);
8949 pi.nonLocalizedLabel = parser.getAttributeValue(
8950 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008951 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 bp.pendingInfo = pi;
8953 }
8954 out.put(bp.name, bp);
8955 } else {
8956 reportSettingsProblem(Log.WARN,
8957 "Error in package manager settings: permissions has"
8958 + " no name at " + parser.getPositionDescription());
8959 }
8960 } else {
8961 reportSettingsProblem(Log.WARN,
8962 "Unknown element reading permissions: "
8963 + parser.getName() + " at "
8964 + parser.getPositionDescription());
8965 }
8966 XmlUtils.skipCurrentTag(parser);
8967 }
8968 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008970 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008971 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008972 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008973 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008974 String codePathStr = parser.getAttributeValue(null, "codePath");
8975 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008976 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008977 resourcePathStr = codePathStr;
8978 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008979 String version = parser.getAttributeValue(null, "version");
8980 int versionCode = 0;
8981 if (version != null) {
8982 try {
8983 versionCode = Integer.parseInt(version);
8984 } catch (NumberFormatException e) {
8985 }
8986 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008988 int pkgFlags = 0;
8989 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008990 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008991 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008992 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008993 String timeStampStr = parser.getAttributeValue(null, "ts");
8994 if (timeStampStr != null) {
8995 try {
8996 long timeStamp = Long.parseLong(timeStampStr);
8997 ps.setTimeStamp(timeStamp, timeStampStr);
8998 } catch (NumberFormatException e) {
8999 }
9000 }
9001 String idStr = parser.getAttributeValue(null, "userId");
9002 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9003 if(ps.userId <= 0) {
9004 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9005 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9006 }
9007 int outerDepth = parser.getDepth();
9008 int type;
9009 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9010 && (type != XmlPullParser.END_TAG
9011 || parser.getDepth() > outerDepth)) {
9012 if (type == XmlPullParser.END_TAG
9013 || type == XmlPullParser.TEXT) {
9014 continue;
9015 }
9016
9017 String tagName = parser.getName();
9018 if (tagName.equals("perms")) {
9019 readGrantedPermissionsLP(parser,
9020 ps.grantedPermissions);
9021 } else {
9022 reportSettingsProblem(Log.WARN,
9023 "Unknown element under <updated-package>: "
9024 + parser.getName());
9025 XmlUtils.skipCurrentTag(parser);
9026 }
9027 }
9028 mDisabledSysPackages.put(name, ps);
9029 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009031 private void readPackageLP(XmlPullParser parser)
9032 throws XmlPullParserException, IOException {
9033 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009034 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 String idStr = null;
9036 String sharedIdStr = null;
9037 String codePathStr = null;
9038 String resourcePathStr = null;
9039 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009040 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009041 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009042 int pkgFlags = 0;
9043 String timeStampStr;
9044 long timeStamp = 0;
9045 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009046 String version = null;
9047 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009048 try {
9049 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009050 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009051 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009052 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009053 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9054 codePathStr = parser.getAttributeValue(null, "codePath");
9055 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009056 version = parser.getAttributeValue(null, "version");
9057 if (version != null) {
9058 try {
9059 versionCode = Integer.parseInt(version);
9060 } catch (NumberFormatException e) {
9061 }
9062 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009063 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009064
9065 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009066 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009067 try {
9068 pkgFlags = Integer.parseInt(systemStr);
9069 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009070 }
9071 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009072 // For backward compatibility
9073 systemStr = parser.getAttributeValue(null, "system");
9074 if (systemStr != null) {
9075 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9076 } else {
9077 // Old settings that don't specify system... just treat
9078 // them as system, good enough.
9079 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009081 }
9082 timeStampStr = parser.getAttributeValue(null, "ts");
9083 if (timeStampStr != null) {
9084 try {
9085 timeStamp = Long.parseLong(timeStampStr);
9086 } catch (NumberFormatException e) {
9087 }
9088 }
9089 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9090 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9091 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9092 if (resourcePathStr == null) {
9093 resourcePathStr = codePathStr;
9094 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009095 if (realName != null) {
9096 realName = realName.intern();
9097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009098 if (name == null) {
9099 reportSettingsProblem(Log.WARN,
9100 "Error in package manager settings: <package> has no name at "
9101 + parser.getPositionDescription());
9102 } else if (codePathStr == null) {
9103 reportSettingsProblem(Log.WARN,
9104 "Error in package manager settings: <package> has no codePath at "
9105 + parser.getPositionDescription());
9106 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009107 packageSetting = addPackageLP(name.intern(), realName,
9108 new File(codePathStr), new File(resourcePathStr),
9109 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009110 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9111 + ": userId=" + userId + " pkg=" + packageSetting);
9112 if (packageSetting == null) {
9113 reportSettingsProblem(Log.ERROR,
9114 "Failure adding uid " + userId
9115 + " while parsing settings at "
9116 + parser.getPositionDescription());
9117 } else {
9118 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9119 }
9120 } else if (sharedIdStr != null) {
9121 userId = sharedIdStr != null
9122 ? Integer.parseInt(sharedIdStr) : 0;
9123 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009124 packageSetting = new PendingPackage(name.intern(), realName,
9125 new File(codePathStr), new File(resourcePathStr),
9126 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009127 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9128 mPendingPackages.add((PendingPackage) packageSetting);
9129 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9130 + ": sharedUserId=" + userId + " pkg="
9131 + packageSetting);
9132 } else {
9133 reportSettingsProblem(Log.WARN,
9134 "Error in package manager settings: package "
9135 + name + " has bad sharedId " + sharedIdStr
9136 + " at " + parser.getPositionDescription());
9137 }
9138 } else {
9139 reportSettingsProblem(Log.WARN,
9140 "Error in package manager settings: package "
9141 + name + " has bad userId " + idStr + " at "
9142 + parser.getPositionDescription());
9143 }
9144 } catch (NumberFormatException e) {
9145 reportSettingsProblem(Log.WARN,
9146 "Error in package manager settings: package "
9147 + name + " has bad userId " + idStr + " at "
9148 + parser.getPositionDescription());
9149 }
9150 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009151 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009152 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009153 final String enabledStr = parser.getAttributeValue(null, "enabled");
9154 if (enabledStr != null) {
9155 if (enabledStr.equalsIgnoreCase("true")) {
9156 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9157 } else if (enabledStr.equalsIgnoreCase("false")) {
9158 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9159 } else if (enabledStr.equalsIgnoreCase("default")) {
9160 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9161 } else {
9162 reportSettingsProblem(Log.WARN,
9163 "Error in package manager settings: package "
9164 + name + " has bad enabled value: " + idStr
9165 + " at " + parser.getPositionDescription());
9166 }
9167 } else {
9168 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9169 }
9170 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9171 if (installStatusStr != null) {
9172 if (installStatusStr.equalsIgnoreCase("false")) {
9173 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9174 } else {
9175 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9176 }
9177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009179 int outerDepth = parser.getDepth();
9180 int type;
9181 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9182 && (type != XmlPullParser.END_TAG
9183 || parser.getDepth() > outerDepth)) {
9184 if (type == XmlPullParser.END_TAG
9185 || type == XmlPullParser.TEXT) {
9186 continue;
9187 }
9188
9189 String tagName = parser.getName();
9190 if (tagName.equals("disabled-components")) {
9191 readDisabledComponentsLP(packageSetting, parser);
9192 } else if (tagName.equals("enabled-components")) {
9193 readEnabledComponentsLP(packageSetting, parser);
9194 } else if (tagName.equals("sigs")) {
9195 packageSetting.signatures.readXml(parser, mPastSignatures);
9196 } else if (tagName.equals("perms")) {
9197 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009198 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009199 packageSetting.permissionsFixed = true;
9200 } else {
9201 reportSettingsProblem(Log.WARN,
9202 "Unknown element under <package>: "
9203 + parser.getName());
9204 XmlUtils.skipCurrentTag(parser);
9205 }
9206 }
9207 } else {
9208 XmlUtils.skipCurrentTag(parser);
9209 }
9210 }
9211
9212 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9213 XmlPullParser parser)
9214 throws IOException, XmlPullParserException {
9215 int outerDepth = parser.getDepth();
9216 int type;
9217 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9218 && (type != XmlPullParser.END_TAG
9219 || parser.getDepth() > outerDepth)) {
9220 if (type == XmlPullParser.END_TAG
9221 || type == XmlPullParser.TEXT) {
9222 continue;
9223 }
9224
9225 String tagName = parser.getName();
9226 if (tagName.equals("item")) {
9227 String name = parser.getAttributeValue(null, "name");
9228 if (name != null) {
9229 packageSetting.disabledComponents.add(name.intern());
9230 } else {
9231 reportSettingsProblem(Log.WARN,
9232 "Error in package manager settings: <disabled-components> has"
9233 + " no name at " + parser.getPositionDescription());
9234 }
9235 } else {
9236 reportSettingsProblem(Log.WARN,
9237 "Unknown element under <disabled-components>: "
9238 + parser.getName());
9239 }
9240 XmlUtils.skipCurrentTag(parser);
9241 }
9242 }
9243
9244 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9245 XmlPullParser parser)
9246 throws IOException, XmlPullParserException {
9247 int outerDepth = parser.getDepth();
9248 int type;
9249 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9250 && (type != XmlPullParser.END_TAG
9251 || parser.getDepth() > outerDepth)) {
9252 if (type == XmlPullParser.END_TAG
9253 || type == XmlPullParser.TEXT) {
9254 continue;
9255 }
9256
9257 String tagName = parser.getName();
9258 if (tagName.equals("item")) {
9259 String name = parser.getAttributeValue(null, "name");
9260 if (name != null) {
9261 packageSetting.enabledComponents.add(name.intern());
9262 } else {
9263 reportSettingsProblem(Log.WARN,
9264 "Error in package manager settings: <enabled-components> has"
9265 + " no name at " + parser.getPositionDescription());
9266 }
9267 } else {
9268 reportSettingsProblem(Log.WARN,
9269 "Unknown element under <enabled-components>: "
9270 + parser.getName());
9271 }
9272 XmlUtils.skipCurrentTag(parser);
9273 }
9274 }
9275
9276 private void readSharedUserLP(XmlPullParser parser)
9277 throws XmlPullParserException, IOException {
9278 String name = null;
9279 String idStr = null;
9280 int pkgFlags = 0;
9281 SharedUserSetting su = null;
9282 try {
9283 name = parser.getAttributeValue(null, "name");
9284 idStr = parser.getAttributeValue(null, "userId");
9285 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9286 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9287 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9288 }
9289 if (name == null) {
9290 reportSettingsProblem(Log.WARN,
9291 "Error in package manager settings: <shared-user> has no name at "
9292 + parser.getPositionDescription());
9293 } else if (userId == 0) {
9294 reportSettingsProblem(Log.WARN,
9295 "Error in package manager settings: shared-user "
9296 + name + " has bad userId " + idStr + " at "
9297 + parser.getPositionDescription());
9298 } else {
9299 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9300 reportSettingsProblem(Log.ERROR,
9301 "Occurred while parsing settings at "
9302 + parser.getPositionDescription());
9303 }
9304 }
9305 } catch (NumberFormatException e) {
9306 reportSettingsProblem(Log.WARN,
9307 "Error in package manager settings: package "
9308 + name + " has bad userId " + idStr + " at "
9309 + parser.getPositionDescription());
9310 };
9311
9312 if (su != null) {
9313 int outerDepth = parser.getDepth();
9314 int type;
9315 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9316 && (type != XmlPullParser.END_TAG
9317 || parser.getDepth() > outerDepth)) {
9318 if (type == XmlPullParser.END_TAG
9319 || type == XmlPullParser.TEXT) {
9320 continue;
9321 }
9322
9323 String tagName = parser.getName();
9324 if (tagName.equals("sigs")) {
9325 su.signatures.readXml(parser, mPastSignatures);
9326 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009327 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009328 } else {
9329 reportSettingsProblem(Log.WARN,
9330 "Unknown element under <shared-user>: "
9331 + parser.getName());
9332 XmlUtils.skipCurrentTag(parser);
9333 }
9334 }
9335
9336 } else {
9337 XmlUtils.skipCurrentTag(parser);
9338 }
9339 }
9340
9341 private void readGrantedPermissionsLP(XmlPullParser parser,
9342 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9343 int outerDepth = parser.getDepth();
9344 int type;
9345 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9346 && (type != XmlPullParser.END_TAG
9347 || parser.getDepth() > outerDepth)) {
9348 if (type == XmlPullParser.END_TAG
9349 || type == XmlPullParser.TEXT) {
9350 continue;
9351 }
9352
9353 String tagName = parser.getName();
9354 if (tagName.equals("item")) {
9355 String name = parser.getAttributeValue(null, "name");
9356 if (name != null) {
9357 outPerms.add(name.intern());
9358 } else {
9359 reportSettingsProblem(Log.WARN,
9360 "Error in package manager settings: <perms> has"
9361 + " no name at " + parser.getPositionDescription());
9362 }
9363 } else {
9364 reportSettingsProblem(Log.WARN,
9365 "Unknown element under <perms>: "
9366 + parser.getName());
9367 }
9368 XmlUtils.skipCurrentTag(parser);
9369 }
9370 }
9371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009372 private void readPreferredActivitiesLP(XmlPullParser parser)
9373 throws XmlPullParserException, IOException {
9374 int outerDepth = parser.getDepth();
9375 int type;
9376 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9377 && (type != XmlPullParser.END_TAG
9378 || parser.getDepth() > outerDepth)) {
9379 if (type == XmlPullParser.END_TAG
9380 || type == XmlPullParser.TEXT) {
9381 continue;
9382 }
9383
9384 String tagName = parser.getName();
9385 if (tagName.equals("item")) {
9386 PreferredActivity pa = new PreferredActivity(parser);
9387 if (pa.mParseError == null) {
9388 mPreferredActivities.addFilter(pa);
9389 } else {
9390 reportSettingsProblem(Log.WARN,
9391 "Error in package manager settings: <preferred-activity> "
9392 + pa.mParseError + " at "
9393 + parser.getPositionDescription());
9394 }
9395 } else {
9396 reportSettingsProblem(Log.WARN,
9397 "Unknown element under <preferred-activities>: "
9398 + parser.getName());
9399 XmlUtils.skipCurrentTag(parser);
9400 }
9401 }
9402 }
9403
9404 // Returns -1 if we could not find an available UserId to assign
9405 private int newUserIdLP(Object obj) {
9406 // Let's be stupidly inefficient for now...
9407 final int N = mUserIds.size();
9408 for (int i=0; i<N; i++) {
9409 if (mUserIds.get(i) == null) {
9410 mUserIds.set(i, obj);
9411 return FIRST_APPLICATION_UID + i;
9412 }
9413 }
9414
9415 // None left?
9416 if (N >= MAX_APPLICATION_UIDS) {
9417 return -1;
9418 }
9419
9420 mUserIds.add(obj);
9421 return FIRST_APPLICATION_UID + N;
9422 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009424 public PackageSetting getDisabledSystemPkg(String name) {
9425 synchronized(mPackages) {
9426 PackageSetting ps = mDisabledSysPackages.get(name);
9427 return ps;
9428 }
9429 }
9430
9431 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9432 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9433 if (Config.LOGV) {
9434 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9435 + " componentName = " + componentInfo.name);
9436 Log.v(TAG, "enabledComponents: "
9437 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9438 Log.v(TAG, "disabledComponents: "
9439 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9440 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009441 if (packageSettings == null) {
9442 if (false) {
9443 Log.w(TAG, "WAITING FOR DEBUGGER");
9444 Debug.waitForDebugger();
9445 Log.i(TAG, "We will crash!");
9446 }
9447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009448 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9449 || ((componentInfo.enabled
9450 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9451 || (componentInfo.applicationInfo.enabled
9452 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9453 && !packageSettings.disabledComponents.contains(componentInfo.name))
9454 || packageSettings.enabledComponents.contains(componentInfo.name));
9455 }
9456 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009457
9458 // ------- apps on sdcard specific code -------
9459 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009460 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009461 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009462 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009463 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009464
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009465 private String getEncryptKey() {
9466 try {
9467 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9468 if (sdEncKey == null) {
9469 sdEncKey = SystemKeyStore.getInstance().
9470 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9471 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009472 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009473 return null;
9474 }
9475 }
9476 return sdEncKey;
9477 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009478 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009479 return null;
9480 }
9481 }
9482
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009483 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009484 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009485 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009486 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009487 if (list != null) {
9488 int idx = 0;
9489 int idList[] = new int[MAX_CONTAINERS];
9490 boolean neverFound = true;
9491 for (String name : list) {
9492 // Ignore null entries
9493 if (name == null) {
9494 continue;
9495 }
9496 int sidx = name.indexOf(prefix);
9497 if (sidx == -1) {
9498 // Not a temp file. just ignore
9499 continue;
9500 }
9501 String subStr = name.substring(sidx + prefix.length());
9502 idList[idx] = -1;
9503 if (subStr != null) {
9504 try {
9505 int cid = Integer.parseInt(subStr);
9506 idList[idx++] = cid;
9507 neverFound = false;
9508 } catch (NumberFormatException e) {
9509 }
9510 }
9511 }
9512 if (!neverFound) {
9513 // Sort idList
9514 Arrays.sort(idList);
9515 for (int j = 1; j <= idList.length; j++) {
9516 if (idList[j-1] != j) {
9517 tmpIdx = j;
9518 break;
9519 }
9520 }
9521 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009522 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009523 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009524 }
9525
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009526 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009527 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009528 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009529 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9530 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9531 throw new SecurityException("Media status can only be updated by the system");
9532 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009533 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009534 Log.i(TAG, "Updating external media status from " +
9535 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9536 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009537 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9538 mediaStatus+", mMediaMounted=" + mMediaMounted);
9539 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009540 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9541 reportStatus ? 1 : 0, -1);
9542 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009543 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009544 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009545 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009546 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009547 // Queue up an async operation since the package installation may take a little while.
9548 mHandler.post(new Runnable() {
9549 public void run() {
9550 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009551 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009552 }
9553 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009554 }
9555
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009556 /*
9557 * Collect information of applications on external media, map them
9558 * against existing containers and update information based on current
9559 * mount status. Please note that we always have to report status
9560 * if reportStatus has been set to true especially when unloading packages.
9561 */
9562 private void updateExternalMediaStatusInner(boolean mediaStatus,
9563 boolean reportStatus) {
9564 // Collection of uids
9565 int uidArr[] = null;
9566 // Collection of stale containers
9567 HashSet<String> removeCids = new HashSet<String>();
9568 // Collection of packages on external media with valid containers.
9569 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9570 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009571 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009572 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009573 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009574 } else {
9575 // Process list of secure containers and categorize them
9576 // as active or stale based on their package internal state.
9577 int uidList[] = new int[list.length];
9578 int num = 0;
9579 synchronized (mPackages) {
9580 for (String cid : list) {
9581 SdInstallArgs args = new SdInstallArgs(cid);
9582 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009583 String pkgName = args.getPackageName();
9584 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009585 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9586 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009587 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009588 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009589 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9590 PackageSetting ps = mSettings.mPackages.get(pkgName);
9591 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009592 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009593 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9594 " corresponds to pkg : " + pkgName +
9595 " at code path: " + ps.codePathString);
9596 // We do have a valid package installed on sdcard
9597 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009598 int uid = ps.userId;
9599 if (uid != -1) {
9600 uidList[num++] = uid;
9601 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009602 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009603 // Stale container on sdcard. Just delete
9604 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9605 removeCids.add(cid);
9606 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009607 }
9608 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009609
9610 if (num > 0) {
9611 // Sort uid list
9612 Arrays.sort(uidList, 0, num);
9613 // Throw away duplicates
9614 uidArr = new int[num];
9615 uidArr[0] = uidList[0];
9616 int di = 0;
9617 for (int i = 1; i < num; i++) {
9618 if (uidList[i-1] != uidList[i]) {
9619 uidArr[di++] = uidList[i];
9620 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009621 }
9622 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009623 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009624 // Process packages with valid entries.
9625 if (mediaStatus) {
9626 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009627 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009628 startCleaningPackages();
9629 } else {
9630 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009631 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009632 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009633 }
9634
9635 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009636 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009637 int size = pkgList.size();
9638 if (size > 0) {
9639 // Send broadcasts here
9640 Bundle extras = new Bundle();
9641 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9642 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009643 if (uidArr != null) {
9644 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9645 }
9646 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9647 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009648 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009649 }
9650 }
9651
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009652 /*
9653 * Look at potentially valid container ids from processCids
9654 * If package information doesn't match the one on record
9655 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009656 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009657 */
9658 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009659 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009660 ArrayList<String> pkgList = new ArrayList<String>();
9661 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009662 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009663 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009664 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009665 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9666 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009667 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009668 try {
9669 // Make sure there are no container errors first.
9670 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9671 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009672 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009673 " when installing from sdcard");
9674 continue;
9675 }
9676 // Check code path here.
9677 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009678 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009679 " does not match one in settings " + codePath);
9680 continue;
9681 }
9682 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009683 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009684 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009685 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009686 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9687 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009688 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009689 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009690 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009691 retCode = PackageManager.INSTALL_SUCCEEDED;
9692 pkgList.add(pkg.packageName);
9693 // Post process args
9694 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9695 }
9696 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009697 Slog.i(TAG, "Failed to install pkg from " +
9698 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009699 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009700 }
9701
9702 } finally {
9703 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9704 // Don't destroy container here. Wait till gc clears things up.
9705 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009706 }
9707 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009708 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009709 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009710 // If the platform SDK has changed since the last time we booted,
9711 // we need to re-grant app permission to catch any new ones that
9712 // appear. This is really a hack, and means that apps can in some
9713 // cases get permissions that the user didn't initially explicitly
9714 // allow... it would be nice to have some better way to handle
9715 // this situation.
9716 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9717 != mSdkVersion;
9718 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9719 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9720 + "; regranting permissions for external storage");
9721 mSettings.mExternalSdkPlatform = mSdkVersion;
9722
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009723 // Make sure group IDs have been assigned, and any permission
9724 // changes in other apps are accounted for
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009725 updatePermissionsLP(null, null, true, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009726 // Persist settings
9727 mSettings.writeLP();
9728 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009729 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009730 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009731 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009732 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009733 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009734 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009735 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009736 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009737 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009738 if (removeCids != null) {
9739 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009740 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009741 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009742 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009743 }
9744
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009745 /*
9746 * Utility method to unload a list of specified containers
9747 */
9748 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9749 // Just unmount all valid containers.
9750 for (SdInstallArgs arg : cidArgs) {
9751 synchronized (mInstallLock) {
9752 arg.doPostDeleteLI(false);
9753 }
9754 }
9755 }
9756
9757 /*
9758 * Unload packages mounted on external media. This involves deleting
9759 * package data from internal structures, sending broadcasts about
9760 * diabled packages, gc'ing to free up references, unmounting all
9761 * secure containers corresponding to packages on external media, and
9762 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9763 * Please note that we always have to post this message if status has
9764 * been requested no matter what.
9765 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009766 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009767 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009768 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009769 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009770 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009771 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009772 for (SdInstallArgs args : keys) {
9773 String cid = args.cid;
9774 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009775 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009776 // Delete package internally
9777 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9778 synchronized (mInstallLock) {
9779 boolean res = deletePackageLI(pkgName, false,
9780 PackageManager.DONT_DELETE_DATA, outInfo);
9781 if (res) {
9782 pkgList.add(pkgName);
9783 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009784 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009785 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009786 }
9787 }
9788 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009789 // We have to absolutely send UPDATED_MEDIA_STATUS only
9790 // after confirming that all the receivers processed the ordered
9791 // broadcast when packages get disabled, force a gc to clean things up.
9792 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009793 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009794 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9795 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9796 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009797 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9798 reportStatus ? 1 : 0, 1, keys);
9799 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009800 }
9801 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009802 } else {
9803 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9804 reportStatus ? 1 : 0, -1, keys);
9805 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009806 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009807 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009808
9809 public void movePackage(final String packageName,
9810 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009811 mContext.enforceCallingOrSelfPermission(
9812 android.Manifest.permission.MOVE_PACKAGE, null);
9813 int returnCode = PackageManager.MOVE_SUCCEEDED;
9814 int currFlags = 0;
9815 int newFlags = 0;
9816 synchronized (mPackages) {
9817 PackageParser.Package pkg = mPackages.get(packageName);
9818 if (pkg == null) {
9819 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009820 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009821 // Disable moving fwd locked apps and system packages
9822 if (pkg.applicationInfo != null &&
9823 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9824 Slog.w(TAG, "Cannot move system application");
9825 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9826 } else if (pkg.applicationInfo != null &&
9827 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9828 Slog.w(TAG, "Cannot move forward locked app.");
9829 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009830 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009831 // Find install location first
9832 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9833 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9834 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009835 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009836 } else {
9837 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9838 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9839 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9840 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9841 if (newFlags == currFlags) {
9842 Slog.w(TAG, "No move required. Trying to move to same location");
9843 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9844 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009845 }
9846 }
9847 }
9848 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07009849 processPendingMove(new MoveParams(null, observer, 0, packageName), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009850 } else {
9851 Message msg = mHandler.obtainMessage(INIT_COPY);
9852 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9853 pkg.applicationInfo.publicSourceDir);
9854 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9855 packageName);
9856 msg.obj = mp;
9857 mHandler.sendMessage(msg);
9858 }
9859 }
9860 }
9861
9862 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9863 // Queue up an async operation since the package deletion may take a little while.
9864 mHandler.post(new Runnable() {
9865 public void run() {
9866 mHandler.removeCallbacks(this);
9867 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009868 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9869 int uidArr[] = null;
9870 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009871 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009872 PackageParser.Package pkg = mPackages.get(mp.packageName);
9873 if (pkg == null ) {
9874 Slog.w(TAG, " Package " + mp.packageName +
9875 " doesn't exist. Aborting move");
9876 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9877 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9878 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9879 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9880 " Aborting move and returning error");
9881 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9882 } else {
9883 uidArr = new int[] { pkg.applicationInfo.uid };
9884 pkgList = new ArrayList<String>();
9885 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009886 }
9887 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009888 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9889 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009890 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009891 // Update package code and resource paths
9892 synchronized (mInstallLock) {
9893 synchronized (mPackages) {
9894 PackageParser.Package pkg = mPackages.get(mp.packageName);
9895 // Recheck for package again.
9896 if (pkg == null ) {
9897 Slog.w(TAG, " Package " + mp.packageName +
9898 " doesn't exist. Aborting move");
9899 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9900 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9901 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9902 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9903 " Aborting move and returning error");
9904 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9905 } else {
9906 String oldCodePath = pkg.mPath;
9907 String newCodePath = mp.targetArgs.getCodePath();
9908 String newResPath = mp.targetArgs.getResourcePath();
9909 pkg.mPath = newCodePath;
9910 // Move dex files around
9911 if (moveDexFilesLI(pkg)
9912 != PackageManager.INSTALL_SUCCEEDED) {
9913 // Moving of dex files failed. Set
9914 // error code and abort move.
9915 pkg.mPath = pkg.mScanPath;
9916 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9917 } else {
9918 pkg.mScanPath = newCodePath;
9919 pkg.applicationInfo.sourceDir = newCodePath;
9920 pkg.applicationInfo.publicSourceDir = newResPath;
9921 PackageSetting ps = (PackageSetting) pkg.mExtras;
9922 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9923 ps.codePathString = ps.codePath.getPath();
9924 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9925 ps.resourcePathString = ps.resourcePath.getPath();
9926 // Set the application info flag correctly.
9927 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9928 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9929 } else {
9930 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9931 }
9932 ps.setFlags(pkg.applicationInfo.flags);
9933 mAppDirs.remove(oldCodePath);
9934 mAppDirs.put(newCodePath, pkg);
9935 // Persist settings
9936 mSettings.writeLP();
9937 }
9938 }
9939 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009940 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009941 // Send resources available broadcast
9942 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009943 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009944 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009945 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009946 // Clean up failed installation
9947 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009948 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009949 }
9950 } else {
9951 // Force a gc to clear things up.
9952 Runtime.getRuntime().gc();
9953 // Delete older code
9954 synchronized (mInstallLock) {
9955 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009956 }
9957 }
9958 IPackageMoveObserver observer = mp.observer;
9959 if (observer != null) {
9960 try {
9961 observer.packageMoved(mp.packageName, returnCode);
9962 } catch (RemoteException e) {
9963 Log.i(TAG, "Observer no longer exists.");
9964 }
9965 }
9966 }
9967 });
9968 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009969
9970 public boolean setInstallLocation(int loc) {
9971 mContext.enforceCallingOrSelfPermission(
9972 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9973 if (getInstallLocation() == loc) {
9974 return true;
9975 }
9976 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9977 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9978 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9979 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9980 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9981 return true;
9982 }
9983 return false;
9984 }
9985
9986 public int getInstallLocation() {
9987 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9988 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009990}