blob: 2ad1bd5d1fb364e71386319d5b310f1d8069f0ef [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
141 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
142 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400143 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 private static final int FIRST_APPLICATION_UID =
145 Process.FIRST_APPLICATION_UID;
146 private static final int MAX_APPLICATION_UIDS = 1000;
147
148 private static final boolean SHOW_INFO = false;
149
150 private static final boolean GET_CERTIFICATES = true;
151
Oscar Montemayora8529f62009-11-18 10:14:20 -0800152 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 private static final int REMOVE_EVENTS =
155 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
156 private static final int ADD_EVENTS =
157 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
158
159 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800160 // Suffix used during package installation when copying/moving
161 // package apks to install directory.
162 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800164 /**
165 * Indicates the state of installation. Used by PackageManager to
166 * figure out incomplete installations. Say a package is being installed
167 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
168 * the package installation is successful or unsuccesful lin which case
169 * the PackageManager will no longer maintain state information associated
170 * with the package. If some exception(like device freeze or battery being
171 * pulled out) occurs during installation of a package, the PackageManager
172 * needs this information to clean up the previously failed installation.
173 */
174 private static final int PKG_INSTALL_INCOMPLETE = 0;
175 private static final int PKG_INSTALL_COMPLETE = 1;
176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 static final int SCAN_MONITOR = 1<<0;
178 static final int SCAN_NO_DEX = 1<<1;
179 static final int SCAN_FORCE_DEX = 1<<2;
180 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800181 static final int SCAN_NEW_INSTALL = 1<<4;
182 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800184 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
185 "com.android.defcontainer",
186 "com.android.defcontainer.DefaultContainerService");
187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
189 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700190 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
Dianne Hackborn851a5412009-05-08 12:06:44 -0700192 final int mSdkVersion = Build.VERSION.SDK_INT;
193 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
194 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 final Context mContext;
197 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700198 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 final DisplayMetrics mMetrics;
200 final int mDefParseFlags;
201 final String[] mSeparateProcesses;
202
203 // This is where all application persistent data goes.
204 final File mAppDataDir;
205
Oscar Montemayora8529f62009-11-18 10:14:20 -0800206 // If Encrypted File System feature is enabled, all application persistent data
207 // should go here instead.
208 final File mSecureAppDataDir;
209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 // This is the object monitoring the framework dir.
211 final FileObserver mFrameworkInstallObserver;
212
213 // This is the object monitoring the system app dir.
214 final FileObserver mSystemInstallObserver;
215
216 // This is the object monitoring mAppInstallDir.
217 final FileObserver mAppInstallObserver;
218
219 // This is the object monitoring mDrmAppPrivateInstallDir.
220 final FileObserver mDrmAppInstallObserver;
221
222 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
223 // LOCK HELD. Can be called with mInstallLock held.
224 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 final File mFrameworkDir;
227 final File mSystemAppDir;
228 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700229 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230
231 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
232 // apps.
233 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 // Lock for state used when installing and doing other long running
238 // operations. Methods that must be called with this lock held have
239 // the prefix "LI".
240 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 // These are the directories in the 3rd party applications installed dir
243 // that we have currently loaded packages from. Keys are the application's
244 // installed zip file (absolute codePath), and values are Package.
245 final HashMap<String, PackageParser.Package> mAppDirs =
246 new HashMap<String, PackageParser.Package>();
247
248 // Information for the parser to write more useful error messages.
249 File mScanningPath;
250 int mLastScanError;
251
252 final int[] mOutPermissions = new int[3];
253
254 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 // Keys are String (package name), values are Package. This also serves
257 // as the lock for the global state. Methods that must be called with
258 // this lock held have the prefix "LP".
259 final HashMap<String, PackageParser.Package> mPackages =
260 new HashMap<String, PackageParser.Package>();
261
262 final Settings mSettings;
263 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264
265 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
266 int[] mGlobalGids;
267
268 // These are the built-in uid -> permission mappings that were read from the
269 // etc/permissions.xml file.
270 final SparseArray<HashSet<String>> mSystemPermissions =
271 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 // These are the built-in shared libraries that were read from the
274 // etc/permissions.xml file.
275 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800276
Dianne Hackborn49237342009-08-27 20:08:01 -0700277 // Temporary for building the final shared libraries for an .apk.
278 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800279
Dianne Hackborn49237342009-08-27 20:08:01 -0700280 // These are the features this devices supports that were read from the
281 // etc/permissions.xml file.
282 final HashMap<String, FeatureInfo> mAvailableFeatures =
283 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 // All available activities, for your resolving pleasure.
286 final ActivityIntentResolver mActivities =
287 new ActivityIntentResolver();
288
289 // All available receivers, for your resolving pleasure.
290 final ActivityIntentResolver mReceivers =
291 new ActivityIntentResolver();
292
293 // All available services, for your resolving pleasure.
294 final ServiceIntentResolver mServices = new ServiceIntentResolver();
295
296 // Keys are String (provider class name), values are Provider.
297 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
298 new HashMap<ComponentName, PackageParser.Provider>();
299
300 // Mapping from provider base names (first directory in content URI codePath)
301 // to the provider information.
302 final HashMap<String, PackageParser.Provider> mProviders =
303 new HashMap<String, PackageParser.Provider>();
304
305 // Mapping from instrumentation class names to info about them.
306 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
307 new HashMap<ComponentName, PackageParser.Instrumentation>();
308
309 // Mapping from permission names to info about them.
310 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
311 new HashMap<String, PackageParser.PermissionGroup>();
312
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800313 // Packages whose data we have transfered into another package, thus
314 // should no longer exist.
315 final HashSet<String> mTransferedPackages = new HashSet<String>();
316
Dianne Hackborn854060af2009-07-09 18:14:31 -0700317 // Broadcast actions that are only available to the system.
318 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 boolean mSystemReady;
321 boolean mSafeMode;
322 boolean mHasSystemUidErrors;
323
324 ApplicationInfo mAndroidApplication;
325 final ActivityInfo mResolveActivity = new ActivityInfo();
326 final ResolveInfo mResolveInfo = new ResolveInfo();
327 ComponentName mResolveComponentName;
328 PackageParser.Package mPlatformPackage;
329
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700330 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800331 final HashMap<String, ArrayList<String>> mPendingBroadcasts
332 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800333 // Service Connection to remote media container service to copy
334 // package uri's from external media onto secure containers
335 // or internal storage.
336 private IMediaContainerService mContainerService = null;
337
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700338 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800339 static final int MCS_BOUND = 3;
340 static final int END_COPY = 4;
341 static final int INIT_COPY = 5;
342 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800343 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800344 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800345 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800346 static final int MCS_RECONNECT = 10;
347 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700348 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700349 static final int WRITE_SETTINGS = 13;
350
351 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800352
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700353 // Delay time in millisecs
354 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800355 final private DefaultContainerConnection mDefContainerConn =
356 new DefaultContainerConnection();
357 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800358 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800359 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800360 IMediaContainerService imcs =
361 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800362 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800363 }
364
365 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800366 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800367 }
368 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700369
Christopher Tate1bb69062010-02-19 17:02:12 -0800370 // Recordkeeping of restore-after-install operations that are currently in flight
371 // between the Package Manager and the Backup Manager
372 class PostInstallData {
373 public InstallArgs args;
374 public PackageInstalledInfo res;
375
376 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
377 args = _a;
378 res = _r;
379 }
380 };
381 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
382 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
383
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700384 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800385 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800386 final ArrayList<HandlerParams> mPendingInstalls =
387 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800388
389 private boolean connectToService() {
390 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
391 " DefaultContainerService");
392 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700393 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800394 if (mContext.bindService(service, mDefContainerConn,
395 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700396 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800397 mBound = true;
398 return true;
399 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700400 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800401 return false;
402 }
403
404 private void disconnectService() {
405 mContainerService = null;
406 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700407 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800408 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800410 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800411
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700412 PackageHandler(Looper looper) {
413 super(looper);
414 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700415
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700416 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700417 try {
418 doHandleMessage(msg);
419 } finally {
420 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
421 }
422 }
423
424 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700425 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800426 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800427 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800428 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800429 int idx = mPendingInstalls.size();
430 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
431 // If a bind was already initiated we dont really
432 // need to do anything. The pending install
433 // will be processed later on.
434 if (!mBound) {
435 // If this is the only one pending we might
436 // have to bind to the service again.
437 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800438 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800439 params.serviceError();
440 return;
441 } else {
442 // Once we bind to the service, the first
443 // pending request will be processed.
444 mPendingInstalls.add(idx, params);
445 }
446 } else {
447 mPendingInstalls.add(idx, params);
448 // Already bound to the service. Just make
449 // sure we trigger off processing the first request.
450 if (idx == 0) {
451 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800452 }
453 }
454 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800455 }
456 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800457 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800458 if (msg.obj != null) {
459 mContainerService = (IMediaContainerService) msg.obj;
460 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800461 if (mContainerService == null) {
462 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800463 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800464 for (HandlerParams params : mPendingInstalls) {
465 mPendingInstalls.remove(0);
466 // Indicate service bind error
467 params.serviceError();
468 }
469 mPendingInstalls.clear();
470 } else if (mPendingInstalls.size() > 0) {
471 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800472 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800473 params.startCopy();
474 }
475 } else {
476 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800477 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800478 }
479 break;
480 }
481 case MCS_RECONNECT : {
482 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
483 if (mPendingInstalls.size() > 0) {
484 if (mBound) {
485 disconnectService();
486 }
487 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800488 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800489 for (HandlerParams params : mPendingInstalls) {
490 mPendingInstalls.remove(0);
491 // Indicate service bind error
492 params.serviceError();
493 }
494 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800495 }
496 }
497 break;
498 }
499 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800500 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
501 // Delete pending install
502 if (mPendingInstalls.size() > 0) {
503 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800504 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800505 if (mPendingInstalls.size() == 0) {
506 if (mBound) {
507 disconnectService();
508 }
509 } else {
510 // There are more pending requests in queue.
511 // Just post MCS_BOUND message to trigger processing
512 // of next pending install.
513 mHandler.sendEmptyMessage(MCS_BOUND);
514 }
515 break;
516 }
517 case MCS_GIVE_UP: {
518 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
519 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800520 break;
521 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700522 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800523 String packages[];
524 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700525 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700526 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700527 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700528 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800529 if (mPendingBroadcasts == null) {
530 return;
531 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700532 size = mPendingBroadcasts.size();
533 if (size <= 0) {
534 // Nothing to be done. Just return
535 return;
536 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800537 packages = new String[size];
538 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700539 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800540 Iterator<HashMap.Entry<String, ArrayList<String>>>
541 it = mPendingBroadcasts.entrySet().iterator();
542 int i = 0;
543 while (it.hasNext() && i < size) {
544 HashMap.Entry<String, ArrayList<String>> ent = it.next();
545 packages[i] = ent.getKey();
546 components[i] = ent.getValue();
547 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700548 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800549 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700550 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800551 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700552 mPendingBroadcasts.clear();
553 }
554 // Send broadcasts
555 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800556 sendPackageChangedBroadcast(packages[i], true,
557 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700558 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700559 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700560 break;
561 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800562 case START_CLEANING_PACKAGE: {
563 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700564 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800565 synchronized (mPackages) {
566 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
567 mSettings.mPackagesToBeCleaned.add(packageName);
568 }
569 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700570 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800571 startCleaningPackages();
572 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800573 case POST_INSTALL: {
574 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
575 PostInstallData data = mRunningInstalls.get(msg.arg1);
576 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800577 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800578
579 if (data != null) {
580 InstallArgs args = data.args;
581 PackageInstalledInfo res = data.res;
582
583 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
584 res.removedInfo.sendBroadcast(false, true);
585 Bundle extras = new Bundle(1);
586 extras.putInt(Intent.EXTRA_UID, res.uid);
587 final boolean update = res.removedInfo.removedPackage != null;
588 if (update) {
589 extras.putBoolean(Intent.EXTRA_REPLACING, true);
590 }
591 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
592 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700593 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800594 if (update) {
595 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
596 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700597 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800598 }
599 if (res.removedInfo.args != null) {
600 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800601 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800602 }
603 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800604 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800605 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800606 // We delete after a gc for applications on sdcard.
607 if (deleteOld) {
608 synchronized (mInstallLock) {
609 res.removedInfo.args.doPostDeleteLI(true);
610 }
611 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800612 if (args.observer != null) {
613 try {
614 args.observer.packageInstalled(res.name, res.returnCode);
615 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800616 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800617 }
618 }
619 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800620 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800621 }
622 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700623 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700624 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
625 boolean reportStatus = msg.arg1 == 1;
626 boolean doGc = msg.arg2 == 1;
627 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
628 if (doGc) {
629 // Force a gc to clear up stale containers.
630 Runtime.getRuntime().gc();
631 }
632 if (msg.obj != null) {
633 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
634 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
635 // Unload containers
636 unloadAllContainers(args);
637 }
638 if (reportStatus) {
639 try {
640 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
641 PackageHelper.getMountService().finishMediaUpdate();
642 } catch (RemoteException e) {
643 Log.e(TAG, "MountService not running?");
644 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700645 }
646 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700647 case WRITE_SETTINGS: {
648 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
649 synchronized (mPackages) {
650 removeMessages(WRITE_SETTINGS);
651 mSettings.writeLP();
652 }
653 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
654 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700655 }
656 }
657 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800658
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700659 void scheduleWriteSettingsLocked() {
660 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
661 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
662 }
663 }
664
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800665 static boolean installOnSd(int flags) {
666 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700667 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800668 return false;
669 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700670 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
671 return true;
672 }
673 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800674 }
675
676 static boolean isFwdLocked(int flags) {
677 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
678 return true;
679 }
680 return false;
681 }
682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 public static final IPackageManager main(Context context, boolean factoryTest) {
684 PackageManagerService m = new PackageManagerService(context, factoryTest);
685 ServiceManager.addService("package", m);
686 return m;
687 }
688
689 static String[] splitString(String str, char sep) {
690 int count = 1;
691 int i = 0;
692 while ((i=str.indexOf(sep, i)) >= 0) {
693 count++;
694 i++;
695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 String[] res = new String[count];
698 i=0;
699 count = 0;
700 int lastI=0;
701 while ((i=str.indexOf(sep, i)) >= 0) {
702 res[count] = str.substring(lastI, i);
703 count++;
704 i++;
705 lastI = i;
706 }
707 res[count] = str.substring(lastI, str.length());
708 return res;
709 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800712 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800716 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 mContext = context;
720 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700721 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 mMetrics = new DisplayMetrics();
723 mSettings = new Settings();
724 mSettings.addSharedUserLP("android.uid.system",
725 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
726 mSettings.addSharedUserLP("android.uid.phone",
727 MULTIPLE_APPLICATION_UIDS
728 ? RADIO_UID : FIRST_APPLICATION_UID,
729 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400730 mSettings.addSharedUserLP("android.uid.log",
731 MULTIPLE_APPLICATION_UIDS
732 ? LOG_UID : FIRST_APPLICATION_UID,
733 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734
735 String separateProcesses = SystemProperties.get("debug.separate_processes");
736 if (separateProcesses != null && separateProcesses.length() > 0) {
737 if ("*".equals(separateProcesses)) {
738 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
739 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800740 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 } else {
742 mDefParseFlags = 0;
743 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800744 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 + separateProcesses);
746 }
747 } else {
748 mDefParseFlags = 0;
749 mSeparateProcesses = null;
750 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 Installer installer = new Installer();
753 // Little hacky thing to check if installd is here, to determine
754 // whether we are running on the simulator and thus need to take
755 // care of building the /data file structure ourself.
756 // (apparently the sim now has a working installer)
757 if (installer.ping() && Process.supportsProcesses()) {
758 mInstaller = installer;
759 } else {
760 mInstaller = null;
761 }
762
763 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
764 Display d = wm.getDefaultDisplay();
765 d.getMetrics(mMetrics);
766
767 synchronized (mInstallLock) {
768 synchronized (mPackages) {
769 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700770 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 File dataDir = Environment.getDataDirectory();
773 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800774 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
776
777 if (mInstaller == null) {
778 // Make sure these dirs exist, when we are running in
779 // the simulator.
780 // Make a wide-open directory for random misc stuff.
781 File miscDir = new File(dataDir, "misc");
782 miscDir.mkdirs();
783 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800784 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 mDrmAppPrivateInstallDir.mkdirs();
786 }
787
788 readPermissions();
789
790 mRestoredSettings = mSettings.readLP();
791 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800792
793 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800795
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800796 // Set flag to monitor and not change apk file paths when
797 // scanning install directories.
798 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700799 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800800 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800801 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700802 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700807 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700810 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 /**
813 * Out of paranoia, ensure that everything in the boot class
814 * path has been dexed.
815 */
816 String bootClassPath = System.getProperty("java.boot.class.path");
817 if (bootClassPath != null) {
818 String[] paths = splitString(bootClassPath, ':');
819 for (int i=0; i<paths.length; i++) {
820 try {
821 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
822 libFiles.add(paths[i]);
823 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700824 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 }
826 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800827 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800829 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 }
831 }
832 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800833 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 /**
837 * Also ensure all external libraries have had dexopt run on them.
838 */
839 if (mSharedLibraries.size() > 0) {
840 Iterator<String> libs = mSharedLibraries.values().iterator();
841 while (libs.hasNext()) {
842 String lib = libs.next();
843 try {
844 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
845 libFiles.add(lib);
846 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700847 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
849 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800850 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800852 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 }
854 }
855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 // Gross hack for now: we know this file doesn't contain any
858 // code, so don't dexopt it to avoid the resulting log spew.
859 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 /**
862 * And there are a number of commands implemented in Java, which
863 * we currently need to do the dexopt on so that they can be
864 * run from a non-root shell.
865 */
866 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700867 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 for (int i=0; i<frameworkFiles.length; i++) {
869 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
870 String path = libPath.getPath();
871 // Skip the file if we alrady did it.
872 if (libFiles.contains(path)) {
873 continue;
874 }
875 // Skip the file if it is not a type we want to dexopt.
876 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
877 continue;
878 }
879 try {
880 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
881 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700882 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 }
884 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800885 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800887 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 }
889 }
890 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800891
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700892 if (didDexOpt) {
893 // If we had to do a dexopt of one of the previous
894 // things, then something on the system has changed.
895 // Consider this significant, and wipe away all other
896 // existing dexopt files to ensure we don't leave any
897 // dangling around.
898 String[] files = mDalvikCacheDir.list();
899 if (files != null) {
900 for (int i=0; i<files.length; i++) {
901 String fn = files[i];
902 if (fn.startsWith("data@app@")
903 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800904 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700905 (new File(mDalvikCacheDir, fn)).delete();
906 }
907 }
908 }
909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800911
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800912 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 mFrameworkInstallObserver = new AppDirObserver(
914 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
915 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700916 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
917 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800918 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800919
920 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
922 mSystemInstallObserver = new AppDirObserver(
923 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
924 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700925 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
926 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800927
928 if (mInstaller != null) {
929 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
930 mInstaller.moveFiles();
931 }
932
933 // Prune any system packages that no longer exist.
934 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
935 while (psit.hasNext()) {
936 PackageSetting ps = psit.next();
937 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800938 && !mPackages.containsKey(ps.name)
939 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800940 psit.remove();
941 String msg = "System package " + ps.name
942 + " no longer exists; wiping its data";
943 reportSettingsProblem(Log.WARN, msg);
944 if (mInstaller != null) {
945 // XXX how to set useEncryptedFSDir for packages that
946 // are not encrypted?
947 mInstaller.remove(ps.name, true);
948 }
949 }
950 }
951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 mAppInstallDir = new File(dataDir, "app");
953 if (mInstaller == null) {
954 // Make sure these dirs exist, when we are running in
955 // the simulator.
956 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
957 }
958 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800959 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 //clean up list
961 for(int i = 0; i < deletePkgsList.size(); i++) {
962 //clean up here
963 cleanupInstallFailedPackage(deletePkgsList.get(i));
964 }
965 //delete tmp files
966 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800967
968 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 SystemClock.uptimeMillis());
970 mAppInstallObserver = new AppDirObserver(
971 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
972 mAppInstallObserver.startWatching();
973 scanDirLI(mAppInstallDir, 0, scanMode);
974
975 mDrmAppInstallObserver = new AppDirObserver(
976 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
977 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800978 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800980 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800982 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 + ((SystemClock.uptimeMillis()-startTime)/1000f)
984 + " seconds");
985
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700986 // If the platform SDK has changed since the last time we booted,
987 // we need to re-grant app permission to catch any new ones that
988 // appear. This is really a hack, and means that apps can in some
989 // cases get permissions that the user didn't initially explicitly
990 // allow... it would be nice to have some better way to handle
991 // this situation.
992 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
993 != mSdkVersion;
994 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
995 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
996 + "; regranting permissions for internal storage");
997 mSettings.mInternalSdkPlatform = mSdkVersion;
998
999 updatePermissionsLP(null, null, true, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000
1001 mSettings.writeLP();
1002
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001003 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 // Now after opening every single application zip, make sure they
1007 // are all flushed. Not really needed, but keeps things nice and
1008 // tidy.
1009 Runtime.getRuntime().gc();
1010 } // synchronized (mPackages)
1011 } // synchronized (mInstallLock)
1012 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 @Override
1015 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1016 throws RemoteException {
1017 try {
1018 return super.onTransact(code, data, reply, flags);
1019 } catch (RuntimeException e) {
1020 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001021 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 }
1023 throw e;
1024 }
1025 }
1026
Dianne Hackborne6620b22010-01-22 14:46:21 -08001027 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001028 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001030 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1031 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001033 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001034 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 }
1036 } else {
1037 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001038 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 File dataDir = new File(pkg.applicationInfo.dataDir);
1040 dataDir.delete();
1041 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001042 if (ps.codePath != null) {
1043 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001044 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001045 }
1046 }
1047 if (ps.resourcePath != null) {
1048 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001049 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001050 }
1051 }
1052 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 }
1054
1055 void readPermissions() {
1056 // Read permissions from .../etc/permission directory.
1057 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1058 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001059 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 return;
1061 }
1062 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001063 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 return;
1065 }
1066
1067 // Iterate over the files in the directory and scan .xml files
1068 for (File f : libraryDir.listFiles()) {
1069 // We'll read platform.xml last
1070 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1071 continue;
1072 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001075 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 continue;
1077 }
1078 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001079 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 continue;
1081 }
1082
1083 readPermissionsFromXml(f);
1084 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1087 final File permFile = new File(Environment.getRootDirectory(),
1088 "etc/permissions/platform.xml");
1089 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001090
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001091 StringBuilder sb = new StringBuilder(128);
1092 sb.append("Libs:");
1093 Iterator<String> it = mSharedLibraries.keySet().iterator();
1094 while (it.hasNext()) {
1095 sb.append(' ');
1096 String name = it.next();
1097 sb.append(name);
1098 sb.append(':');
1099 sb.append(mSharedLibraries.get(name));
1100 }
1101 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001102
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001103 sb.setLength(0);
1104 sb.append("Features:");
1105 it = mAvailableFeatures.keySet().iterator();
1106 while (it.hasNext()) {
1107 sb.append(' ');
1108 sb.append(it.next());
1109 }
1110 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001112
1113 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 FileReader permReader = null;
1115 try {
1116 permReader = new FileReader(permFile);
1117 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001118 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 return;
1120 }
1121
1122 try {
1123 XmlPullParser parser = Xml.newPullParser();
1124 parser.setInput(permReader);
1125
1126 XmlUtils.beginDocument(parser, "permissions");
1127
1128 while (true) {
1129 XmlUtils.nextElement(parser);
1130 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1131 break;
1132 }
1133
1134 String name = parser.getName();
1135 if ("group".equals(name)) {
1136 String gidStr = parser.getAttributeValue(null, "gid");
1137 if (gidStr != null) {
1138 int gid = Integer.parseInt(gidStr);
1139 mGlobalGids = appendInt(mGlobalGids, gid);
1140 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001141 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 + parser.getPositionDescription());
1143 }
1144
1145 XmlUtils.skipCurrentTag(parser);
1146 continue;
1147 } else if ("permission".equals(name)) {
1148 String perm = parser.getAttributeValue(null, "name");
1149 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001150 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 + parser.getPositionDescription());
1152 XmlUtils.skipCurrentTag(parser);
1153 continue;
1154 }
1155 perm = perm.intern();
1156 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 } else if ("assign-permission".equals(name)) {
1159 String perm = parser.getAttributeValue(null, "name");
1160 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001161 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 + parser.getPositionDescription());
1163 XmlUtils.skipCurrentTag(parser);
1164 continue;
1165 }
1166 String uidStr = parser.getAttributeValue(null, "uid");
1167 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001168 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 + parser.getPositionDescription());
1170 XmlUtils.skipCurrentTag(parser);
1171 continue;
1172 }
1173 int uid = Process.getUidForName(uidStr);
1174 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001175 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 + uidStr + "\" at "
1177 + parser.getPositionDescription());
1178 XmlUtils.skipCurrentTag(parser);
1179 continue;
1180 }
1181 perm = perm.intern();
1182 HashSet<String> perms = mSystemPermissions.get(uid);
1183 if (perms == null) {
1184 perms = new HashSet<String>();
1185 mSystemPermissions.put(uid, perms);
1186 }
1187 perms.add(perm);
1188 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 } else if ("library".equals(name)) {
1191 String lname = parser.getAttributeValue(null, "name");
1192 String lfile = parser.getAttributeValue(null, "file");
1193 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001194 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 + parser.getPositionDescription());
1196 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001197 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 + parser.getPositionDescription());
1199 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001200 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001201 mSharedLibraries.put(lname, lfile);
1202 }
1203 XmlUtils.skipCurrentTag(parser);
1204 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001205
Dianne Hackborn49237342009-08-27 20:08:01 -07001206 } else if ("feature".equals(name)) {
1207 String fname = parser.getAttributeValue(null, "name");
1208 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001209 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001210 + parser.getPositionDescription());
1211 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001212 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001213 FeatureInfo fi = new FeatureInfo();
1214 fi.name = fname;
1215 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 }
1217 XmlUtils.skipCurrentTag(parser);
1218 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 } else {
1221 XmlUtils.skipCurrentTag(parser);
1222 continue;
1223 }
1224
1225 }
1226 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001227 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001229 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 }
1231 }
1232
1233 void readPermission(XmlPullParser parser, String name)
1234 throws IOException, XmlPullParserException {
1235
1236 name = name.intern();
1237
1238 BasePermission bp = mSettings.mPermissions.get(name);
1239 if (bp == null) {
1240 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1241 mSettings.mPermissions.put(name, bp);
1242 }
1243 int outerDepth = parser.getDepth();
1244 int type;
1245 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1246 && (type != XmlPullParser.END_TAG
1247 || parser.getDepth() > outerDepth)) {
1248 if (type == XmlPullParser.END_TAG
1249 || type == XmlPullParser.TEXT) {
1250 continue;
1251 }
1252
1253 String tagName = parser.getName();
1254 if ("group".equals(tagName)) {
1255 String gidStr = parser.getAttributeValue(null, "gid");
1256 if (gidStr != null) {
1257 int gid = Process.getGidForName(gidStr);
1258 bp.gids = appendInt(bp.gids, gid);
1259 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001260 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 + parser.getPositionDescription());
1262 }
1263 }
1264 XmlUtils.skipCurrentTag(parser);
1265 }
1266 }
1267
1268 static int[] appendInt(int[] cur, int val) {
1269 if (cur == null) {
1270 return new int[] { val };
1271 }
1272 final int N = cur.length;
1273 for (int i=0; i<N; i++) {
1274 if (cur[i] == val) {
1275 return cur;
1276 }
1277 }
1278 int[] ret = new int[N+1];
1279 System.arraycopy(cur, 0, ret, 0, N);
1280 ret[N] = val;
1281 return ret;
1282 }
1283
1284 static int[] appendInts(int[] cur, int[] add) {
1285 if (add == null) return cur;
1286 if (cur == null) return add;
1287 final int N = add.length;
1288 for (int i=0; i<N; i++) {
1289 cur = appendInt(cur, add[i]);
1290 }
1291 return cur;
1292 }
1293
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001294 static int[] removeInt(int[] cur, int val) {
1295 if (cur == null) {
1296 return null;
1297 }
1298 final int N = cur.length;
1299 for (int i=0; i<N; i++) {
1300 if (cur[i] == val) {
1301 int[] ret = new int[N-1];
1302 if (i > 0) {
1303 System.arraycopy(cur, 0, ret, 0, i);
1304 }
1305 if (i < (N-1)) {
1306 System.arraycopy(cur, i, ret, i+1, N-i-1);
1307 }
1308 return ret;
1309 }
1310 }
1311 return cur;
1312 }
1313
1314 static int[] removeInts(int[] cur, int[] rem) {
1315 if (rem == null) return cur;
1316 if (cur == null) return cur;
1317 final int N = rem.length;
1318 for (int i=0; i<N; i++) {
1319 cur = removeInt(cur, rem[i]);
1320 }
1321 return cur;
1322 }
1323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001325 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1326 // The package has been uninstalled but has retained data and resources.
1327 return PackageParser.generatePackageInfo(p, null, flags);
1328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 final PackageSetting ps = (PackageSetting)p.mExtras;
1330 if (ps == null) {
1331 return null;
1332 }
1333 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1334 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1335 }
1336
1337 public PackageInfo getPackageInfo(String packageName, int flags) {
1338 synchronized (mPackages) {
1339 PackageParser.Package p = mPackages.get(packageName);
1340 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001341 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 + ": " + p);
1343 if (p != null) {
1344 return generatePackageInfo(p, flags);
1345 }
1346 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1347 return generatePackageInfoFromSettingsLP(packageName, flags);
1348 }
1349 }
1350 return null;
1351 }
1352
Dianne Hackborn47096932010-02-11 15:57:09 -08001353 public String[] currentToCanonicalPackageNames(String[] names) {
1354 String[] out = new String[names.length];
1355 synchronized (mPackages) {
1356 for (int i=names.length-1; i>=0; i--) {
1357 PackageSetting ps = mSettings.mPackages.get(names[i]);
1358 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1359 }
1360 }
1361 return out;
1362 }
1363
1364 public String[] canonicalToCurrentPackageNames(String[] names) {
1365 String[] out = new String[names.length];
1366 synchronized (mPackages) {
1367 for (int i=names.length-1; i>=0; i--) {
1368 String cur = mSettings.mRenamedPackages.get(names[i]);
1369 out[i] = cur != null ? cur : names[i];
1370 }
1371 }
1372 return out;
1373 }
1374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 public int getPackageUid(String packageName) {
1376 synchronized (mPackages) {
1377 PackageParser.Package p = mPackages.get(packageName);
1378 if(p != null) {
1379 return p.applicationInfo.uid;
1380 }
1381 PackageSetting ps = mSettings.mPackages.get(packageName);
1382 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1383 return -1;
1384 }
1385 p = ps.pkg;
1386 return p != null ? p.applicationInfo.uid : -1;
1387 }
1388 }
1389
1390 public int[] getPackageGids(String packageName) {
1391 synchronized (mPackages) {
1392 PackageParser.Package p = mPackages.get(packageName);
1393 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001394 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 + ": " + p);
1396 if (p != null) {
1397 final PackageSetting ps = (PackageSetting)p.mExtras;
1398 final SharedUserSetting suid = ps.sharedUser;
1399 return suid != null ? suid.gids : ps.gids;
1400 }
1401 }
1402 // stupid thing to indicate an error.
1403 return new int[0];
1404 }
1405
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001406 static final PermissionInfo generatePermissionInfo(
1407 BasePermission bp, int flags) {
1408 if (bp.perm != null) {
1409 return PackageParser.generatePermissionInfo(bp.perm, flags);
1410 }
1411 PermissionInfo pi = new PermissionInfo();
1412 pi.name = bp.name;
1413 pi.packageName = bp.sourcePackage;
1414 pi.nonLocalizedLabel = bp.name;
1415 pi.protectionLevel = bp.protectionLevel;
1416 return pi;
1417 }
1418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 public PermissionInfo getPermissionInfo(String name, int flags) {
1420 synchronized (mPackages) {
1421 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001422 if (p != null) {
1423 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
1425 return null;
1426 }
1427 }
1428
1429 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1430 synchronized (mPackages) {
1431 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1432 for (BasePermission p : mSettings.mPermissions.values()) {
1433 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001434 if (p.perm == null || p.perm.info.group == null) {
1435 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 }
1437 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001438 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1440 }
1441 }
1442 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 if (out.size() > 0) {
1445 return out;
1446 }
1447 return mPermissionGroups.containsKey(group) ? out : null;
1448 }
1449 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1452 synchronized (mPackages) {
1453 return PackageParser.generatePermissionGroupInfo(
1454 mPermissionGroups.get(name), flags);
1455 }
1456 }
1457
1458 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1459 synchronized (mPackages) {
1460 final int N = mPermissionGroups.size();
1461 ArrayList<PermissionGroupInfo> out
1462 = new ArrayList<PermissionGroupInfo>(N);
1463 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1464 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1465 }
1466 return out;
1467 }
1468 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1471 PackageSetting ps = mSettings.mPackages.get(packageName);
1472 if(ps != null) {
1473 if(ps.pkg == null) {
1474 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1475 if(pInfo != null) {
1476 return pInfo.applicationInfo;
1477 }
1478 return null;
1479 }
1480 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1481 }
1482 return null;
1483 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1486 PackageSetting ps = mSettings.mPackages.get(packageName);
1487 if(ps != null) {
1488 if(ps.pkg == null) {
1489 ps.pkg = new PackageParser.Package(packageName);
1490 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001491 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1492 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1493 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1494 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
1496 return generatePackageInfo(ps.pkg, flags);
1497 }
1498 return null;
1499 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1502 synchronized (mPackages) {
1503 PackageParser.Package p = mPackages.get(packageName);
1504 if (Config.LOGV) Log.v(
1505 TAG, "getApplicationInfo " + packageName
1506 + ": " + p);
1507 if (p != null) {
1508 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001509 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 }
1511 if ("android".equals(packageName)||"system".equals(packageName)) {
1512 return mAndroidApplication;
1513 }
1514 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1515 return generateApplicationInfoFromSettingsLP(packageName, flags);
1516 }
1517 }
1518 return null;
1519 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001520
1521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1523 mContext.enforceCallingOrSelfPermission(
1524 android.Manifest.permission.CLEAR_APP_CACHE, null);
1525 // Queue up an async operation since clearing cache may take a little while.
1526 mHandler.post(new Runnable() {
1527 public void run() {
1528 mHandler.removeCallbacks(this);
1529 int retCode = -1;
1530 if (mInstaller != null) {
1531 retCode = mInstaller.freeCache(freeStorageSize);
1532 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001533 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 }
1535 } //end if mInstaller
1536 if (observer != null) {
1537 try {
1538 observer.onRemoveCompleted(null, (retCode >= 0));
1539 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001540 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
1542 }
1543 }
1544 });
1545 }
1546
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001547 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001548 mContext.enforceCallingOrSelfPermission(
1549 android.Manifest.permission.CLEAR_APP_CACHE, null);
1550 // Queue up an async operation since clearing cache may take a little while.
1551 mHandler.post(new Runnable() {
1552 public void run() {
1553 mHandler.removeCallbacks(this);
1554 int retCode = -1;
1555 if (mInstaller != null) {
1556 retCode = mInstaller.freeCache(freeStorageSize);
1557 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001558 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001559 }
1560 }
1561 if(pi != null) {
1562 try {
1563 // Callback via pending intent
1564 int code = (retCode >= 0) ? 1 : 0;
1565 pi.sendIntent(null, code, null,
1566 null, null);
1567 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001568 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001569 }
1570 }
1571 }
1572 });
1573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1576 synchronized (mPackages) {
1577 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001578
1579 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001581 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
1583 if (mResolveComponentName.equals(component)) {
1584 return mResolveActivity;
1585 }
1586 }
1587 return null;
1588 }
1589
1590 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1591 synchronized (mPackages) {
1592 PackageParser.Activity a = mReceivers.mActivities.get(component);
1593 if (Config.LOGV) Log.v(
1594 TAG, "getReceiverInfo " + component + ": " + a);
1595 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1596 return PackageParser.generateActivityInfo(a, flags);
1597 }
1598 }
1599 return null;
1600 }
1601
1602 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1603 synchronized (mPackages) {
1604 PackageParser.Service s = mServices.mServices.get(component);
1605 if (Config.LOGV) Log.v(
1606 TAG, "getServiceInfo " + component + ": " + s);
1607 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1608 return PackageParser.generateServiceInfo(s, flags);
1609 }
1610 }
1611 return null;
1612 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 public String[] getSystemSharedLibraryNames() {
1615 Set<String> libSet;
1616 synchronized (mPackages) {
1617 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001618 int size = libSet.size();
1619 if (size > 0) {
1620 String[] libs = new String[size];
1621 libSet.toArray(libs);
1622 return libs;
1623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001625 return null;
1626 }
1627
1628 public FeatureInfo[] getSystemAvailableFeatures() {
1629 Collection<FeatureInfo> featSet;
1630 synchronized (mPackages) {
1631 featSet = mAvailableFeatures.values();
1632 int size = featSet.size();
1633 if (size > 0) {
1634 FeatureInfo[] features = new FeatureInfo[size+1];
1635 featSet.toArray(features);
1636 FeatureInfo fi = new FeatureInfo();
1637 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1638 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1639 features[size] = fi;
1640 return features;
1641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 }
1643 return null;
1644 }
1645
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001646 public boolean hasSystemFeature(String name) {
1647 synchronized (mPackages) {
1648 return mAvailableFeatures.containsKey(name);
1649 }
1650 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 public int checkPermission(String permName, String pkgName) {
1653 synchronized (mPackages) {
1654 PackageParser.Package p = mPackages.get(pkgName);
1655 if (p != null && p.mExtras != null) {
1656 PackageSetting ps = (PackageSetting)p.mExtras;
1657 if (ps.sharedUser != null) {
1658 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1659 return PackageManager.PERMISSION_GRANTED;
1660 }
1661 } else if (ps.grantedPermissions.contains(permName)) {
1662 return PackageManager.PERMISSION_GRANTED;
1663 }
1664 }
1665 }
1666 return PackageManager.PERMISSION_DENIED;
1667 }
1668
1669 public int checkUidPermission(String permName, int uid) {
1670 synchronized (mPackages) {
1671 Object obj = mSettings.getUserIdLP(uid);
1672 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001673 GrantedPermissions gp = (GrantedPermissions)obj;
1674 if (gp.grantedPermissions.contains(permName)) {
1675 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 }
1677 } else {
1678 HashSet<String> perms = mSystemPermissions.get(uid);
1679 if (perms != null && perms.contains(permName)) {
1680 return PackageManager.PERMISSION_GRANTED;
1681 }
1682 }
1683 }
1684 return PackageManager.PERMISSION_DENIED;
1685 }
1686
1687 private BasePermission findPermissionTreeLP(String permName) {
1688 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1689 if (permName.startsWith(bp.name) &&
1690 permName.length() > bp.name.length() &&
1691 permName.charAt(bp.name.length()) == '.') {
1692 return bp;
1693 }
1694 }
1695 return null;
1696 }
1697
1698 private BasePermission checkPermissionTreeLP(String permName) {
1699 if (permName != null) {
1700 BasePermission bp = findPermissionTreeLP(permName);
1701 if (bp != null) {
1702 if (bp.uid == Binder.getCallingUid()) {
1703 return bp;
1704 }
1705 throw new SecurityException("Calling uid "
1706 + Binder.getCallingUid()
1707 + " is not allowed to add to permission tree "
1708 + bp.name + " owned by uid " + bp.uid);
1709 }
1710 }
1711 throw new SecurityException("No permission tree found for " + permName);
1712 }
1713
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001714 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1715 if (s1 == null) {
1716 return s2 == null;
1717 }
1718 if (s2 == null) {
1719 return false;
1720 }
1721 if (s1.getClass() != s2.getClass()) {
1722 return false;
1723 }
1724 return s1.equals(s2);
1725 }
1726
1727 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1728 if (pi1.icon != pi2.icon) return false;
1729 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1730 if (!compareStrings(pi1.name, pi2.name)) return false;
1731 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1732 // We'll take care of setting this one.
1733 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1734 // These are not currently stored in settings.
1735 //if (!compareStrings(pi1.group, pi2.group)) return false;
1736 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1737 //if (pi1.labelRes != pi2.labelRes) return false;
1738 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1739 return true;
1740 }
1741
1742 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1743 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1744 throw new SecurityException("Label must be specified in permission");
1745 }
1746 BasePermission tree = checkPermissionTreeLP(info.name);
1747 BasePermission bp = mSettings.mPermissions.get(info.name);
1748 boolean added = bp == null;
1749 boolean changed = true;
1750 if (added) {
1751 bp = new BasePermission(info.name, tree.sourcePackage,
1752 BasePermission.TYPE_DYNAMIC);
1753 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1754 throw new SecurityException(
1755 "Not allowed to modify non-dynamic permission "
1756 + info.name);
1757 } else {
1758 if (bp.protectionLevel == info.protectionLevel
1759 && bp.perm.owner.equals(tree.perm.owner)
1760 && bp.uid == tree.uid
1761 && comparePermissionInfos(bp.perm.info, info)) {
1762 changed = false;
1763 }
1764 }
1765 bp.protectionLevel = info.protectionLevel;
1766 bp.perm = new PackageParser.Permission(tree.perm.owner,
1767 new PermissionInfo(info));
1768 bp.perm.info.packageName = tree.perm.info.packageName;
1769 bp.uid = tree.uid;
1770 if (added) {
1771 mSettings.mPermissions.put(info.name, bp);
1772 }
1773 if (changed) {
1774 if (!async) {
1775 mSettings.writeLP();
1776 } else {
1777 scheduleWriteSettingsLocked();
1778 }
1779 }
1780 return added;
1781 }
1782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 public boolean addPermission(PermissionInfo info) {
1784 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001785 return addPermissionLocked(info, false);
1786 }
1787 }
1788
1789 public boolean addPermissionAsync(PermissionInfo info) {
1790 synchronized (mPackages) {
1791 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 }
1793 }
1794
1795 public void removePermission(String name) {
1796 synchronized (mPackages) {
1797 checkPermissionTreeLP(name);
1798 BasePermission bp = mSettings.mPermissions.get(name);
1799 if (bp != null) {
1800 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1801 throw new SecurityException(
1802 "Not allowed to modify non-dynamic permission "
1803 + name);
1804 }
1805 mSettings.mPermissions.remove(name);
1806 mSettings.writeLP();
1807 }
1808 }
1809 }
1810
Dianne Hackborn854060af2009-07-09 18:14:31 -07001811 public boolean isProtectedBroadcast(String actionName) {
1812 synchronized (mPackages) {
1813 return mProtectedBroadcasts.contains(actionName);
1814 }
1815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 public int checkSignatures(String pkg1, String pkg2) {
1818 synchronized (mPackages) {
1819 PackageParser.Package p1 = mPackages.get(pkg1);
1820 PackageParser.Package p2 = mPackages.get(pkg2);
1821 if (p1 == null || p1.mExtras == null
1822 || p2 == null || p2.mExtras == null) {
1823 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1824 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001825 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827 }
1828
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001829 public int checkUidSignatures(int uid1, int uid2) {
1830 synchronized (mPackages) {
1831 Signature[] s1;
1832 Signature[] s2;
1833 Object obj = mSettings.getUserIdLP(uid1);
1834 if (obj != null) {
1835 if (obj instanceof SharedUserSetting) {
1836 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1837 } else if (obj instanceof PackageSetting) {
1838 s1 = ((PackageSetting)obj).signatures.mSignatures;
1839 } else {
1840 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1841 }
1842 } else {
1843 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1844 }
1845 obj = mSettings.getUserIdLP(uid2);
1846 if (obj != null) {
1847 if (obj instanceof SharedUserSetting) {
1848 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1849 } else if (obj instanceof PackageSetting) {
1850 s2 = ((PackageSetting)obj).signatures.mSignatures;
1851 } else {
1852 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1853 }
1854 } else {
1855 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1856 }
1857 return checkSignaturesLP(s1, s2);
1858 }
1859 }
1860
1861 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1862 if (s1 == null) {
1863 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1865 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1866 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001867 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1869 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001870 HashSet<Signature> set1 = new HashSet<Signature>();
1871 for (Signature sig : s1) {
1872 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001874 HashSet<Signature> set2 = new HashSet<Signature>();
1875 for (Signature sig : s2) {
1876 set2.add(sig);
1877 }
1878 // Make sure s2 contains all signatures in s1.
1879 if (set1.equals(set2)) {
1880 return PackageManager.SIGNATURE_MATCH;
1881 }
1882 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
1884
1885 public String[] getPackagesForUid(int uid) {
1886 synchronized (mPackages) {
1887 Object obj = mSettings.getUserIdLP(uid);
1888 if (obj instanceof SharedUserSetting) {
1889 SharedUserSetting sus = (SharedUserSetting)obj;
1890 final int N = sus.packages.size();
1891 String[] res = new String[N];
1892 Iterator<PackageSetting> it = sus.packages.iterator();
1893 int i=0;
1894 while (it.hasNext()) {
1895 res[i++] = it.next().name;
1896 }
1897 return res;
1898 } else if (obj instanceof PackageSetting) {
1899 PackageSetting ps = (PackageSetting)obj;
1900 return new String[] { ps.name };
1901 }
1902 }
1903 return null;
1904 }
1905
1906 public String getNameForUid(int uid) {
1907 synchronized (mPackages) {
1908 Object obj = mSettings.getUserIdLP(uid);
1909 if (obj instanceof SharedUserSetting) {
1910 SharedUserSetting sus = (SharedUserSetting)obj;
1911 return sus.name + ":" + sus.userId;
1912 } else if (obj instanceof PackageSetting) {
1913 PackageSetting ps = (PackageSetting)obj;
1914 return ps.name;
1915 }
1916 }
1917 return null;
1918 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 public int getUidForSharedUser(String sharedUserName) {
1921 if(sharedUserName == null) {
1922 return -1;
1923 }
1924 synchronized (mPackages) {
1925 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1926 if(suid == null) {
1927 return -1;
1928 }
1929 return suid.userId;
1930 }
1931 }
1932
1933 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1934 int flags) {
1935 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001936 return chooseBestActivity(intent, resolvedType, flags, query);
1937 }
1938
Mihai Predaeae850c2009-05-13 10:13:48 +02001939 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1940 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 if (query != null) {
1942 final int N = query.size();
1943 if (N == 1) {
1944 return query.get(0);
1945 } else if (N > 1) {
1946 // If there is more than one activity with the same priority,
1947 // then let the user decide between them.
1948 ResolveInfo r0 = query.get(0);
1949 ResolveInfo r1 = query.get(1);
1950 if (false) {
1951 System.out.println(r0.activityInfo.name +
1952 "=" + r0.priority + " vs " +
1953 r1.activityInfo.name +
1954 "=" + r1.priority);
1955 }
1956 // If the first activity has a higher priority, or a different
1957 // default, then it is always desireable to pick it.
1958 if (r0.priority != r1.priority
1959 || r0.preferredOrder != r1.preferredOrder
1960 || r0.isDefault != r1.isDefault) {
1961 return query.get(0);
1962 }
1963 // If we have saved a preference for a preferred activity for
1964 // this Intent, use that.
1965 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1966 flags, query, r0.priority);
1967 if (ri != null) {
1968 return ri;
1969 }
1970 return mResolveInfo;
1971 }
1972 }
1973 return null;
1974 }
1975
1976 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1977 int flags, List<ResolveInfo> query, int priority) {
1978 synchronized (mPackages) {
1979 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1980 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001981 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1983 if (prefs != null && prefs.size() > 0) {
1984 // First figure out how good the original match set is.
1985 // We will only allow preferred activities that came
1986 // from the same match quality.
1987 int match = 0;
1988 final int N = query.size();
1989 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1990 for (int j=0; j<N; j++) {
1991 ResolveInfo ri = query.get(j);
1992 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1993 + ": 0x" + Integer.toHexString(match));
1994 if (ri.match > match) match = ri.match;
1995 }
1996 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1997 + Integer.toHexString(match));
1998 match &= IntentFilter.MATCH_CATEGORY_MASK;
1999 final int M = prefs.size();
2000 for (int i=0; i<M; i++) {
2001 PreferredActivity pa = prefs.get(i);
2002 if (pa.mMatch != match) {
2003 continue;
2004 }
2005 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2006 if (DEBUG_PREFERRED) {
2007 Log.v(TAG, "Got preferred activity:");
2008 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
2009 }
2010 if (ai != null) {
2011 for (int j=0; j<N; j++) {
2012 ResolveInfo ri = query.get(j);
2013 if (!ri.activityInfo.applicationInfo.packageName
2014 .equals(ai.applicationInfo.packageName)) {
2015 continue;
2016 }
2017 if (!ri.activityInfo.name.equals(ai.name)) {
2018 continue;
2019 }
2020
2021 // Okay we found a previously set preferred app.
2022 // If the result set is different from when this
2023 // was created, we need to clear it and re-ask the
2024 // user their preference.
2025 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002026 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 + intent + " type " + resolvedType);
2028 mSettings.mPreferredActivities.removeFilter(pa);
2029 return null;
2030 }
2031
2032 // Yay!
2033 return ri;
2034 }
2035 }
2036 }
2037 }
2038 }
2039 return null;
2040 }
2041
2042 public List<ResolveInfo> queryIntentActivities(Intent intent,
2043 String resolvedType, int flags) {
2044 ComponentName comp = intent.getComponent();
2045 if (comp != null) {
2046 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2047 ActivityInfo ai = getActivityInfo(comp, flags);
2048 if (ai != null) {
2049 ResolveInfo ri = new ResolveInfo();
2050 ri.activityInfo = ai;
2051 list.add(ri);
2052 }
2053 return list;
2054 }
2055
2056 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002057 String pkgName = intent.getPackage();
2058 if (pkgName == null) {
2059 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2060 resolvedType, flags);
2061 }
2062 PackageParser.Package pkg = mPackages.get(pkgName);
2063 if (pkg != null) {
2064 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2065 resolvedType, flags, pkg.activities);
2066 }
2067 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 }
2069 }
2070
2071 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2072 Intent[] specifics, String[] specificTypes, Intent intent,
2073 String resolvedType, int flags) {
2074 final String resultsAction = intent.getAction();
2075
2076 List<ResolveInfo> results = queryIntentActivities(
2077 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2078 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2079
2080 int specificsPos = 0;
2081 int N;
2082
2083 // todo: note that the algorithm used here is O(N^2). This
2084 // isn't a problem in our current environment, but if we start running
2085 // into situations where we have more than 5 or 10 matches then this
2086 // should probably be changed to something smarter...
2087
2088 // First we go through and resolve each of the specific items
2089 // that were supplied, taking care of removing any corresponding
2090 // duplicate items in the generic resolve list.
2091 if (specifics != null) {
2092 for (int i=0; i<specifics.length; i++) {
2093 final Intent sintent = specifics[i];
2094 if (sintent == null) {
2095 continue;
2096 }
2097
2098 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2099 String action = sintent.getAction();
2100 if (resultsAction != null && resultsAction.equals(action)) {
2101 // If this action was explicitly requested, then don't
2102 // remove things that have it.
2103 action = null;
2104 }
2105 ComponentName comp = sintent.getComponent();
2106 ResolveInfo ri = null;
2107 ActivityInfo ai = null;
2108 if (comp == null) {
2109 ri = resolveIntent(
2110 sintent,
2111 specificTypes != null ? specificTypes[i] : null,
2112 flags);
2113 if (ri == null) {
2114 continue;
2115 }
2116 if (ri == mResolveInfo) {
2117 // ACK! Must do something better with this.
2118 }
2119 ai = ri.activityInfo;
2120 comp = new ComponentName(ai.applicationInfo.packageName,
2121 ai.name);
2122 } else {
2123 ai = getActivityInfo(comp, flags);
2124 if (ai == null) {
2125 continue;
2126 }
2127 }
2128
2129 // Look for any generic query activities that are duplicates
2130 // of this specific one, and remove them from the results.
2131 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2132 N = results.size();
2133 int j;
2134 for (j=specificsPos; j<N; j++) {
2135 ResolveInfo sri = results.get(j);
2136 if ((sri.activityInfo.name.equals(comp.getClassName())
2137 && sri.activityInfo.applicationInfo.packageName.equals(
2138 comp.getPackageName()))
2139 || (action != null && sri.filter.matchAction(action))) {
2140 results.remove(j);
2141 if (Config.LOGV) Log.v(
2142 TAG, "Removing duplicate item from " + j
2143 + " due to specific " + specificsPos);
2144 if (ri == null) {
2145 ri = sri;
2146 }
2147 j--;
2148 N--;
2149 }
2150 }
2151
2152 // Add this specific item to its proper place.
2153 if (ri == null) {
2154 ri = new ResolveInfo();
2155 ri.activityInfo = ai;
2156 }
2157 results.add(specificsPos, ri);
2158 ri.specificIndex = i;
2159 specificsPos++;
2160 }
2161 }
2162
2163 // Now we go through the remaining generic results and remove any
2164 // duplicate actions that are found here.
2165 N = results.size();
2166 for (int i=specificsPos; i<N-1; i++) {
2167 final ResolveInfo rii = results.get(i);
2168 if (rii.filter == null) {
2169 continue;
2170 }
2171
2172 // Iterate over all of the actions of this result's intent
2173 // filter... typically this should be just one.
2174 final Iterator<String> it = rii.filter.actionsIterator();
2175 if (it == null) {
2176 continue;
2177 }
2178 while (it.hasNext()) {
2179 final String action = it.next();
2180 if (resultsAction != null && resultsAction.equals(action)) {
2181 // If this action was explicitly requested, then don't
2182 // remove things that have it.
2183 continue;
2184 }
2185 for (int j=i+1; j<N; j++) {
2186 final ResolveInfo rij = results.get(j);
2187 if (rij.filter != null && rij.filter.hasAction(action)) {
2188 results.remove(j);
2189 if (Config.LOGV) Log.v(
2190 TAG, "Removing duplicate item from " + j
2191 + " due to action " + action + " at " + i);
2192 j--;
2193 N--;
2194 }
2195 }
2196 }
2197
2198 // If the caller didn't request filter information, drop it now
2199 // so we don't have to marshall/unmarshall it.
2200 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2201 rii.filter = null;
2202 }
2203 }
2204
2205 // Filter out the caller activity if so requested.
2206 if (caller != null) {
2207 N = results.size();
2208 for (int i=0; i<N; i++) {
2209 ActivityInfo ainfo = results.get(i).activityInfo;
2210 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2211 && caller.getClassName().equals(ainfo.name)) {
2212 results.remove(i);
2213 break;
2214 }
2215 }
2216 }
2217
2218 // If the caller didn't request filter information,
2219 // drop them now so we don't have to
2220 // marshall/unmarshall it.
2221 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2222 N = results.size();
2223 for (int i=0; i<N; i++) {
2224 results.get(i).filter = null;
2225 }
2226 }
2227
2228 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2229 return results;
2230 }
2231
2232 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2233 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002234 ComponentName comp = intent.getComponent();
2235 if (comp != null) {
2236 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2237 ActivityInfo ai = getReceiverInfo(comp, flags);
2238 if (ai != null) {
2239 ResolveInfo ri = new ResolveInfo();
2240 ri.activityInfo = ai;
2241 list.add(ri);
2242 }
2243 return list;
2244 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002247 String pkgName = intent.getPackage();
2248 if (pkgName == null) {
2249 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2250 resolvedType, flags);
2251 }
2252 PackageParser.Package pkg = mPackages.get(pkgName);
2253 if (pkg != null) {
2254 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2255 resolvedType, flags, pkg.receivers);
2256 }
2257 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 }
2259 }
2260
2261 public ResolveInfo resolveService(Intent intent, String resolvedType,
2262 int flags) {
2263 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2264 flags);
2265 if (query != null) {
2266 if (query.size() >= 1) {
2267 // If there is more than one service with the same priority,
2268 // just arbitrarily pick the first one.
2269 return query.get(0);
2270 }
2271 }
2272 return null;
2273 }
2274
2275 public List<ResolveInfo> queryIntentServices(Intent intent,
2276 String resolvedType, int flags) {
2277 ComponentName comp = intent.getComponent();
2278 if (comp != null) {
2279 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2280 ServiceInfo si = getServiceInfo(comp, flags);
2281 if (si != null) {
2282 ResolveInfo ri = new ResolveInfo();
2283 ri.serviceInfo = si;
2284 list.add(ri);
2285 }
2286 return list;
2287 }
2288
2289 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002290 String pkgName = intent.getPackage();
2291 if (pkgName == null) {
2292 return (List<ResolveInfo>)mServices.queryIntent(intent,
2293 resolvedType, flags);
2294 }
2295 PackageParser.Package pkg = mPackages.get(pkgName);
2296 if (pkg != null) {
2297 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2298 resolvedType, flags, pkg.services);
2299 }
2300 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301 }
2302 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 public List<PackageInfo> getInstalledPackages(int flags) {
2305 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2306
2307 synchronized (mPackages) {
2308 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2309 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2310 while (i.hasNext()) {
2311 final PackageSetting ps = i.next();
2312 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2313 if(psPkg != null) {
2314 finalList.add(psPkg);
2315 }
2316 }
2317 }
2318 else {
2319 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2320 while (i.hasNext()) {
2321 final PackageParser.Package p = i.next();
2322 if (p.applicationInfo != null) {
2323 PackageInfo pi = generatePackageInfo(p, flags);
2324 if(pi != null) {
2325 finalList.add(pi);
2326 }
2327 }
2328 }
2329 }
2330 }
2331 return finalList;
2332 }
2333
2334 public List<ApplicationInfo> getInstalledApplications(int flags) {
2335 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2336 synchronized(mPackages) {
2337 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2338 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2339 while (i.hasNext()) {
2340 final PackageSetting ps = i.next();
2341 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2342 if(ai != null) {
2343 finalList.add(ai);
2344 }
2345 }
2346 }
2347 else {
2348 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2349 while (i.hasNext()) {
2350 final PackageParser.Package p = i.next();
2351 if (p.applicationInfo != null) {
2352 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2353 if(ai != null) {
2354 finalList.add(ai);
2355 }
2356 }
2357 }
2358 }
2359 }
2360 return finalList;
2361 }
2362
2363 public List<ApplicationInfo> getPersistentApplications(int flags) {
2364 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2365
2366 synchronized (mPackages) {
2367 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2368 while (i.hasNext()) {
2369 PackageParser.Package p = i.next();
2370 if (p.applicationInfo != null
2371 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2372 && (!mSafeMode || (p.applicationInfo.flags
2373 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2374 finalList.add(p.applicationInfo);
2375 }
2376 }
2377 }
2378
2379 return finalList;
2380 }
2381
2382 public ProviderInfo resolveContentProvider(String name, int flags) {
2383 synchronized (mPackages) {
2384 final PackageParser.Provider provider = mProviders.get(name);
2385 return provider != null
2386 && mSettings.isEnabledLP(provider.info, flags)
2387 && (!mSafeMode || (provider.info.applicationInfo.flags
2388 &ApplicationInfo.FLAG_SYSTEM) != 0)
2389 ? PackageParser.generateProviderInfo(provider, flags)
2390 : null;
2391 }
2392 }
2393
Fred Quintana718d8a22009-04-29 17:53:20 -07002394 /**
2395 * @deprecated
2396 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 public void querySyncProviders(List outNames, List outInfo) {
2398 synchronized (mPackages) {
2399 Iterator<Map.Entry<String, PackageParser.Provider>> i
2400 = mProviders.entrySet().iterator();
2401
2402 while (i.hasNext()) {
2403 Map.Entry<String, PackageParser.Provider> entry = i.next();
2404 PackageParser.Provider p = entry.getValue();
2405
2406 if (p.syncable
2407 && (!mSafeMode || (p.info.applicationInfo.flags
2408 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2409 outNames.add(entry.getKey());
2410 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2411 }
2412 }
2413 }
2414 }
2415
2416 public List<ProviderInfo> queryContentProviders(String processName,
2417 int uid, int flags) {
2418 ArrayList<ProviderInfo> finalList = null;
2419
2420 synchronized (mPackages) {
2421 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2422 while (i.hasNext()) {
2423 PackageParser.Provider p = i.next();
2424 if (p.info.authority != null
2425 && (processName == null ||
2426 (p.info.processName.equals(processName)
2427 && p.info.applicationInfo.uid == uid))
2428 && mSettings.isEnabledLP(p.info, flags)
2429 && (!mSafeMode || (p.info.applicationInfo.flags
2430 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2431 if (finalList == null) {
2432 finalList = new ArrayList<ProviderInfo>(3);
2433 }
2434 finalList.add(PackageParser.generateProviderInfo(p,
2435 flags));
2436 }
2437 }
2438 }
2439
2440 if (finalList != null) {
2441 Collections.sort(finalList, mProviderInitOrderSorter);
2442 }
2443
2444 return finalList;
2445 }
2446
2447 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2448 int flags) {
2449 synchronized (mPackages) {
2450 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2451 return PackageParser.generateInstrumentationInfo(i, flags);
2452 }
2453 }
2454
2455 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2456 int flags) {
2457 ArrayList<InstrumentationInfo> finalList =
2458 new ArrayList<InstrumentationInfo>();
2459
2460 synchronized (mPackages) {
2461 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2462 while (i.hasNext()) {
2463 PackageParser.Instrumentation p = i.next();
2464 if (targetPackage == null
2465 || targetPackage.equals(p.info.targetPackage)) {
2466 finalList.add(PackageParser.generateInstrumentationInfo(p,
2467 flags));
2468 }
2469 }
2470 }
2471
2472 return finalList;
2473 }
2474
2475 private void scanDirLI(File dir, int flags, int scanMode) {
2476 Log.d(TAG, "Scanning app dir " + dir);
2477
2478 String[] files = dir.list();
2479
2480 int i;
2481 for (i=0; i<files.length; i++) {
2482 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002483 if (!isPackageFilename(files[i])) {
2484 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002485 continue;
2486 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002487 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002489 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002490 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2491 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002492 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002493 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002494 file.delete();
2495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 }
2497 }
2498
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002499 private static File getSettingsProblemFile() {
2500 File dataDir = Environment.getDataDirectory();
2501 File systemDir = new File(dataDir, "system");
2502 File fname = new File(systemDir, "uiderrors.txt");
2503 return fname;
2504 }
2505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 private static void reportSettingsProblem(int priority, String msg) {
2507 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002508 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 FileOutputStream out = new FileOutputStream(fname, true);
2510 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002511 SimpleDateFormat formatter = new SimpleDateFormat();
2512 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2513 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 pw.close();
2515 FileUtils.setPermissions(
2516 fname.toString(),
2517 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2518 -1, -1);
2519 } catch (java.io.IOException e) {
2520 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002521 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 }
2523
2524 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2525 PackageParser.Package pkg, File srcFile, int parseFlags) {
2526 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002527 if (ps != null
2528 && ps.codePath.equals(srcFile)
2529 && ps.getTimeStamp() == srcFile.lastModified()) {
2530 if (ps.signatures.mSignatures != null
2531 && ps.signatures.mSignatures.length != 0) {
2532 // Optimization: reuse the existing cached certificates
2533 // if the package appears to be unchanged.
2534 pkg.mSignatures = ps.signatures.mSignatures;
2535 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 }
Jeff Browne7600722010-04-07 18:28:23 -07002537
2538 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002539 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002540 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2541 }
2542
2543 if (!pp.collectCertificates(pkg, parseFlags)) {
2544 mLastScanError = pp.getParseError();
2545 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 }
2547 }
2548 return true;
2549 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 /*
2552 * Scan a package and return the newly parsed package.
2553 * Returns null in case of errors and the error code is stored in mLastScanError
2554 */
2555 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002556 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002558 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002560 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002563 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 if (pkg == null) {
2565 mLastScanError = pp.getParseError();
2566 return null;
2567 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002568 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 PackageSetting updatedPkg;
2570 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002571 // Look to see if we already know about this package.
2572 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002573 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002574 // This package has been renamed to its original name. Let's
2575 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002576 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002577 }
2578 // If there was no original package, see one for the real package name.
2579 if (ps == null) {
2580 ps = mSettings.peekPackageLP(pkg.packageName);
2581 }
2582 // Check to see if this package could be hiding/updating a system
2583 // package. Must look for it either under the original or real
2584 // package name depending on our state.
2585 updatedPkg = mSettings.mDisabledSysPackages.get(
2586 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002588 // First check if this is a system package that may involve an update
2589 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2590 if (!ps.codePath.equals(scanFile)) {
2591 // The path has changed from what was last scanned... check the
2592 // version of the new path against what we have stored to determine
2593 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002594 if (pkg.mVersionCode < ps.versionCode) {
2595 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002596 // Ignore entry. Skip it.
2597 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2598 + "ignored: updated version " + ps.versionCode
2599 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002600 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2601 return null;
2602 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002603 // The current app on the system partion is better than
2604 // what we have updated to on the data partition; switch
2605 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002606 // At this point, its safely assumed that package installation for
2607 // apps in system partition will go through. If not there won't be a working
2608 // version of the app
2609 synchronized (mPackages) {
2610 // Just remove the loaded entries from package lists.
2611 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002612 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002613 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002614 + "reverting from " + ps.codePathString
2615 + ": new version " + pkg.mVersionCode
2616 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002617 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2618 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002619 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 }
2622 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002623 if (updatedPkg != null) {
2624 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2625 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2626 }
2627 // Verify certificates against what was last scanned
2628 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002629 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002630 return null;
2631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 // The apk is forward locked (not public) if its code and resources
2633 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002634 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002636 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002637 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002638
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002639 String codePath = null;
2640 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002641 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2642 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002643 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002644 } else {
2645 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002646 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002647 }
2648 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002649 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002650 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002651 codePath = pkg.mScanPath;
2652 // Set application objects path explicitly.
2653 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002655 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 }
2657
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002658 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2659 String destCodePath, String destResPath) {
2660 pkg.mPath = pkg.mScanPath = destCodePath;
2661 pkg.applicationInfo.sourceDir = destCodePath;
2662 pkg.applicationInfo.publicSourceDir = destResPath;
2663 }
2664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 private static String fixProcessName(String defProcessName,
2666 String processName, int uid) {
2667 if (processName == null) {
2668 return defProcessName;
2669 }
2670 return processName;
2671 }
2672
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002673 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002674 PackageParser.Package pkg) {
2675 if (pkgSetting.signatures.mSignatures != null) {
2676 // Already existing package. Make sure signatures match
2677 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2678 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002679 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002680 + " signatures do not match the previously installed version; ignoring!");
2681 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 return false;
2683 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002684 }
2685 // Check for shared user signatures
2686 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2687 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2688 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2689 Slog.e(TAG, "Package " + pkg.packageName
2690 + " has no signatures that match those in shared user "
2691 + pkgSetting.sharedUser.name + "; ignoring!");
2692 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2693 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 }
2696 return true;
2697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002698
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002699 public boolean performDexOpt(String packageName) {
2700 if (!mNoDexOpt) {
2701 return false;
2702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002703
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002704 PackageParser.Package p;
2705 synchronized (mPackages) {
2706 p = mPackages.get(packageName);
2707 if (p == null || p.mDidDexOpt) {
2708 return false;
2709 }
2710 }
2711 synchronized (mInstallLock) {
2712 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2713 }
2714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002715
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002716 static final int DEX_OPT_SKIPPED = 0;
2717 static final int DEX_OPT_PERFORMED = 1;
2718 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002719
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002720 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2721 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002722 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002723 String path = pkg.mScanPath;
2724 int ret = 0;
2725 try {
2726 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002727 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002728 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002729 pkg.mDidDexOpt = true;
2730 performed = true;
2731 }
2732 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002733 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002734 ret = -1;
2735 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002736 Slog.w(TAG, "IOException reading apk: " + path, e);
2737 ret = -1;
2738 } catch (dalvik.system.StaleDexCacheError e) {
2739 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2740 ret = -1;
2741 } catch (Exception e) {
2742 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002743 ret = -1;
2744 }
2745 if (ret < 0) {
2746 //error from installer
2747 return DEX_OPT_FAILED;
2748 }
2749 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002750
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002751 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2752 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002753
2754 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2755 return Environment.isEncryptedFilesystemEnabled() &&
2756 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2757 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002758
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002759 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2760 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002761 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002762 + " to " + newPkg.packageName
2763 + ": old package not in system partition");
2764 return false;
2765 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002766 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002767 + " to " + newPkg.packageName
2768 + ": old package still exists");
2769 return false;
2770 }
2771 return true;
2772 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002773
2774 private File getDataPathForPackage(PackageParser.Package pkg) {
2775 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2776 File dataPath;
2777 if (useEncryptedFSDir) {
2778 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2779 } else {
2780 dataPath = new File(mAppDataDir, pkg.packageName);
2781 }
2782 return dataPath;
2783 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002784
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002785 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2786 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002787 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002788 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2789 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002790 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002791 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002792 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2793 return null;
2794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 mScanningPath = scanFile;
2796 if (pkg == null) {
2797 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2798 return null;
2799 }
2800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2802 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2803 }
2804
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002805 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 synchronized (mPackages) {
2807 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002808 Slog.w(TAG, "*************************************************");
2809 Slog.w(TAG, "Core android package being redefined. Skipping.");
2810 Slog.w(TAG, " file=" + mScanningPath);
2811 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2813 return null;
2814 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 // Set up information for our fall-back user intent resolution
2817 // activity.
2818 mPlatformPackage = pkg;
2819 pkg.mVersionCode = mSdkVersion;
2820 mAndroidApplication = pkg.applicationInfo;
2821 mResolveActivity.applicationInfo = mAndroidApplication;
2822 mResolveActivity.name = ResolverActivity.class.getName();
2823 mResolveActivity.packageName = mAndroidApplication.packageName;
2824 mResolveActivity.processName = mAndroidApplication.processName;
2825 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2826 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2827 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2828 mResolveActivity.exported = true;
2829 mResolveActivity.enabled = true;
2830 mResolveInfo.activityInfo = mResolveActivity;
2831 mResolveInfo.priority = 0;
2832 mResolveInfo.preferredOrder = 0;
2833 mResolveInfo.match = 0;
2834 mResolveComponentName = new ComponentName(
2835 mAndroidApplication.packageName, mResolveActivity.name);
2836 }
2837 }
2838
2839 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002840 TAG, "Scanning package " + pkg.packageName);
2841 if (mPackages.containsKey(pkg.packageName)
2842 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002843 Slog.w(TAG, "*************************************************");
2844 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002846 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2848 return null;
2849 }
2850
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002851 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002852 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2853 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 SharedUserSetting suid = null;
2856 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002857
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002858 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2859 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002860 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002861 pkg.mRealPackage = null;
2862 pkg.mAdoptPermissions = null;
2863 }
2864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 synchronized (mPackages) {
2866 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002867 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2868 if (mTmpSharedLibraries == null ||
2869 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2870 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2871 }
2872 int num = 0;
2873 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2874 for (int i=0; i<N; i++) {
2875 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002877 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002879 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2881 return null;
2882 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002883 mTmpSharedLibraries[num] = file;
2884 num++;
2885 }
2886 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2887 for (int i=0; i<N; i++) {
2888 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2889 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002890 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002891 + " desires unavailable shared library "
2892 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2893 } else {
2894 mTmpSharedLibraries[num] = file;
2895 num++;
2896 }
2897 }
2898 if (num > 0) {
2899 pkg.usesLibraryFiles = new String[num];
2900 System.arraycopy(mTmpSharedLibraries, 0,
2901 pkg.usesLibraryFiles, 0, num);
2902 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002903
Dianne Hackborn49237342009-08-27 20:08:01 -07002904 if (pkg.reqFeatures != null) {
2905 N = pkg.reqFeatures.size();
2906 for (int i=0; i<N; i++) {
2907 FeatureInfo fi = pkg.reqFeatures.get(i);
2908 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2909 // Don't care.
2910 continue;
2911 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002912
Dianne Hackborn49237342009-08-27 20:08:01 -07002913 if (fi.name != null) {
2914 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002915 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002916 + " requires unavailable feature "
2917 + fi.name + "; failing!");
2918 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2919 return null;
2920 }
2921 }
2922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 }
2924 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 if (pkg.mSharedUserId != null) {
2927 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2928 pkg.applicationInfo.flags, true);
2929 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002930 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 + " for shared user failed");
2932 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2933 return null;
2934 }
2935 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2936 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2937 + suid.userId + "): packages=" + suid.packages);
2938 }
2939 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002940
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002941 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002942 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002943 Log.w(TAG, "WAITING FOR DEBUGGER");
2944 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002945 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2946 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002947 }
2948 }
2949
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002950 // Check if we are renaming from an original package name.
2951 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002952 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002953 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002954 // This package may need to be renamed to a previously
2955 // installed name. Let's check on that...
2956 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002957 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002958 // This package had originally been installed as the
2959 // original name, and we have already taken care of
2960 // transitioning to the new one. Just update the new
2961 // one to continue using the old name.
2962 realName = pkg.mRealPackage;
2963 if (!pkg.packageName.equals(renamed)) {
2964 // Callers into this function may have already taken
2965 // care of renaming the package; only do it here if
2966 // it is not already done.
2967 pkg.setPackageName(renamed);
2968 }
2969
Dianne Hackbornc1552392010-03-03 16:19:01 -08002970 } else {
2971 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2972 if ((origPackage=mSettings.peekPackageLP(
2973 pkg.mOriginalPackages.get(i))) != null) {
2974 // We do have the package already installed under its
2975 // original name... should we use it?
2976 if (!verifyPackageUpdate(origPackage, pkg)) {
2977 // New package is not compatible with original.
2978 origPackage = null;
2979 continue;
2980 } else if (origPackage.sharedUser != null) {
2981 // Make sure uid is compatible between packages.
2982 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002983 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002984 + " to " + pkg.packageName + ": old uid "
2985 + origPackage.sharedUser.name
2986 + " differs from " + pkg.mSharedUserId);
2987 origPackage = null;
2988 continue;
2989 }
2990 } else {
2991 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2992 + pkg.packageName + " to old name " + origPackage.name);
2993 }
2994 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002995 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002996 }
2997 }
2998 }
2999
3000 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003001 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003002 + " was transferred to another, but its .apk remains");
3003 }
3004
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003005 // Just create the setting, don't add it yet. For already existing packages
3006 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003007 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 destResourceFile, pkg.applicationInfo.flags, true, false);
3009 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003010 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3012 return null;
3013 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003014
3015 if (pkgSetting.origPackage != null) {
3016 // If we are first transitioning from an original package,
3017 // fix up the new package's name now. We need to do this after
3018 // looking up the package under its new name, so getPackageLP
3019 // can take care of fiddling things correctly.
3020 pkg.setPackageName(origPackage.name);
3021
3022 // File a report about this.
3023 String msg = "New package " + pkgSetting.realName
3024 + " renamed to replace old package " + pkgSetting.name;
3025 reportSettingsProblem(Log.WARN, msg);
3026
3027 // Make a note of it.
3028 mTransferedPackages.add(origPackage.name);
3029
3030 // No longer need to retain this.
3031 pkgSetting.origPackage = null;
3032 }
3033
3034 if (realName != null) {
3035 // Make a note of it.
3036 mTransferedPackages.add(pkg.packageName);
3037 }
3038
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003039 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3041 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 pkg.applicationInfo.uid = pkgSetting.userId;
3044 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003045
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003046 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003047 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 return null;
3049 }
3050 // The signature has changed, but this package is in the system
3051 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003052 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053 // However... if this package is part of a shared user, but it
3054 // doesn't match the signature of the shared user, let's fail.
3055 // What this means is that you can't change the signatures
3056 // associated with an overall shared user, which doesn't seem all
3057 // that unreasonable.
3058 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003059 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3060 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3061 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3063 return null;
3064 }
3065 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003066 // File a report about this.
3067 String msg = "System package " + pkg.packageName
3068 + " signature changed; retaining data.";
3069 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003071
The Android Open Source Project10592532009-03-18 17:39:46 -07003072 // Verify that this new package doesn't have any content providers
3073 // that conflict with existing packages. Only do this if the
3074 // package isn't already installed, since we don't want to break
3075 // things that are installed.
3076 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3077 int N = pkg.providers.size();
3078 int i;
3079 for (i=0; i<N; i++) {
3080 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003081 if (p.info.authority != null) {
3082 String names[] = p.info.authority.split(";");
3083 for (int j = 0; j < names.length; j++) {
3084 if (mProviders.containsKey(names[j])) {
3085 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003086 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003087 " (in package " + pkg.applicationInfo.packageName +
3088 ") is already used by "
3089 + ((other != null && other.getComponentName() != null)
3090 ? other.getComponentName().getPackageName() : "?"));
3091 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3092 return null;
3093 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003094 }
3095 }
3096 }
3097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 }
3099
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003100 final String pkgName = pkg.packageName;
3101
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003102 if (pkg.mAdoptPermissions != null) {
3103 // This package wants to adopt ownership of permissions from
3104 // another package.
3105 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3106 String origName = pkg.mAdoptPermissions.get(i);
3107 PackageSetting orig = mSettings.peekPackageLP(origName);
3108 if (orig != null) {
3109 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003110 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003111 + origName + " to " + pkg.packageName);
3112 mSettings.transferPermissions(origName, pkg.packageName);
3113 }
3114 }
3115 }
3116 }
3117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 long scanFileTime = scanFile.lastModified();
3119 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3120 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3121 pkg.applicationInfo.processName = fixProcessName(
3122 pkg.applicationInfo.packageName,
3123 pkg.applicationInfo.processName,
3124 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125
3126 File dataPath;
3127 if (mPlatformPackage == pkg) {
3128 // The system package is special.
3129 dataPath = new File (Environment.getDataDirectory(), "system");
3130 pkg.applicationInfo.dataDir = dataPath.getPath();
3131 } else {
3132 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003133 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003134 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003135
3136 boolean uidError = false;
3137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 if (dataPath.exists()) {
3139 mOutPermissions[1] = 0;
3140 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3141 if (mOutPermissions[1] == pkg.applicationInfo.uid
3142 || !Process.supportsProcesses()) {
3143 pkg.applicationInfo.dataDir = dataPath.getPath();
3144 } else {
3145 boolean recovered = false;
3146 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3147 // If this is a system app, we can at least delete its
3148 // current data so the application will still work.
3149 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003150 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003151 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003152 // Old data gone!
3153 String msg = "System package " + pkg.packageName
3154 + " has changed from uid: "
3155 + mOutPermissions[1] + " to "
3156 + pkg.applicationInfo.uid + "; old data erased";
3157 reportSettingsProblem(Log.WARN, msg);
3158 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003161 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 pkg.applicationInfo.uid);
3163 if (ret == -1) {
3164 // Ack should not happen!
3165 msg = "System package " + pkg.packageName
3166 + " could not have data directory re-created after delete.";
3167 reportSettingsProblem(Log.WARN, msg);
3168 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3169 return null;
3170 }
3171 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 if (!recovered) {
3174 mHasSystemUidErrors = true;
3175 }
3176 }
3177 if (!recovered) {
3178 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3179 + pkg.applicationInfo.uid + "/fs_"
3180 + mOutPermissions[1];
3181 String msg = "Package " + pkg.packageName
3182 + " has mismatched uid: "
3183 + mOutPermissions[1] + " on disk, "
3184 + pkg.applicationInfo.uid + " in settings";
3185 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003186 mSettings.mReadMessages.append(msg);
3187 mSettings.mReadMessages.append('\n');
3188 uidError = true;
3189 if (!pkgSetting.uidError) {
3190 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 }
3193 }
3194 }
3195 pkg.applicationInfo.dataDir = dataPath.getPath();
3196 } else {
3197 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3198 Log.v(TAG, "Want this data dir: " + dataPath);
3199 //invoke installer to do the actual installation
3200 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003201 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 pkg.applicationInfo.uid);
3203 if(ret < 0) {
3204 // Error from installer
3205 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3206 return null;
3207 }
3208 } else {
3209 dataPath.mkdirs();
3210 if (dataPath.exists()) {
3211 FileUtils.setPermissions(
3212 dataPath.toString(),
3213 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3214 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3215 }
3216 }
3217 if (dataPath.exists()) {
3218 pkg.applicationInfo.dataDir = dataPath.getPath();
3219 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003220 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 pkg.applicationInfo.dataDir = null;
3222 }
3223 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003224
3225 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 }
3227
3228 // Perform shared library installation and dex validation and
3229 // optimization, if this is not a system app.
3230 if (mInstaller != null) {
3231 String path = scanFile.getPath();
3232 if (scanFileNewer) {
3233 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003234 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3235 if (err != PackageManager.INSTALL_SUCCEEDED) {
3236 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237 return null;
3238 }
3239 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003240 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003241
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003242 if ((scanMode&SCAN_NO_DEX) == 0) {
3243 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3245 return null;
3246 }
3247 }
3248 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 if (mFactoryTest && pkg.requestedPermissions.contains(
3251 android.Manifest.permission.FACTORY_TEST)) {
3252 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3253 }
3254
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003255 // Request the ActivityManager to kill the process(only for existing packages)
3256 // so that we do not end up in a confused state while the user is still using the older
3257 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003258 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003259 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003260 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003261 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003264 // We don't expect installation to fail beyond this point,
3265 if ((scanMode&SCAN_MONITOR) != 0) {
3266 mAppDirs.put(pkg.mPath, pkg);
3267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003269 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003271 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003272 // Make sure we don't accidentally delete its data.
3273 mSettings.mPackagesToBeCleaned.remove(pkgName);
3274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003275 int N = pkg.providers.size();
3276 StringBuilder r = null;
3277 int i;
3278 for (i=0; i<N; i++) {
3279 PackageParser.Provider p = pkg.providers.get(i);
3280 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3281 p.info.processName, pkg.applicationInfo.uid);
3282 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3283 p.info.name), p);
3284 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003285 if (p.info.authority != null) {
3286 String names[] = p.info.authority.split(";");
3287 p.info.authority = null;
3288 for (int j = 0; j < names.length; j++) {
3289 if (j == 1 && p.syncable) {
3290 // We only want the first authority for a provider to possibly be
3291 // syncable, so if we already added this provider using a different
3292 // authority clear the syncable flag. We copy the provider before
3293 // changing it because the mProviders object contains a reference
3294 // to a provider that we don't want to change.
3295 // Only do this for the second authority since the resulting provider
3296 // object can be the same for all future authorities for this provider.
3297 p = new PackageParser.Provider(p);
3298 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003300 if (!mProviders.containsKey(names[j])) {
3301 mProviders.put(names[j], p);
3302 if (p.info.authority == null) {
3303 p.info.authority = names[j];
3304 } else {
3305 p.info.authority = p.info.authority + ";" + names[j];
3306 }
3307 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3308 Log.d(TAG, "Registered content provider: " + names[j] +
3309 ", className = " + p.info.name +
3310 ", isSyncable = " + p.info.isSyncable);
3311 } else {
3312 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003313 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003314 " (in package " + pkg.applicationInfo.packageName +
3315 "): name already used by "
3316 + ((other != null && other.getComponentName() != null)
3317 ? other.getComponentName().getPackageName() : "?"));
3318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 }
3320 }
3321 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3322 if (r == null) {
3323 r = new StringBuilder(256);
3324 } else {
3325 r.append(' ');
3326 }
3327 r.append(p.info.name);
3328 }
3329 }
3330 if (r != null) {
3331 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3332 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 N = pkg.services.size();
3335 r = null;
3336 for (i=0; i<N; i++) {
3337 PackageParser.Service s = pkg.services.get(i);
3338 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3339 s.info.processName, pkg.applicationInfo.uid);
3340 mServices.addService(s);
3341 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3342 if (r == null) {
3343 r = new StringBuilder(256);
3344 } else {
3345 r.append(' ');
3346 }
3347 r.append(s.info.name);
3348 }
3349 }
3350 if (r != null) {
3351 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3352 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 N = pkg.receivers.size();
3355 r = null;
3356 for (i=0; i<N; i++) {
3357 PackageParser.Activity a = pkg.receivers.get(i);
3358 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3359 a.info.processName, pkg.applicationInfo.uid);
3360 mReceivers.addActivity(a, "receiver");
3361 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3362 if (r == null) {
3363 r = new StringBuilder(256);
3364 } else {
3365 r.append(' ');
3366 }
3367 r.append(a.info.name);
3368 }
3369 }
3370 if (r != null) {
3371 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3372 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 N = pkg.activities.size();
3375 r = null;
3376 for (i=0; i<N; i++) {
3377 PackageParser.Activity a = pkg.activities.get(i);
3378 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3379 a.info.processName, pkg.applicationInfo.uid);
3380 mActivities.addActivity(a, "activity");
3381 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3382 if (r == null) {
3383 r = new StringBuilder(256);
3384 } else {
3385 r.append(' ');
3386 }
3387 r.append(a.info.name);
3388 }
3389 }
3390 if (r != null) {
3391 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3392 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003394 N = pkg.permissionGroups.size();
3395 r = null;
3396 for (i=0; i<N; i++) {
3397 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3398 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3399 if (cur == null) {
3400 mPermissionGroups.put(pg.info.name, pg);
3401 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3402 if (r == null) {
3403 r = new StringBuilder(256);
3404 } else {
3405 r.append(' ');
3406 }
3407 r.append(pg.info.name);
3408 }
3409 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003410 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 + pg.info.packageName + " ignored: original from "
3412 + cur.info.packageName);
3413 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3414 if (r == null) {
3415 r = new StringBuilder(256);
3416 } else {
3417 r.append(' ');
3418 }
3419 r.append("DUP:");
3420 r.append(pg.info.name);
3421 }
3422 }
3423 }
3424 if (r != null) {
3425 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3426 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 N = pkg.permissions.size();
3429 r = null;
3430 for (i=0; i<N; i++) {
3431 PackageParser.Permission p = pkg.permissions.get(i);
3432 HashMap<String, BasePermission> permissionMap =
3433 p.tree ? mSettings.mPermissionTrees
3434 : mSettings.mPermissions;
3435 p.group = mPermissionGroups.get(p.info.group);
3436 if (p.info.group == null || p.group != null) {
3437 BasePermission bp = permissionMap.get(p.info.name);
3438 if (bp == null) {
3439 bp = new BasePermission(p.info.name, p.info.packageName,
3440 BasePermission.TYPE_NORMAL);
3441 permissionMap.put(p.info.name, bp);
3442 }
3443 if (bp.perm == null) {
3444 if (bp.sourcePackage == null
3445 || bp.sourcePackage.equals(p.info.packageName)) {
3446 BasePermission tree = findPermissionTreeLP(p.info.name);
3447 if (tree == null
3448 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003449 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 bp.perm = p;
3451 bp.uid = pkg.applicationInfo.uid;
3452 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3453 if (r == null) {
3454 r = new StringBuilder(256);
3455 } else {
3456 r.append(' ');
3457 }
3458 r.append(p.info.name);
3459 }
3460 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003461 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 + p.info.packageName + " ignored: base tree "
3463 + tree.name + " is from package "
3464 + tree.sourcePackage);
3465 }
3466 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003467 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 + p.info.packageName + " ignored: original from "
3469 + bp.sourcePackage);
3470 }
3471 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3472 if (r == null) {
3473 r = new StringBuilder(256);
3474 } else {
3475 r.append(' ');
3476 }
3477 r.append("DUP:");
3478 r.append(p.info.name);
3479 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003480 if (bp.perm == p) {
3481 bp.protectionLevel = p.info.protectionLevel;
3482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003484 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 + p.info.packageName + " ignored: no group "
3486 + p.group);
3487 }
3488 }
3489 if (r != null) {
3490 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3491 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493 N = pkg.instrumentation.size();
3494 r = null;
3495 for (i=0; i<N; i++) {
3496 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3497 a.info.packageName = pkg.applicationInfo.packageName;
3498 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3499 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3500 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003501 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3503 if (r == null) {
3504 r = new StringBuilder(256);
3505 } else {
3506 r.append(' ');
3507 }
3508 r.append(a.info.name);
3509 }
3510 }
3511 if (r != null) {
3512 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3513 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003514
Dianne Hackborn854060af2009-07-09 18:14:31 -07003515 if (pkg.protectedBroadcasts != null) {
3516 N = pkg.protectedBroadcasts.size();
3517 for (i=0; i<N; i++) {
3518 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3519 }
3520 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003522 pkgSetting.setTimeStamp(scanFileTime);
3523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 return pkg;
3526 }
3527
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003528 private void killApplication(String pkgName, int uid) {
3529 // Request the ActivityManager to kill the process(only for existing packages)
3530 // so that we do not end up in a confused state while the user is still using the older
3531 // version of the application while the new one gets installed.
3532 IActivityManager am = ActivityManagerNative.getDefault();
3533 if (am != null) {
3534 try {
3535 am.killApplicationWithUid(pkgName, uid);
3536 } catch (RemoteException e) {
3537 }
3538 }
3539 }
3540
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003541 // The following constants are returned by cachePackageSharedLibsForAbiLI
3542 // to indicate if native shared libraries were found in the package.
3543 // Values are:
3544 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3545 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3546 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3547 // in package (and not installed)
3548 //
3549 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3550 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3551 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003553 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3554 // and automatically copy them to /data/data/<appname>/lib if present.
3555 //
3556 // NOTE: this method may throw an IOException if the library cannot
3557 // be copied to its final destination, e.g. if there isn't enough
3558 // room left on the data partition, or a ZipException if the package
3559 // file is malformed.
3560 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003561 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3562 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003563 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3564 final String apkLib = "lib/";
3565 final int apkLibLen = apkLib.length();
3566 final int cpuAbiLen = cpuAbi.length();
3567 final String libPrefix = "lib";
3568 final int libPrefixLen = libPrefix.length();
3569 final String libSuffix = ".so";
3570 final int libSuffixLen = libSuffix.length();
3571 boolean hasNativeLibraries = false;
3572 boolean installedNativeLibraries = false;
3573
3574 // the minimum length of a valid native shared library of the form
3575 // lib/<something>/lib<name>.so.
3576 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3577
3578 ZipFile zipFile = new ZipFile(scanFile);
3579 Enumeration<ZipEntry> entries =
3580 (Enumeration<ZipEntry>) zipFile.entries();
3581
3582 while (entries.hasMoreElements()) {
3583 ZipEntry entry = entries.nextElement();
3584 // skip directories
3585 if (entry.isDirectory()) {
3586 continue;
3587 }
3588 String entryName = entry.getName();
3589
3590 // check that the entry looks like lib/<something>/lib<name>.so
3591 // here, but don't check the ABI just yet.
3592 //
3593 // - must be sufficiently long
3594 // - must end with libSuffix, i.e. ".so"
3595 // - must start with apkLib, i.e. "lib/"
3596 if (entryName.length() < minEntryLen ||
3597 !entryName.endsWith(libSuffix) ||
3598 !entryName.startsWith(apkLib) ) {
3599 continue;
3600 }
3601
3602 // file name must start with libPrefix, i.e. "lib"
3603 int lastSlash = entryName.lastIndexOf('/');
3604
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003605 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003606 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3607 continue;
3608 }
3609
3610 hasNativeLibraries = true;
3611
3612 // check the cpuAbi now, between lib/ and /lib<name>.so
3613 //
3614 if (lastSlash != apkLibLen + cpuAbiLen ||
3615 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3616 continue;
3617
3618 // extract the library file name, ensure it doesn't contain
3619 // weird characters. we're guaranteed here that it doesn't contain
3620 // a directory separator though.
3621 String libFileName = entryName.substring(lastSlash+1);
3622 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3623 continue;
3624 }
3625
3626 installedNativeLibraries = true;
3627
3628 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3629 File.separator + libFileName;
3630 File sharedLibraryFile = new File(sharedLibraryFilePath);
3631 if (! sharedLibraryFile.exists() ||
3632 sharedLibraryFile.length() != entry.getSize() ||
3633 sharedLibraryFile.lastModified() != entry.getTime()) {
3634 if (Config.LOGD) {
3635 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003637 if (mInstaller == null) {
3638 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003639 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003640 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003641 sharedLibraryFile);
3642 }
3643 }
3644 if (!hasNativeLibraries)
3645 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3646
3647 if (!installedNativeLibraries)
3648 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3649
3650 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3651 }
3652
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003653 // Find the gdbserver executable program in a package at
3654 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3655 //
3656 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3657 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3658 //
3659 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3660 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3661 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3662 final String GDBSERVER = "gdbserver";
3663 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3664
3665 ZipFile zipFile = new ZipFile(scanFile);
3666 Enumeration<ZipEntry> entries =
3667 (Enumeration<ZipEntry>) zipFile.entries();
3668
3669 while (entries.hasMoreElements()) {
3670 ZipEntry entry = entries.nextElement();
3671 // skip directories
3672 if (entry.isDirectory()) {
3673 continue;
3674 }
3675 String entryName = entry.getName();
3676
3677 if (!entryName.equals(apkGdbServerPath)) {
3678 continue;
3679 }
3680
3681 String installGdbServerPath = installGdbServerDir.getPath() +
3682 "/" + GDBSERVER;
3683 File installGdbServerFile = new File(installGdbServerPath);
3684 if (! installGdbServerFile.exists() ||
3685 installGdbServerFile.length() != entry.getSize() ||
3686 installGdbServerFile.lastModified() != entry.getTime()) {
3687 if (Config.LOGD) {
3688 Log.d(TAG, "Caching gdbserver " + entry.getName());
3689 }
3690 if (mInstaller == null) {
3691 installGdbServerDir.mkdir();
3692 }
3693 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3694 installGdbServerFile);
3695 }
3696 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3697 }
3698 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3699 }
3700
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003701 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3702 // and copy them to /data/data/<appname>/lib.
3703 //
3704 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3705 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3706 // one if ro.product.cpu.abi2 is defined.
3707 //
3708 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3709 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003710 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003711 try {
3712 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3713
3714 // some architectures are capable of supporting several CPU ABIs
3715 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3716 // this is indicated by the definition of the ro.product.cpu.abi2
3717 // system property.
3718 //
3719 // only scan the package twice in case of ABI mismatch
3720 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003721 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003722 if (cpuAbi2 != null) {
3723 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003725
3726 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003727 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003728 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003730
3731 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3732 cpuAbi = cpuAbi2;
3733 }
3734 }
3735
3736 // for debuggable packages, also extract gdbserver from lib/<abi>
3737 // into /data/data/<appname>/lib too.
3738 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3739 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3740 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3741 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3742 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003745 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003746 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003747 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003749 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003750 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003752 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 }
3754
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003755 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003757 File binaryDir,
3758 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 InputStream inputStream = zipFile.getInputStream(entry);
3760 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003761 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003763 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 // now need to be left as world readable and owned by the system.
3765 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3766 ! tempFile.setLastModified(entry.getTime()) ||
3767 FileUtils.setPermissions(tempFilePath,
3768 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003769 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003771 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772 // Failed to properly write file.
3773 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003774 throw new IOException("Couldn't create cached binary "
3775 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 }
3777 } finally {
3778 inputStream.close();
3779 }
3780 }
3781
3782 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3783 if (chatty && Config.LOGD) Log.d(
3784 TAG, "Removing package " + pkg.applicationInfo.packageName );
3785
3786 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003787 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 mPackages.remove(pkg.applicationInfo.packageName);
3790 if (pkg.mPath != null) {
3791 mAppDirs.remove(pkg.mPath);
3792 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 PackageSetting ps = (PackageSetting)pkg.mExtras;
3795 if (ps != null && ps.sharedUser != null) {
3796 // XXX don't do this until the data is removed.
3797 if (false) {
3798 ps.sharedUser.packages.remove(ps);
3799 if (ps.sharedUser.packages.size() == 0) {
3800 // Remove.
3801 }
3802 }
3803 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 int N = pkg.providers.size();
3806 StringBuilder r = null;
3807 int i;
3808 for (i=0; i<N; i++) {
3809 PackageParser.Provider p = pkg.providers.get(i);
3810 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3811 p.info.name));
3812 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003814 /* The is another ContentProvider with this authority when
3815 * this app was installed so this authority is null,
3816 * Ignore it as we don't have to unregister the provider.
3817 */
3818 continue;
3819 }
3820 String names[] = p.info.authority.split(";");
3821 for (int j = 0; j < names.length; j++) {
3822 if (mProviders.get(names[j]) == p) {
3823 mProviders.remove(names[j]);
3824 if (chatty && Config.LOGD) Log.d(
3825 TAG, "Unregistered content provider: " + names[j] +
3826 ", className = " + p.info.name +
3827 ", isSyncable = " + p.info.isSyncable);
3828 }
3829 }
3830 if (chatty) {
3831 if (r == null) {
3832 r = new StringBuilder(256);
3833 } else {
3834 r.append(' ');
3835 }
3836 r.append(p.info.name);
3837 }
3838 }
3839 if (r != null) {
3840 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 N = pkg.services.size();
3844 r = null;
3845 for (i=0; i<N; i++) {
3846 PackageParser.Service s = pkg.services.get(i);
3847 mServices.removeService(s);
3848 if (chatty) {
3849 if (r == null) {
3850 r = new StringBuilder(256);
3851 } else {
3852 r.append(' ');
3853 }
3854 r.append(s.info.name);
3855 }
3856 }
3857 if (r != null) {
3858 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3859 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 N = pkg.receivers.size();
3862 r = null;
3863 for (i=0; i<N; i++) {
3864 PackageParser.Activity a = pkg.receivers.get(i);
3865 mReceivers.removeActivity(a, "receiver");
3866 if (chatty) {
3867 if (r == null) {
3868 r = new StringBuilder(256);
3869 } else {
3870 r.append(' ');
3871 }
3872 r.append(a.info.name);
3873 }
3874 }
3875 if (r != null) {
3876 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3877 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 N = pkg.activities.size();
3880 r = null;
3881 for (i=0; i<N; i++) {
3882 PackageParser.Activity a = pkg.activities.get(i);
3883 mActivities.removeActivity(a, "activity");
3884 if (chatty) {
3885 if (r == null) {
3886 r = new StringBuilder(256);
3887 } else {
3888 r.append(' ');
3889 }
3890 r.append(a.info.name);
3891 }
3892 }
3893 if (r != null) {
3894 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3895 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 N = pkg.permissions.size();
3898 r = null;
3899 for (i=0; i<N; i++) {
3900 PackageParser.Permission p = pkg.permissions.get(i);
3901 boolean tree = false;
3902 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3903 if (bp == null) {
3904 tree = true;
3905 bp = mSettings.mPermissionTrees.get(p.info.name);
3906 }
3907 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003908 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 if (chatty) {
3910 if (r == null) {
3911 r = new StringBuilder(256);
3912 } else {
3913 r.append(' ');
3914 }
3915 r.append(p.info.name);
3916 }
3917 }
3918 }
3919 if (r != null) {
3920 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003923 N = pkg.instrumentation.size();
3924 r = null;
3925 for (i=0; i<N; i++) {
3926 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003927 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 if (chatty) {
3929 if (r == null) {
3930 r = new StringBuilder(256);
3931 } else {
3932 r.append(' ');
3933 }
3934 r.append(a.info.name);
3935 }
3936 }
3937 if (r != null) {
3938 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3939 }
3940 }
3941 }
3942
3943 private static final boolean isPackageFilename(String name) {
3944 return name != null && name.endsWith(".apk");
3945 }
3946
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003947 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3948 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3949 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3950 return true;
3951 }
3952 }
3953 return false;
3954 }
3955
3956 private void updatePermissionsLP(String changingPkg,
3957 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 // Make sure there are no dangling permission trees.
3959 Iterator<BasePermission> it = mSettings.mPermissionTrees
3960 .values().iterator();
3961 while (it.hasNext()) {
3962 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003963 if (bp.packageSetting == null) {
3964 // We may not yet have parsed the package, so just see if
3965 // we still know about its settings.
3966 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3967 }
3968 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003969 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 + " from package " + bp.sourcePackage);
3971 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003972 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3973 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3974 Slog.i(TAG, "Removing old permission tree: " + bp.name
3975 + " from package " + bp.sourcePackage);
3976 grantPermissions = true;
3977 it.remove();
3978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979 }
3980 }
3981
3982 // Make sure all dynamic permissions have been assigned to a package,
3983 // and make sure there are no dangling permissions.
3984 it = mSettings.mPermissions.values().iterator();
3985 while (it.hasNext()) {
3986 BasePermission bp = it.next();
3987 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3988 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3989 + bp.name + " pkg=" + bp.sourcePackage
3990 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003991 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 BasePermission tree = findPermissionTreeLP(bp.name);
3993 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003994 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 bp.perm = new PackageParser.Permission(tree.perm.owner,
3996 new PermissionInfo(bp.pendingInfo));
3997 bp.perm.info.packageName = tree.perm.info.packageName;
3998 bp.perm.info.name = bp.name;
3999 bp.uid = tree.uid;
4000 }
4001 }
4002 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004003 if (bp.packageSetting == null) {
4004 // We may not yet have parsed the package, so just see if
4005 // we still know about its settings.
4006 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4007 }
4008 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004009 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 + " from package " + bp.sourcePackage);
4011 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004012 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4013 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4014 Slog.i(TAG, "Removing old permission: " + bp.name
4015 + " from package " + bp.sourcePackage);
4016 grantPermissions = true;
4017 it.remove();
4018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 }
4020 }
4021
4022 // Now update the permissions for all packages, in particular
4023 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004024 if (grantPermissions) {
4025 for (PackageParser.Package pkg : mPackages.values()) {
4026 if (pkg != pkgInfo) {
4027 grantPermissionsLP(pkg, false);
4028 }
4029 }
4030 }
4031
4032 if (pkgInfo != null) {
4033 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 }
4035 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
4038 final PackageSetting ps = (PackageSetting)pkg.mExtras;
4039 if (ps == null) {
4040 return;
4041 }
4042 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004043 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 if (replace) {
4046 ps.permissionsFixed = false;
4047 if (gp == ps) {
4048 gp.grantedPermissions.clear();
4049 gp.gids = mGlobalGids;
4050 }
4051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 if (gp.gids == null) {
4054 gp.gids = mGlobalGids;
4055 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 final int N = pkg.requestedPermissions.size();
4058 for (int i=0; i<N; i++) {
4059 String name = pkg.requestedPermissions.get(i);
4060 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 if (false) {
4062 if (gp != ps) {
4063 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004064 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 }
4066 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004067 if (bp != null && bp.packageSetting != null) {
4068 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004069 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004070 boolean allowedSig = false;
4071 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4072 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004074 } else if (bp.packageSetting == null) {
4075 // This permission is invalid; skip it.
4076 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004077 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4078 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4079 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004081 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004083 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4085 // For updated system applications, the signatureOrSystem permission
4086 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004087 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4089 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4090 if(sysPs.grantedPermissions.contains(perm)) {
4091 allowed = true;
4092 } else {
4093 allowed = false;
4094 }
4095 } else {
4096 allowed = true;
4097 }
4098 }
4099 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004100 if (allowed) {
4101 allowedSig = true;
4102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 } else {
4104 allowed = false;
4105 }
4106 if (false) {
4107 if (gp != ps) {
4108 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4109 }
4110 }
4111 if (allowed) {
4112 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4113 && ps.permissionsFixed) {
4114 // If this is an existing, non-system package, then
4115 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004116 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004118 // Except... if this is a permission that was added
4119 // to the platform (note: need to only do this when
4120 // updating the platform).
4121 final int NP = PackageParser.NEW_PERMISSIONS.length;
4122 for (int ip=0; ip<NP; ip++) {
4123 final PackageParser.NewPermissionInfo npi
4124 = PackageParser.NEW_PERMISSIONS[ip];
4125 if (npi.name.equals(perm)
4126 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4127 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004128 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004129 + pkg.packageName);
4130 break;
4131 }
4132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 }
4134 }
4135 if (allowed) {
4136 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004137 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 gp.grantedPermissions.add(perm);
4139 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004140 } else if (!ps.haveGids) {
4141 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004142 }
4143 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004144 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 + " to package " + pkg.packageName
4146 + " because it was previously installed without");
4147 }
4148 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004149 if (gp.grantedPermissions.remove(perm)) {
4150 changedPermission = true;
4151 gp.gids = removeInts(gp.gids, bp.gids);
4152 Slog.i(TAG, "Un-granting permission " + perm
4153 + " from package " + pkg.packageName
4154 + " (protectionLevel=" + bp.protectionLevel
4155 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4156 + ")");
4157 } else {
4158 Slog.w(TAG, "Not granting permission " + perm
4159 + " to package " + pkg.packageName
4160 + " (protectionLevel=" + bp.protectionLevel
4161 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4162 + ")");
4163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 }
4165 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004166 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 + " in package " + pkg.packageName);
4168 }
4169 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004170
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004171 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004172 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4173 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 // This is the first that we have heard about this package, so the
4175 // permissions we have now selected are fixed until explicitly
4176 // changed.
4177 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004179 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 private final class ActivityIntentResolver
4183 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004184 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004185 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004186 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 }
4188
Mihai Preda074edef2009-05-18 17:13:31 +02004189 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004191 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4193 }
4194
Mihai Predaeae850c2009-05-13 10:13:48 +02004195 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4196 ArrayList<PackageParser.Activity> packageActivities) {
4197 if (packageActivities == null) {
4198 return null;
4199 }
4200 mFlags = flags;
4201 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4202 int N = packageActivities.size();
4203 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4204 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004205
4206 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004207 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004208 intentFilters = packageActivities.get(i).intents;
4209 if (intentFilters != null && intentFilters.size() > 0) {
4210 listCut.add(intentFilters);
4211 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004212 }
4213 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4214 }
4215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004217 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218 if (SHOW_INFO || Config.LOGV) Log.v(
4219 TAG, " " + type + " " +
4220 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4221 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4222 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004223 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4225 if (SHOW_INFO || Config.LOGV) {
4226 Log.v(TAG, " IntentFilter:");
4227 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4228 }
4229 if (!intent.debugCheck()) {
4230 Log.w(TAG, "==> For Activity " + a.info.name);
4231 }
4232 addFilter(intent);
4233 }
4234 }
4235
4236 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004237 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 if (SHOW_INFO || Config.LOGV) Log.v(
4239 TAG, " " + type + " " +
4240 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4241 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4242 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004243 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4245 if (SHOW_INFO || Config.LOGV) {
4246 Log.v(TAG, " IntentFilter:");
4247 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4248 }
4249 removeFilter(intent);
4250 }
4251 }
4252
4253 @Override
4254 protected boolean allowFilterResult(
4255 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4256 ActivityInfo filterAi = filter.activity.info;
4257 for (int i=dest.size()-1; i>=0; i--) {
4258 ActivityInfo destAi = dest.get(i).activityInfo;
4259 if (destAi.name == filterAi.name
4260 && destAi.packageName == filterAi.packageName) {
4261 return false;
4262 }
4263 }
4264 return true;
4265 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004267 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004268 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4269 return info.activity.owner.packageName;
4270 }
4271
4272 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4274 int match) {
4275 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4276 return null;
4277 }
4278 final PackageParser.Activity activity = info.activity;
4279 if (mSafeMode && (activity.info.applicationInfo.flags
4280 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4281 return null;
4282 }
4283 final ResolveInfo res = new ResolveInfo();
4284 res.activityInfo = PackageParser.generateActivityInfo(activity,
4285 mFlags);
4286 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4287 res.filter = info;
4288 }
4289 res.priority = info.getPriority();
4290 res.preferredOrder = activity.owner.mPreferredOrder;
4291 //System.out.println("Result: " + res.activityInfo.className +
4292 // " = " + res.priority);
4293 res.match = match;
4294 res.isDefault = info.hasDefault;
4295 res.labelRes = info.labelRes;
4296 res.nonLocalizedLabel = info.nonLocalizedLabel;
4297 res.icon = info.icon;
4298 return res;
4299 }
4300
4301 @Override
4302 protected void sortResults(List<ResolveInfo> results) {
4303 Collections.sort(results, mResolvePrioritySorter);
4304 }
4305
4306 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004307 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004309 out.print(prefix); out.print(
4310 Integer.toHexString(System.identityHashCode(filter.activity)));
4311 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004312 out.print(filter.activity.getComponentShortName());
4313 out.print(" filter ");
4314 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315 }
4316
4317// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4318// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4319// final List<ResolveInfo> retList = Lists.newArrayList();
4320// while (i.hasNext()) {
4321// final ResolveInfo resolveInfo = i.next();
4322// if (isEnabledLP(resolveInfo.activityInfo)) {
4323// retList.add(resolveInfo);
4324// }
4325// }
4326// return retList;
4327// }
4328
4329 // Keys are String (activity class name), values are Activity.
4330 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4331 = new HashMap<ComponentName, PackageParser.Activity>();
4332 private int mFlags;
4333 }
4334
4335 private final class ServiceIntentResolver
4336 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004337 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004339 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004340 }
4341
Mihai Preda074edef2009-05-18 17:13:31 +02004342 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004344 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4346 }
4347
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004348 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4349 ArrayList<PackageParser.Service> packageServices) {
4350 if (packageServices == null) {
4351 return null;
4352 }
4353 mFlags = flags;
4354 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4355 int N = packageServices.size();
4356 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4357 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4358
4359 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4360 for (int i = 0; i < N; ++i) {
4361 intentFilters = packageServices.get(i).intents;
4362 if (intentFilters != null && intentFilters.size() > 0) {
4363 listCut.add(intentFilters);
4364 }
4365 }
4366 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4367 }
4368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004370 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 if (SHOW_INFO || Config.LOGV) Log.v(
4372 TAG, " " + (s.info.nonLocalizedLabel != null
4373 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4374 if (SHOW_INFO || Config.LOGV) Log.v(
4375 TAG, " Class=" + s.info.name);
4376 int NI = s.intents.size();
4377 int j;
4378 for (j=0; j<NI; j++) {
4379 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4380 if (SHOW_INFO || Config.LOGV) {
4381 Log.v(TAG, " IntentFilter:");
4382 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4383 }
4384 if (!intent.debugCheck()) {
4385 Log.w(TAG, "==> For Service " + s.info.name);
4386 }
4387 addFilter(intent);
4388 }
4389 }
4390
4391 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004392 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393 if (SHOW_INFO || Config.LOGV) Log.v(
4394 TAG, " " + (s.info.nonLocalizedLabel != null
4395 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4396 if (SHOW_INFO || Config.LOGV) Log.v(
4397 TAG, " Class=" + s.info.name);
4398 int NI = s.intents.size();
4399 int j;
4400 for (j=0; j<NI; j++) {
4401 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4402 if (SHOW_INFO || Config.LOGV) {
4403 Log.v(TAG, " IntentFilter:");
4404 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4405 }
4406 removeFilter(intent);
4407 }
4408 }
4409
4410 @Override
4411 protected boolean allowFilterResult(
4412 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4413 ServiceInfo filterSi = filter.service.info;
4414 for (int i=dest.size()-1; i>=0; i--) {
4415 ServiceInfo destAi = dest.get(i).serviceInfo;
4416 if (destAi.name == filterSi.name
4417 && destAi.packageName == filterSi.packageName) {
4418 return false;
4419 }
4420 }
4421 return true;
4422 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004424 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004425 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4426 return info.service.owner.packageName;
4427 }
4428
4429 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004430 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4431 int match) {
4432 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4433 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4434 return null;
4435 }
4436 final PackageParser.Service service = info.service;
4437 if (mSafeMode && (service.info.applicationInfo.flags
4438 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4439 return null;
4440 }
4441 final ResolveInfo res = new ResolveInfo();
4442 res.serviceInfo = PackageParser.generateServiceInfo(service,
4443 mFlags);
4444 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4445 res.filter = filter;
4446 }
4447 res.priority = info.getPriority();
4448 res.preferredOrder = service.owner.mPreferredOrder;
4449 //System.out.println("Result: " + res.activityInfo.className +
4450 // " = " + res.priority);
4451 res.match = match;
4452 res.isDefault = info.hasDefault;
4453 res.labelRes = info.labelRes;
4454 res.nonLocalizedLabel = info.nonLocalizedLabel;
4455 res.icon = info.icon;
4456 return res;
4457 }
4458
4459 @Override
4460 protected void sortResults(List<ResolveInfo> results) {
4461 Collections.sort(results, mResolvePrioritySorter);
4462 }
4463
4464 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004465 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004466 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004467 out.print(prefix); out.print(
4468 Integer.toHexString(System.identityHashCode(filter.service)));
4469 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004470 out.print(filter.service.getComponentShortName());
4471 out.print(" filter ");
4472 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004473 }
4474
4475// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4476// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4477// final List<ResolveInfo> retList = Lists.newArrayList();
4478// while (i.hasNext()) {
4479// final ResolveInfo resolveInfo = (ResolveInfo) i;
4480// if (isEnabledLP(resolveInfo.serviceInfo)) {
4481// retList.add(resolveInfo);
4482// }
4483// }
4484// return retList;
4485// }
4486
4487 // Keys are String (activity class name), values are Activity.
4488 private final HashMap<ComponentName, PackageParser.Service> mServices
4489 = new HashMap<ComponentName, PackageParser.Service>();
4490 private int mFlags;
4491 };
4492
4493 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4494 new Comparator<ResolveInfo>() {
4495 public int compare(ResolveInfo r1, ResolveInfo r2) {
4496 int v1 = r1.priority;
4497 int v2 = r2.priority;
4498 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4499 if (v1 != v2) {
4500 return (v1 > v2) ? -1 : 1;
4501 }
4502 v1 = r1.preferredOrder;
4503 v2 = r2.preferredOrder;
4504 if (v1 != v2) {
4505 return (v1 > v2) ? -1 : 1;
4506 }
4507 if (r1.isDefault != r2.isDefault) {
4508 return r1.isDefault ? -1 : 1;
4509 }
4510 v1 = r1.match;
4511 v2 = r2.match;
4512 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4513 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4514 }
4515 };
4516
4517 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4518 new Comparator<ProviderInfo>() {
4519 public int compare(ProviderInfo p1, ProviderInfo p2) {
4520 final int v1 = p1.initOrder;
4521 final int v2 = p2.initOrder;
4522 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4523 }
4524 };
4525
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004526 private static final void sendPackageBroadcast(String action, String pkg,
4527 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004528 IActivityManager am = ActivityManagerNative.getDefault();
4529 if (am != null) {
4530 try {
4531 final Intent intent = new Intent(action,
4532 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4533 if (extras != null) {
4534 intent.putExtras(extras);
4535 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004536 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004537 am.broadcastIntent(null, intent, null, finishedReceiver,
4538 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004539 } catch (RemoteException ex) {
4540 }
4541 }
4542 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004543
4544 public String nextPackageToClean(String lastPackage) {
4545 synchronized (mPackages) {
4546 if (!mMediaMounted) {
4547 // If the external storage is no longer mounted at this point,
4548 // the caller may not have been able to delete all of this
4549 // packages files and can not delete any more. Bail.
4550 return null;
4551 }
4552 if (lastPackage != null) {
4553 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4554 }
4555 return mSettings.mPackagesToBeCleaned.size() > 0
4556 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4557 }
4558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004559
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004560 void schedulePackageCleaning(String packageName) {
4561 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4562 }
4563
4564 void startCleaningPackages() {
4565 synchronized (mPackages) {
4566 if (!mMediaMounted) {
4567 return;
4568 }
4569 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4570 return;
4571 }
4572 }
4573 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4574 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4575 IActivityManager am = ActivityManagerNative.getDefault();
4576 if (am != null) {
4577 try {
4578 am.startService(null, intent, null);
4579 } catch (RemoteException e) {
4580 }
4581 }
4582 }
4583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004584 private final class AppDirObserver extends FileObserver {
4585 public AppDirObserver(String path, int mask, boolean isrom) {
4586 super(path, mask);
4587 mRootDir = path;
4588 mIsRom = isrom;
4589 }
4590
4591 public void onEvent(int event, String path) {
4592 String removedPackage = null;
4593 int removedUid = -1;
4594 String addedPackage = null;
4595 int addedUid = -1;
4596
4597 synchronized (mInstallLock) {
4598 String fullPathStr = null;
4599 File fullPath = null;
4600 if (path != null) {
4601 fullPath = new File(mRootDir, path);
4602 fullPathStr = fullPath.getPath();
4603 }
4604
4605 if (Config.LOGV) Log.v(
4606 TAG, "File " + fullPathStr + " changed: "
4607 + Integer.toHexString(event));
4608
4609 if (!isPackageFilename(path)) {
4610 if (Config.LOGV) Log.v(
4611 TAG, "Ignoring change of non-package file: " + fullPathStr);
4612 return;
4613 }
4614
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004615 // Ignore packages that are being installed or
4616 // have just been installed.
4617 if (ignoreCodePath(fullPathStr)) {
4618 return;
4619 }
4620 PackageParser.Package p = null;
4621 synchronized (mPackages) {
4622 p = mAppDirs.get(fullPathStr);
4623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004624 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004625 if (p != null) {
4626 removePackageLI(p, true);
4627 removedPackage = p.applicationInfo.packageName;
4628 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004629 }
4630 }
4631
4632 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004633 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004634 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004635 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4636 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 PackageParser.PARSE_CHATTY |
4638 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004639 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004640 if (p != null) {
4641 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004642 updatePermissionsLP(p.packageName, p,
4643 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 }
4645 addedPackage = p.applicationInfo.packageName;
4646 addedUid = p.applicationInfo.uid;
4647 }
4648 }
4649 }
4650
4651 synchronized (mPackages) {
4652 mSettings.writeLP();
4653 }
4654 }
4655
4656 if (removedPackage != null) {
4657 Bundle extras = new Bundle(1);
4658 extras.putInt(Intent.EXTRA_UID, removedUid);
4659 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004660 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4661 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004662 }
4663 if (addedPackage != null) {
4664 Bundle extras = new Bundle(1);
4665 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004666 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4667 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004668 }
4669 }
4670
4671 private final String mRootDir;
4672 private final boolean mIsRom;
4673 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675 /* Called when a downloaded package installation has been confirmed by the user */
4676 public void installPackage(
4677 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004678 installPackage(packageURI, observer, flags, null);
4679 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004680
Jacek Surazski65e13172009-04-28 15:26:38 +02004681 /* Called when a downloaded package installation has been confirmed by the user */
4682 public void installPackage(
4683 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4684 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004685 mContext.enforceCallingOrSelfPermission(
4686 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004687
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004688 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004689 msg.obj = new InstallParams(packageURI, observer, flags,
4690 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004691 mHandler.sendMessage(msg);
4692 }
4693
Christopher Tate1bb69062010-02-19 17:02:12 -08004694 public void finishPackageInstall(int token) {
4695 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4696 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4697 mHandler.sendMessage(msg);
4698 }
4699
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004700 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004701 // Queue up an async operation since the package installation may take a little while.
4702 mHandler.post(new Runnable() {
4703 public void run() {
4704 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004705 // Result object to be returned
4706 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004707 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004708 res.uid = -1;
4709 res.pkg = null;
4710 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004711 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004712 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004713 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004714 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004715 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004716 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004717 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004718
4719 // A restore should be performed at this point if (a) the install
4720 // succeeded, (b) the operation is not an update, and (c) the new
4721 // package has a backupAgent defined.
4722 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004723 boolean doRestore = (!update
4724 && res.pkg != null
4725 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004726
4727 // Set up the post-install work request bookkeeping. This will be used
4728 // and cleaned up by the post-install event handling regardless of whether
4729 // there's a restore pass performed. Token values are >= 1.
4730 int token;
4731 if (mNextInstallToken < 0) mNextInstallToken = 1;
4732 token = mNextInstallToken++;
4733
4734 PostInstallData data = new PostInstallData(args, res);
4735 mRunningInstalls.put(token, data);
4736 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4737
4738 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4739 // Pass responsibility to the Backup Manager. It will perform a
4740 // restore if appropriate, then pass responsibility back to the
4741 // Package Manager to run the post-install observer callbacks
4742 // and broadcasts.
4743 IBackupManager bm = IBackupManager.Stub.asInterface(
4744 ServiceManager.getService(Context.BACKUP_SERVICE));
4745 if (bm != null) {
4746 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4747 + " to BM for possible restore");
4748 try {
4749 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4750 } catch (RemoteException e) {
4751 // can't happen; the backup manager is local
4752 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004753 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004754 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004755 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004756 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004757 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004758 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004761
4762 if (!doRestore) {
4763 // No restore possible, or the Backup Manager was mysteriously not
4764 // available -- just fire the post-install work request directly.
4765 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4766 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4767 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 }
4770 });
4771 }
4772
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004773 abstract class HandlerParams {
4774 final static int MAX_RETRIES = 4;
4775 int retry = 0;
4776 final void startCopy() {
4777 try {
4778 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4779 retry++;
4780 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004781 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004782 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4783 handleServiceError();
4784 return;
4785 } else {
4786 handleStartCopy();
4787 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4788 mHandler.sendEmptyMessage(MCS_UNBIND);
4789 }
4790 } catch (RemoteException e) {
4791 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4792 mHandler.sendEmptyMessage(MCS_RECONNECT);
4793 }
4794 handleReturnCode();
4795 }
4796
4797 final void serviceError() {
4798 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4799 handleServiceError();
4800 handleReturnCode();
4801 }
4802 abstract void handleStartCopy() throws RemoteException;
4803 abstract void handleServiceError();
4804 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004805 }
4806
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004807 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004808 final IPackageInstallObserver observer;
4809 int flags;
4810 final Uri packageURI;
4811 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004812 private InstallArgs mArgs;
4813 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004814 InstallParams(Uri packageURI,
4815 IPackageInstallObserver observer, int flags,
4816 String installerPackageName) {
4817 this.packageURI = packageURI;
4818 this.flags = flags;
4819 this.observer = observer;
4820 this.installerPackageName = installerPackageName;
4821 }
4822
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004823 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4824 String packageName = pkgLite.packageName;
4825 int installLocation = pkgLite.installLocation;
4826 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4827 synchronized (mPackages) {
4828 PackageParser.Package pkg = mPackages.get(packageName);
4829 if (pkg != null) {
4830 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4831 // Check for updated system application.
4832 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4833 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004834 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004835 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4836 }
4837 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4838 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004839 if (onSd) {
4840 // Install flag overrides everything.
4841 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4842 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004843 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004844 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4845 // Application explicitly specified internal.
4846 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4847 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4848 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004849 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004850 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004851 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4852 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4853 }
4854 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004855 }
4856 }
4857 } else {
4858 // Invalid install. Return error code
4859 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4860 }
4861 }
4862 }
4863 // All the special cases have been taken care of.
4864 // Return result based on recommended install location.
4865 if (onSd) {
4866 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4867 }
4868 return pkgLite.recommendedInstallLocation;
4869 }
4870
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004871 /*
4872 * Invoke remote method to get package information and install
4873 * location values. Override install location based on default
4874 * policy if needed and then create install arguments based
4875 * on the install location.
4876 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004877 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004878 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004879 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4880 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004881 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4882 if (onInt && onSd) {
4883 // Check if both bits are set.
4884 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4885 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4886 } else if (fwdLocked && onSd) {
4887 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004888 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004889 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004890 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004891 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004892 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004893 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004894 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4895 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4896 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4897 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4898 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004899 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4900 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4901 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004902 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4903 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004904 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004905 // Override with defaults if needed.
4906 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004907 if (!onSd && !onInt) {
4908 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004909 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4910 // Set the flag to install on external media.
4911 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004912 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004913 } else {
4914 // Make sure the flag for installing on external
4915 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004916 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004917 flags &= ~PackageManager.INSTALL_EXTERNAL;
4918 }
4919 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004920 }
4921 }
4922 // Create the file args now.
4923 mArgs = createInstallArgs(this);
4924 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4925 // Create copy only if we are not in an erroneous state.
4926 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004927 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004928 }
4929 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004930 }
4931
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004932 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004933 void handleReturnCode() {
4934 processPendingInstall(mArgs, mRet);
4935 }
4936
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004937 @Override
4938 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004939 mArgs = createInstallArgs(this);
4940 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004941 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004942 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004943
4944 /*
4945 * Utility class used in movePackage api.
4946 * srcArgs and targetArgs are not set for invalid flags and make
4947 * sure to do null checks when invoking methods on them.
4948 * We probably want to return ErrorPrams for both failed installs
4949 * and moves.
4950 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004951 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004952 final IPackageMoveObserver observer;
4953 final int flags;
4954 final String packageName;
4955 final InstallArgs srcArgs;
4956 final InstallArgs targetArgs;
4957 int mRet;
4958 MoveParams(InstallArgs srcArgs,
4959 IPackageMoveObserver observer,
4960 int flags, String packageName) {
4961 this.srcArgs = srcArgs;
4962 this.observer = observer;
4963 this.flags = flags;
4964 this.packageName = packageName;
4965 if (srcArgs != null) {
4966 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4967 targetArgs = createInstallArgs(packageUri, flags, packageName);
4968 } else {
4969 targetArgs = null;
4970 }
4971 }
4972
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004973 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004974 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4975 // Check for storage space on target medium
4976 if (!targetArgs.checkFreeStorage(mContainerService)) {
4977 Log.w(TAG, "Insufficient storage to install");
4978 return;
4979 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004980 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004981 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004982 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004983 if (DEBUG_SD_INSTALL) {
4984 StringBuilder builder = new StringBuilder();
4985 if (srcArgs != null) {
4986 builder.append("src: ");
4987 builder.append(srcArgs.getCodePath());
4988 }
4989 if (targetArgs != null) {
4990 builder.append(" target : ");
4991 builder.append(targetArgs.getCodePath());
4992 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004993 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004994 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004995 }
4996
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004997 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004998 void handleReturnCode() {
4999 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005000 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
5001 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
5002 currentStatus = PackageManager.MOVE_SUCCEEDED;
5003 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
5004 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
5005 }
5006 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005007 }
5008
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005009 @Override
5010 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005011 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005012 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005013 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005014
5015 private InstallArgs createInstallArgs(InstallParams params) {
5016 if (installOnSd(params.flags)) {
5017 return new SdInstallArgs(params);
5018 } else {
5019 return new FileInstallArgs(params);
5020 }
5021 }
5022
5023 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
5024 if (installOnSd(flags)) {
5025 return new SdInstallArgs(fullCodePath, fullResourcePath);
5026 } else {
5027 return new FileInstallArgs(fullCodePath, fullResourcePath);
5028 }
5029 }
5030
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005031 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
5032 if (installOnSd(flags)) {
5033 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5034 return new SdInstallArgs(packageURI, cid);
5035 } else {
5036 return new FileInstallArgs(packageURI, pkgName);
5037 }
5038 }
5039
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005040 static abstract class InstallArgs {
5041 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005042 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005043 final int flags;
5044 final Uri packageURI;
5045 final String installerPackageName;
5046
5047 InstallArgs(Uri packageURI,
5048 IPackageInstallObserver observer, int flags,
5049 String installerPackageName) {
5050 this.packageURI = packageURI;
5051 this.flags = flags;
5052 this.observer = observer;
5053 this.installerPackageName = installerPackageName;
5054 }
5055
5056 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005057 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005058 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005059 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005060 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005061 abstract String getCodePath();
5062 abstract String getResourcePath();
5063 // Need installer lock especially for dex file removal.
5064 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005065 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005066 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005067 }
5068
5069 class FileInstallArgs extends InstallArgs {
5070 File installDir;
5071 String codeFileName;
5072 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005073 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005074
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005075 FileInstallArgs(InstallParams params) {
5076 super(params.packageURI, params.observer,
5077 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005078 }
5079
5080 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5081 super(null, null, 0, null);
5082 File codeFile = new File(fullCodePath);
5083 installDir = codeFile.getParentFile();
5084 codeFileName = fullCodePath;
5085 resourceFileName = fullResourcePath;
5086 }
5087
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005088 FileInstallArgs(Uri packageURI, String pkgName) {
5089 super(packageURI, null, 0, null);
5090 boolean fwdLocked = isFwdLocked(flags);
5091 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5092 String apkName = getNextCodePath(null, pkgName, ".apk");
5093 codeFileName = new File(installDir, apkName + ".apk").getPath();
5094 resourceFileName = getResourcePathFromCodePath();
5095 }
5096
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005097 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5098 return imcs.checkFreeStorage(false, packageURI);
5099 }
5100
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005101 String getCodePath() {
5102 return codeFileName;
5103 }
5104
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005105 void createCopyFile() {
5106 boolean fwdLocked = isFwdLocked(flags);
5107 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5108 codeFileName = createTempPackageFile(installDir).getPath();
5109 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005110 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005111 }
5112
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005113 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005114 if (temp) {
5115 // Generate temp file name
5116 createCopyFile();
5117 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005118 // Get a ParcelFileDescriptor to write to the output file
5119 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005120 if (!created) {
5121 try {
5122 codeFile.createNewFile();
5123 // Set permissions
5124 if (!setPermissions()) {
5125 // Failed setting permissions.
5126 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5127 }
5128 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005129 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005130 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5131 }
5132 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005133 ParcelFileDescriptor out = null;
5134 try {
5135 out = ParcelFileDescriptor.open(codeFile,
5136 ParcelFileDescriptor.MODE_READ_WRITE);
5137 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005138 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005139 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5140 }
5141 // Copy the resource now
5142 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5143 try {
5144 if (imcs.copyResource(packageURI, out)) {
5145 ret = PackageManager.INSTALL_SUCCEEDED;
5146 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005147 } finally {
5148 try { if (out != null) out.close(); } catch (IOException e) {}
5149 }
5150 return ret;
5151 }
5152
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005153 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005154 if (status != PackageManager.INSTALL_SUCCEEDED) {
5155 cleanUp();
5156 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005157 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005158 }
5159
5160 boolean doRename(int status, final String pkgName, String oldCodePath) {
5161 if (status != PackageManager.INSTALL_SUCCEEDED) {
5162 cleanUp();
5163 return false;
5164 } else {
5165 // Rename based on packageName
5166 File codeFile = new File(getCodePath());
5167 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5168 File desFile = new File(installDir, apkName + ".apk");
5169 if (!codeFile.renameTo(desFile)) {
5170 return false;
5171 }
5172 // Reset paths since the file has been renamed.
5173 codeFileName = desFile.getPath();
5174 resourceFileName = getResourcePathFromCodePath();
5175 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005176 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005177 // Failed setting permissions.
5178 return false;
5179 }
5180 return true;
5181 }
5182 }
5183
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005184 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005185 if (status != PackageManager.INSTALL_SUCCEEDED) {
5186 cleanUp();
5187 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005188 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005189 }
5190
5191 String getResourcePath() {
5192 return resourceFileName;
5193 }
5194
5195 String getResourcePathFromCodePath() {
5196 String codePath = getCodePath();
5197 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5198 String apkNameOnly = getApkName(codePath);
5199 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5200 } else {
5201 return codePath;
5202 }
5203 }
5204
5205 private boolean cleanUp() {
5206 boolean ret = true;
5207 String sourceDir = getCodePath();
5208 String publicSourceDir = getResourcePath();
5209 if (sourceDir != null) {
5210 File sourceFile = new File(sourceDir);
5211 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005212 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005213 ret = false;
5214 }
5215 // Delete application's code and resources
5216 sourceFile.delete();
5217 }
5218 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5219 final File publicSourceFile = new File(publicSourceDir);
5220 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005221 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005222 }
5223 if (publicSourceFile.exists()) {
5224 publicSourceFile.delete();
5225 }
5226 }
5227 return ret;
5228 }
5229
5230 void cleanUpResourcesLI() {
5231 String sourceDir = getCodePath();
5232 if (cleanUp() && mInstaller != null) {
5233 int retCode = mInstaller.rmdex(sourceDir);
5234 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005235 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005236 + " at location "
5237 + sourceDir + ", retcode=" + retCode);
5238 // we don't consider this to be a failure of the core package deletion
5239 }
5240 }
5241 }
5242
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005243 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005244 // TODO Do this in a more elegant way later on. for now just a hack
5245 if (!isFwdLocked(flags)) {
5246 final int filePermissions =
5247 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5248 |FileUtils.S_IROTH;
5249 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5250 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005251 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005252 getCodePath()
5253 + ". The return code was: " + retCode);
5254 // TODO Define new internal error
5255 return false;
5256 }
5257 return true;
5258 }
5259 return true;
5260 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005261
5262 boolean doPostDeleteLI(boolean delete) {
5263 cleanUpResourcesLI();
5264 return true;
5265 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005266 }
5267
5268 class SdInstallArgs extends InstallArgs {
5269 String cid;
5270 String cachePath;
5271 static final String RES_FILE_NAME = "pkg.apk";
5272
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005273 SdInstallArgs(InstallParams params) {
5274 super(params.packageURI, params.observer,
5275 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005276 }
5277
5278 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005279 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005280 // Extract cid from fullCodePath
5281 int eidx = fullCodePath.lastIndexOf("/");
5282 String subStr1 = fullCodePath.substring(0, eidx);
5283 int sidx = subStr1.lastIndexOf("/");
5284 cid = subStr1.substring(sidx+1, eidx);
5285 cachePath = subStr1;
5286 }
5287
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005288 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005289 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5290 this.cid = cid;
5291 }
5292
5293 SdInstallArgs(Uri packageURI, String cid) {
5294 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005295 this.cid = cid;
5296 }
5297
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005298 void createCopyFile() {
5299 cid = getTempContainerId();
5300 }
5301
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005302 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5303 return imcs.checkFreeStorage(true, packageURI);
5304 }
5305
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005306 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005307 if (temp) {
5308 createCopyFile();
5309 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005310 cachePath = imcs.copyResourceToContainer(
5311 packageURI, cid,
5312 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005313 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5314 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005315 }
5316
5317 @Override
5318 String getCodePath() {
5319 return cachePath + "/" + RES_FILE_NAME;
5320 }
5321
5322 @Override
5323 String getResourcePath() {
5324 return cachePath + "/" + RES_FILE_NAME;
5325 }
5326
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005327 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005328 if (status != PackageManager.INSTALL_SUCCEEDED) {
5329 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005330 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005331 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005332 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005333 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005334 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005335 if (cachePath == null) {
5336 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5337 }
5338 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005339 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005340 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005341 }
5342
5343 boolean doRename(int status, final String pkgName,
5344 String oldCodePath) {
5345 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005346 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005347 if (PackageHelper.isContainerMounted(cid)) {
5348 // Unmount the container
5349 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005350 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005351 return false;
5352 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005353 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005354 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005355 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5356 " which might be stale. Will try to clean up.");
5357 // Clean up the stale container and proceed to recreate.
5358 if (!PackageHelper.destroySdDir(newCacheId)) {
5359 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5360 return false;
5361 }
5362 // Successfully cleaned up stale container. Try to rename again.
5363 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5364 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5365 + " inspite of cleaning it up.");
5366 return false;
5367 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005368 }
5369 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005370 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005371 newCachePath = PackageHelper.mountSdDir(newCacheId,
5372 getEncryptKey(), Process.SYSTEM_UID);
5373 } else {
5374 newCachePath = PackageHelper.getSdDir(newCacheId);
5375 }
5376 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005377 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005378 return false;
5379 }
5380 Log.i(TAG, "Succesfully renamed " + cid +
5381 " at path: " + cachePath + " to " + newCacheId +
5382 " at new path: " + newCachePath);
5383 cid = newCacheId;
5384 cachePath = newCachePath;
5385 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005386 }
5387
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005388 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005389 if (status != PackageManager.INSTALL_SUCCEEDED) {
5390 cleanUp();
5391 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005392 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005393 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005394 PackageHelper.mountSdDir(cid,
5395 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005396 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005397 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005398 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005399 }
5400
5401 private void cleanUp() {
5402 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005403 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005404 }
5405
5406 void cleanUpResourcesLI() {
5407 String sourceFile = getCodePath();
5408 // Remove dex file
5409 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005410 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005411 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005412 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005413 + " at location "
5414 + sourceFile.toString() + ", retcode=" + retCode);
5415 // we don't consider this to be a failure of the core package deletion
5416 }
5417 }
5418 cleanUp();
5419 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005420
5421 boolean matchContainer(String app) {
5422 if (cid.startsWith(app)) {
5423 return true;
5424 }
5425 return false;
5426 }
5427
5428 String getPackageName() {
5429 int idx = cid.lastIndexOf("-");
5430 if (idx == -1) {
5431 return cid;
5432 }
5433 return cid.substring(0, idx);
5434 }
5435
5436 boolean doPostDeleteLI(boolean delete) {
5437 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005438 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005439 if (mounted) {
5440 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005441 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005442 }
5443 if (ret && delete) {
5444 cleanUpResourcesLI();
5445 }
5446 return ret;
5447 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005448 };
5449
5450 // Utility method used to create code paths based on package name and available index.
5451 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5452 String idxStr = "";
5453 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005454 // Fall back to default value of idx=1 if prefix is not
5455 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005456 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005457 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005458 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005459 if (subStr.endsWith(suffix)) {
5460 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005461 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005462 // If oldCodePath already contains prefix find out the
5463 // ending index to either increment or decrement.
5464 int sidx = subStr.lastIndexOf(prefix);
5465 if (sidx != -1) {
5466 subStr = subStr.substring(sidx + prefix.length());
5467 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005468 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5469 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005470 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005471 try {
5472 idx = Integer.parseInt(subStr);
5473 if (idx <= 1) {
5474 idx++;
5475 } else {
5476 idx--;
5477 }
5478 } catch(NumberFormatException e) {
5479 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005480 }
5481 }
5482 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005483 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005484 return prefix + idxStr;
5485 }
5486
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005487 // Utility method used to ignore ADD/REMOVE events
5488 // by directory observer.
5489 private static boolean ignoreCodePath(String fullPathStr) {
5490 String apkName = getApkName(fullPathStr);
5491 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5492 if (idx != -1 && ((idx+1) < apkName.length())) {
5493 // Make sure the package ends with a numeral
5494 String version = apkName.substring(idx+1);
5495 try {
5496 Integer.parseInt(version);
5497 return true;
5498 } catch (NumberFormatException e) {}
5499 }
5500 return false;
5501 }
5502
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005503 // Utility method that returns the relative package path with respect
5504 // to the installation directory. Like say for /data/data/com.test-1.apk
5505 // string com.test-1 is returned.
5506 static String getApkName(String codePath) {
5507 if (codePath == null) {
5508 return null;
5509 }
5510 int sidx = codePath.lastIndexOf("/");
5511 int eidx = codePath.lastIndexOf(".");
5512 if (eidx == -1) {
5513 eidx = codePath.length();
5514 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005515 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005516 return null;
5517 }
5518 return codePath.substring(sidx+1, eidx);
5519 }
5520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521 class PackageInstalledInfo {
5522 String name;
5523 int uid;
5524 PackageParser.Package pkg;
5525 int returnCode;
5526 PackageRemovedInfo removedInfo;
5527 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 /*
5530 * Install a non-existing package.
5531 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005532 private void installNewPackageLI(PackageParser.Package pkg,
5533 int parseFlags,
5534 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005535 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005537 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005538
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005539 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 res.name = pkgName;
5541 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005542 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5543 // A package with the same name is already installed, though
5544 // it has been renamed to an older name. The package we
5545 // are trying to install should be installed as an update to
5546 // the existing one, but that has not been requested, so bail.
5547 Slog.w(TAG, "Attempt to re-install " + pkgName
5548 + " without first uninstalling package running as "
5549 + mSettings.mRenamedPackages.get(pkgName));
5550 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5551 return;
5552 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005553 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005554 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005555 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 + " without first uninstalling.");
5557 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5558 return;
5559 }
5560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005562 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005563 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005564 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5566 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5567 }
5568 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005569 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005570 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571 res);
5572 // delete the partially installed application. the data directory will have to be
5573 // restored if it was already existing
5574 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5575 // remove package from internal structures. Note that we want deletePackageX to
5576 // delete the package data and cache directories that it created in
5577 // scanPackageLocked, unless those directories existed before we even tried to
5578 // install.
5579 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005580 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5582 res.removedInfo);
5583 }
5584 }
5585 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005586
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005587 private void replacePackageLI(PackageParser.Package pkg,
5588 int parseFlags,
5589 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005590 String installerPackageName, PackageInstalledInfo res) {
5591
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005592 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005593 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 // First find the old package info and check signatures
5595 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005596 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005597 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005598 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5600 return;
5601 }
5602 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005603 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005604 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005605 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005607 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 }
5609 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005612 PackageParser.Package pkg,
5613 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005614 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005615 PackageParser.Package newPackage = null;
5616 String pkgName = deletedPackage.packageName;
5617 boolean deletedPkg = true;
5618 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005619
Jacek Surazski65e13172009-04-28 15:26:38 +02005620 String oldInstallerPackageName = null;
5621 synchronized (mPackages) {
5622 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005625 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005626 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 res.removedInfo)) {
5628 // If the existing package was'nt successfully deleted
5629 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5630 deletedPkg = false;
5631 } else {
5632 // Successfully deleted the old package. Now proceed with re-installation
5633 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005634 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005636 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5638 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005639 }
5640 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005641 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005642 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 res);
5644 updatedSettings = true;
5645 }
5646 }
5647
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005648 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 // remove package from internal structures. Note that we want deletePackageX to
5650 // delete the package data and cache directories that it created in
5651 // scanPackageLocked, unless those directories existed before we even tried to
5652 // install.
5653 if(updatedSettings) {
5654 deletePackageLI(
5655 pkgName, true,
5656 PackageManager.DONT_DELETE_DATA,
5657 res.removedInfo);
5658 }
5659 // Since we failed to install the new package we need to restore the old
5660 // package that we deleted.
5661 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005662 File restoreFile = new File(deletedPackage.mPath);
5663 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005664 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005665 return;
5666 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005667 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005668 boolean oldOnSd = isExternal(deletedPackage);
5669 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5670 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5671 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5672 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5673 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5674 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5675 return;
5676 }
5677 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005678 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005679 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5680 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005681 mSettings.writeLP();
5682 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005683 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 }
5685 }
5686 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005689 PackageParser.Package pkg,
5690 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005691 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005692 PackageParser.Package newPackage = null;
5693 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005694 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 PackageParser.PARSE_IS_SYSTEM;
5696 String packageName = deletedPackage.packageName;
5697 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5698 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005699 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005700 return;
5701 }
5702 PackageParser.Package oldPkg;
5703 PackageSetting oldPkgSetting;
5704 synchronized (mPackages) {
5705 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005706 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5708 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005709 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005710 return;
5711 }
5712 }
5713 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5714 res.removedInfo.removedPackage = packageName;
5715 // Remove existing system package
5716 removePackageLI(oldPkg, true);
5717 synchronized (mPackages) {
5718 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5719 }
5720
5721 // Successfully disabled the old package. Now proceed with re-installation
5722 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5723 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005724 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005726 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5728 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5729 }
5730 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005731 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 updatedSettings = true;
5733 }
5734
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005735 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 // Re installation failed. Restore old information
5737 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005738 if (newPackage != null) {
5739 removePackageLI(newPackage, true);
5740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005741 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005742 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005744 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 // Restore the old system information in Settings
5746 synchronized(mPackages) {
5747 if(updatedSettings) {
5748 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005749 mSettings.setInstallerPackageName(packageName,
5750 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 }
5752 mSettings.writeLP();
5753 }
5754 }
5755 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005756
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005757 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005758 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005759 int retCode;
5760 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5761 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5762 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005763 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005764 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5765 }
5766 }
5767 return PackageManager.INSTALL_SUCCEEDED;
5768 }
5769
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005770 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005771 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005772 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773 synchronized (mPackages) {
5774 //write settings. the installStatus will be incomplete at this stage.
5775 //note that the new package setting would have already been
5776 //added to mPackages. It hasn't been persisted yet.
5777 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5778 mSettings.writeLP();
5779 }
5780
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005781 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005782 != PackageManager.INSTALL_SUCCEEDED) {
5783 // Discontinue if moving dex files failed.
5784 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005786 if((res.returnCode = setPermissionsLI(newPackage))
5787 != PackageManager.INSTALL_SUCCEEDED) {
5788 if (mInstaller != null) {
5789 mInstaller.rmdex(newPackage.mScanPath);
5790 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005791 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005793 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005796 updatePermissionsLP(newPackage.packageName, newPackage,
5797 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 res.name = pkgName;
5799 res.uid = newPackage.applicationInfo.uid;
5800 res.pkg = newPackage;
5801 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005802 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5804 //to update install status
5805 mSettings.writeLP();
5806 }
5807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005808
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005809 private void installPackageLI(InstallArgs args,
5810 boolean newInstall, PackageInstalledInfo res) {
5811 int pFlags = args.flags;
5812 String installerPackageName = args.installerPackageName;
5813 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005814 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005815 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005816 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005817 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005818 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005819 // Result object to be returned
5820 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5821
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005822 // Retrieve PackageSettings and parse package
5823 int parseFlags = PackageParser.PARSE_CHATTY |
5824 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5825 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5826 parseFlags |= mDefParseFlags;
5827 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5828 pp.setSeparateProcesses(mSeparateProcesses);
5829 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5830 null, mMetrics, parseFlags);
5831 if (pkg == null) {
5832 res.returnCode = pp.getParseError();
5833 return;
5834 }
5835 String pkgName = res.name = pkg.packageName;
5836 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5837 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5838 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5839 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005841 }
5842 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5843 res.returnCode = pp.getParseError();
5844 return;
5845 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005846 // Get rid of all references to package scan path via parser.
5847 pp = null;
5848 String oldCodePath = null;
5849 boolean systemApp = false;
5850 synchronized (mPackages) {
5851 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005852 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5853 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005854 if (pkg.mOriginalPackages != null
5855 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005856 && mPackages.containsKey(oldName)) {
5857 // This package is derived from an original package,
5858 // and this device has been updating from that original
5859 // name. We must continue using the original name, so
5860 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005861 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005862 pkgName = pkg.packageName;
5863 replace = true;
5864 } else if (mPackages.containsKey(pkgName)) {
5865 // This package, under its official name, already exists
5866 // on the device; we should replace it.
5867 replace = true;
5868 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005869 }
5870 PackageSetting ps = mSettings.mPackages.get(pkgName);
5871 if (ps != null) {
5872 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5873 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5874 systemApp = (ps.pkg.applicationInfo.flags &
5875 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005876 }
5877 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005879
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005880 if (systemApp && onSd) {
5881 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005882 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005883 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5884 return;
5885 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005886
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005887 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5888 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5889 return;
5890 }
5891 // Set application objects path explicitly after the rename
5892 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005893 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005894 replacePackageLI(pkg, parseFlags, scanMode,
5895 installerPackageName, res);
5896 } else {
5897 installNewPackageLI(pkg, parseFlags, scanMode,
5898 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 }
5900 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005901
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005902 private int setPermissionsLI(PackageParser.Package newPackage) {
5903 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005904 int retCode = 0;
5905 // TODO Gross hack but fix later. Ideally move this to be a post installation
5906 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005907 if ((newPackage.applicationInfo.flags
5908 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5909 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005910 try {
5911 extractPublicFiles(newPackage, destResourceFile);
5912 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005913 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 -08005914 " forward-locked app.");
5915 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5916 } finally {
5917 //TODO clean up the extracted public files
5918 }
5919 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005920 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 newPackage.applicationInfo.uid);
5922 } else {
5923 final int filePermissions =
5924 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005925 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005926 newPackage.applicationInfo.uid);
5927 }
5928 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005929 // The permissions on the resource file was set when it was copied for
5930 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005933 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005934 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005935 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005936 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005937 // TODO Define new internal error
5938 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005939 }
5940 return PackageManager.INSTALL_SUCCEEDED;
5941 }
5942
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005943 private boolean isForwardLocked(PackageParser.Package pkg) {
5944 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 }
5946
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005947 private boolean isExternal(PackageParser.Package pkg) {
5948 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
5949 }
5950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 private void extractPublicFiles(PackageParser.Package newPackage,
5952 File publicZipFile) throws IOException {
5953 final ZipOutputStream publicZipOutStream =
5954 new ZipOutputStream(new FileOutputStream(publicZipFile));
5955 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5956
5957 // Copy manifest, resources.arsc and res directory to public zip
5958
5959 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5960 while (privateZipEntries.hasMoreElements()) {
5961 final ZipEntry zipEntry = privateZipEntries.nextElement();
5962 final String zipEntryName = zipEntry.getName();
5963 if ("AndroidManifest.xml".equals(zipEntryName)
5964 || "resources.arsc".equals(zipEntryName)
5965 || zipEntryName.startsWith("res/")) {
5966 try {
5967 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5968 } catch (IOException e) {
5969 try {
5970 publicZipOutStream.close();
5971 throw e;
5972 } finally {
5973 publicZipFile.delete();
5974 }
5975 }
5976 }
5977 }
5978
5979 publicZipOutStream.close();
5980 FileUtils.setPermissions(
5981 publicZipFile.getAbsolutePath(),
5982 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5983 -1, -1);
5984 }
5985
5986 private static void copyZipEntry(ZipEntry zipEntry,
5987 ZipFile inZipFile,
5988 ZipOutputStream outZipStream) throws IOException {
5989 byte[] buffer = new byte[4096];
5990 int num;
5991
5992 ZipEntry newEntry;
5993 if (zipEntry.getMethod() == ZipEntry.STORED) {
5994 // Preserve the STORED method of the input entry.
5995 newEntry = new ZipEntry(zipEntry);
5996 } else {
5997 // Create a new entry so that the compressed len is recomputed.
5998 newEntry = new ZipEntry(zipEntry.getName());
5999 }
6000 outZipStream.putNextEntry(newEntry);
6001
6002 InputStream data = inZipFile.getInputStream(zipEntry);
6003 while ((num = data.read(buffer)) > 0) {
6004 outZipStream.write(buffer, 0, num);
6005 }
6006 outZipStream.flush();
6007 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 private void deleteTempPackageFiles() {
6010 FilenameFilter filter = new FilenameFilter() {
6011 public boolean accept(File dir, String name) {
6012 return name.startsWith("vmdl") && name.endsWith(".tmp");
6013 }
6014 };
6015 String tmpFilesList[] = mAppInstallDir.list(filter);
6016 if(tmpFilesList == null) {
6017 return;
6018 }
6019 for(int i = 0; i < tmpFilesList.length; i++) {
6020 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6021 tmpFile.delete();
6022 }
6023 }
6024
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006025 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 File tmpPackageFile;
6027 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006028 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006030 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 return null;
6032 }
6033 try {
6034 FileUtils.setPermissions(
6035 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6036 -1, -1);
6037 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006038 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 return null;
6040 }
6041 return tmpPackageFile;
6042 }
6043
6044 public void deletePackage(final String packageName,
6045 final IPackageDeleteObserver observer,
6046 final int flags) {
6047 mContext.enforceCallingOrSelfPermission(
6048 android.Manifest.permission.DELETE_PACKAGES, null);
6049 // Queue up an async operation since the package deletion may take a little while.
6050 mHandler.post(new Runnable() {
6051 public void run() {
6052 mHandler.removeCallbacks(this);
6053 final boolean succeded = deletePackageX(packageName, true, true, flags);
6054 if (observer != null) {
6055 try {
6056 observer.packageDeleted(succeded);
6057 } catch (RemoteException e) {
6058 Log.i(TAG, "Observer no longer exists.");
6059 } //end catch
6060 } //end if
6061 } //end run
6062 });
6063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006065 /**
6066 * This method is an internal method that could be get invoked either
6067 * to delete an installed package or to clean up a failed installation.
6068 * After deleting an installed package, a broadcast is sent to notify any
6069 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006070 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 * installation wouldn't have sent the initial broadcast either
6072 * The key steps in deleting a package are
6073 * deleting the package information in internal structures like mPackages,
6074 * deleting the packages base directories through installd
6075 * updating mSettings to reflect current status
6076 * persisting settings for later use
6077 * sending a broadcast if necessary
6078 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6080 boolean deleteCodeAndResources, int flags) {
6081 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006082 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006084 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6085 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6086 try {
6087 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006088 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006089 return false;
6090 }
6091 } catch (RemoteException e) {
6092 }
6093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 synchronized (mInstallLock) {
6095 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
6096 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006098 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006099 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
6100 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
6101
6102 // If the removed package was a system update, the old system packaged
6103 // was re-enabled; we need to broadcast this information
6104 if (systemUpdate) {
6105 Bundle extras = new Bundle(1);
6106 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6107 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6108
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006109 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6110 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006112 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08006113 // Force a gc here.
6114 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006115 // Delete the resources here after sending the broadcast to let
6116 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006117 if (info.args != null) {
6118 synchronized (mInstallLock) {
6119 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006120 }
6121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 return res;
6123 }
6124
6125 static class PackageRemovedInfo {
6126 String removedPackage;
6127 int uid = -1;
6128 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006129 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006130 // Clean up resources deleted packages.
6131 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 void sendBroadcast(boolean fullRemove, boolean replacing) {
6134 Bundle extras = new Bundle(1);
6135 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6136 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6137 if (replacing) {
6138 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6139 }
6140 if (removedPackage != null) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006141 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142 }
6143 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006144 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 }
6146 }
6147 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 /*
6150 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6151 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006152 * 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 -08006153 * delete a partially installed application.
6154 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006155 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 int flags) {
6157 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006158 if (outInfo != null) {
6159 outInfo.removedPackage = packageName;
6160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 removePackageLI(p, true);
6162 // Retrieve object to delete permissions for shared user later on
6163 PackageSetting deletedPs;
6164 synchronized (mPackages) {
6165 deletedPs = mSettings.mPackages.get(packageName);
6166 }
6167 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006168 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006170 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006172 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 + packageName + ", retcode=" + retCode);
6174 // we don't consider this to be a failure of the core package deletion
6175 }
6176 } else {
6177 //for emulator
6178 PackageParser.Package pkg = mPackages.get(packageName);
6179 File dataDir = new File(pkg.applicationInfo.dataDir);
6180 dataDir.delete();
6181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 }
6183 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006184 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006185 schedulePackageCleaning(packageName);
6186
6187 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6188 if (outInfo != null) {
6189 outInfo.removedUid = mSettings.removePackageLP(packageName);
6190 }
6191 if (deletedPs != null) {
6192 updatePermissionsLP(deletedPs.name, null, false, false);
6193 if (deletedPs.sharedUser != null) {
6194 // remove permissions associated with package
6195 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6196 }
6197 }
6198 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006199 // remove from preferred activities.
6200 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6201 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6202 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6203 removed.add(pa);
6204 }
6205 }
6206 for (PreferredActivity pa : removed) {
6207 mSettings.mPreferredActivities.removeFilter(pa);
6208 }
6209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006211 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 }
6213 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 /*
6216 * Tries to delete system package.
6217 */
6218 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006219 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 ApplicationInfo applicationInfo = p.applicationInfo;
6221 //applicable for non-partially installed applications only
6222 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006223 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 return false;
6225 }
6226 PackageSetting ps = null;
6227 // Confirm if the system package has been updated
6228 // An updated system app can be deleted. This will also have to restore
6229 // the system pkg from system partition
6230 synchronized (mPackages) {
6231 ps = mSettings.getDisabledSystemPkg(p.packageName);
6232 }
6233 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006234 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 return false;
6236 } else {
6237 Log.i(TAG, "Deleting system pkg from data partition");
6238 }
6239 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006240 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006241 boolean deleteCodeAndResources = false;
6242 if (ps.versionCode < p.mVersionCode) {
6243 // Delete code and resources for downgrades
6244 deleteCodeAndResources = true;
6245 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6246 flags &= ~PackageManager.DONT_DELETE_DATA;
6247 }
6248 } else {
6249 // Preserve data by setting flag
6250 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6251 flags |= PackageManager.DONT_DELETE_DATA;
6252 }
6253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6255 if (!ret) {
6256 return false;
6257 }
6258 synchronized (mPackages) {
6259 // Reinstate the old system package
6260 mSettings.enableSystemPackageLP(p.packageName);
6261 }
6262 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006263 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006265 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006268 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 return false;
6270 }
6271 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006272 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006273 mSettings.writeLP();
6274 }
6275 return true;
6276 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6279 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6280 ApplicationInfo applicationInfo = p.applicationInfo;
6281 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006282 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 return false;
6284 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006285 if (outInfo != null) {
6286 outInfo.uid = applicationInfo.uid;
6287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288
6289 // Delete package data from internal structures and also remove data if flag is set
6290 removePackageDataLI(p, outInfo, flags);
6291
6292 // Delete application code and resources
6293 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006294 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006295 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006296 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006297 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6298 PackageManager.INSTALL_FORWARD_LOCK : 0;
6299 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006300 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006301 }
6302 return true;
6303 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 /*
6306 * This method handles package deletion in general
6307 */
6308 private boolean deletePackageLI(String packageName,
6309 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6310 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006311 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 return false;
6313 }
6314 PackageParser.Package p;
6315 boolean dataOnly = false;
6316 synchronized (mPackages) {
6317 p = mPackages.get(packageName);
6318 if (p == null) {
6319 //this retrieves partially installed apps
6320 dataOnly = true;
6321 PackageSetting ps = mSettings.mPackages.get(packageName);
6322 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006323 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 return false;
6325 }
6326 p = ps.pkg;
6327 }
6328 }
6329 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006330 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 return false;
6332 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 if (dataOnly) {
6335 // Delete application data first
6336 removePackageDataLI(p, outInfo, flags);
6337 return true;
6338 }
6339 // At this point the package should have ApplicationInfo associated with it
6340 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006341 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 return false;
6343 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006344 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6346 Log.i(TAG, "Removing system package:"+p.packageName);
6347 // When an updated system application is deleted we delete the existing resources as well and
6348 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006349 ret = deleteSystemPackageLI(p, flags, outInfo);
6350 } else {
6351 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006352 // Kill application pre-emptively especially for apps on sd.
6353 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006354 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006356 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 public void clearApplicationUserData(final String packageName,
6360 final IPackageDataObserver observer) {
6361 mContext.enforceCallingOrSelfPermission(
6362 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6363 // Queue up an async operation since the package deletion may take a little while.
6364 mHandler.post(new Runnable() {
6365 public void run() {
6366 mHandler.removeCallbacks(this);
6367 final boolean succeeded;
6368 synchronized (mInstallLock) {
6369 succeeded = clearApplicationUserDataLI(packageName);
6370 }
6371 if (succeeded) {
6372 // invoke DeviceStorageMonitor's update method to clear any notifications
6373 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6374 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6375 if (dsm != null) {
6376 dsm.updateMemory();
6377 }
6378 }
6379 if(observer != null) {
6380 try {
6381 observer.onRemoveCompleted(packageName, succeeded);
6382 } catch (RemoteException e) {
6383 Log.i(TAG, "Observer no longer exists.");
6384 }
6385 } //end if observer
6386 } //end run
6387 });
6388 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 private boolean clearApplicationUserDataLI(String packageName) {
6391 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006392 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 return false;
6394 }
6395 PackageParser.Package p;
6396 boolean dataOnly = false;
6397 synchronized (mPackages) {
6398 p = mPackages.get(packageName);
6399 if(p == null) {
6400 dataOnly = true;
6401 PackageSetting ps = mSettings.mPackages.get(packageName);
6402 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006403 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 return false;
6405 }
6406 p = ps.pkg;
6407 }
6408 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006409 boolean useEncryptedFSDir = false;
6410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 if(!dataOnly) {
6412 //need to check this only for fully installed applications
6413 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006414 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 return false;
6416 }
6417 final ApplicationInfo applicationInfo = p.applicationInfo;
6418 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006419 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 return false;
6421 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006422 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 }
6424 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006425 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006427 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 + packageName);
6429 return false;
6430 }
6431 }
6432 return true;
6433 }
6434
6435 public void deleteApplicationCacheFiles(final String packageName,
6436 final IPackageDataObserver observer) {
6437 mContext.enforceCallingOrSelfPermission(
6438 android.Manifest.permission.DELETE_CACHE_FILES, null);
6439 // Queue up an async operation since the package deletion may take a little while.
6440 mHandler.post(new Runnable() {
6441 public void run() {
6442 mHandler.removeCallbacks(this);
6443 final boolean succeded;
6444 synchronized (mInstallLock) {
6445 succeded = deleteApplicationCacheFilesLI(packageName);
6446 }
6447 if(observer != null) {
6448 try {
6449 observer.onRemoveCompleted(packageName, succeded);
6450 } catch (RemoteException e) {
6451 Log.i(TAG, "Observer no longer exists.");
6452 }
6453 } //end if observer
6454 } //end run
6455 });
6456 }
6457
6458 private boolean deleteApplicationCacheFilesLI(String packageName) {
6459 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006460 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006461 return false;
6462 }
6463 PackageParser.Package p;
6464 synchronized (mPackages) {
6465 p = mPackages.get(packageName);
6466 }
6467 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006468 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 return false;
6470 }
6471 final ApplicationInfo applicationInfo = p.applicationInfo;
6472 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006473 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 return false;
6475 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006476 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006478 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006480 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 + packageName);
6482 return false;
6483 }
6484 }
6485 return true;
6486 }
6487
6488 public void getPackageSizeInfo(final String packageName,
6489 final IPackageStatsObserver observer) {
6490 mContext.enforceCallingOrSelfPermission(
6491 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6492 // Queue up an async operation since the package deletion may take a little while.
6493 mHandler.post(new Runnable() {
6494 public void run() {
6495 mHandler.removeCallbacks(this);
6496 PackageStats lStats = new PackageStats(packageName);
6497 final boolean succeded;
6498 synchronized (mInstallLock) {
6499 succeded = getPackageSizeInfoLI(packageName, lStats);
6500 }
6501 if(observer != null) {
6502 try {
6503 observer.onGetStatsCompleted(lStats, succeded);
6504 } catch (RemoteException e) {
6505 Log.i(TAG, "Observer no longer exists.");
6506 }
6507 } //end if observer
6508 } //end run
6509 });
6510 }
6511
6512 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6513 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006514 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 return false;
6516 }
6517 PackageParser.Package p;
6518 boolean dataOnly = false;
6519 synchronized (mPackages) {
6520 p = mPackages.get(packageName);
6521 if(p == null) {
6522 dataOnly = true;
6523 PackageSetting ps = mSettings.mPackages.get(packageName);
6524 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006525 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 return false;
6527 }
6528 p = ps.pkg;
6529 }
6530 }
6531 String publicSrcDir = null;
6532 if(!dataOnly) {
6533 final ApplicationInfo applicationInfo = p.applicationInfo;
6534 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006535 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 return false;
6537 }
6538 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6539 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006540 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 if (mInstaller != null) {
6542 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006543 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 if (res < 0) {
6545 return false;
6546 } else {
6547 return true;
6548 }
6549 }
6550 return true;
6551 }
6552
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006554 public void addPackageToPreferred(String packageName) {
6555 mContext.enforceCallingOrSelfPermission(
6556 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006557 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006558 }
6559
6560 public void removePackageFromPreferred(String packageName) {
6561 mContext.enforceCallingOrSelfPermission(
6562 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006563 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006564 }
6565
6566 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006567 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 }
6569
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006570 int getUidTargetSdkVersionLockedLP(int uid) {
6571 Object obj = mSettings.getUserIdLP(uid);
6572 if (obj instanceof SharedUserSetting) {
6573 SharedUserSetting sus = (SharedUserSetting)obj;
6574 final int N = sus.packages.size();
6575 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6576 Iterator<PackageSetting> it = sus.packages.iterator();
6577 int i=0;
6578 while (it.hasNext()) {
6579 PackageSetting ps = it.next();
6580 if (ps.pkg != null) {
6581 int v = ps.pkg.applicationInfo.targetSdkVersion;
6582 if (v < vers) vers = v;
6583 }
6584 }
6585 return vers;
6586 } else if (obj instanceof PackageSetting) {
6587 PackageSetting ps = (PackageSetting)obj;
6588 if (ps.pkg != null) {
6589 return ps.pkg.applicationInfo.targetSdkVersion;
6590 }
6591 }
6592 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6593 }
6594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 public void addPreferredActivity(IntentFilter filter, int match,
6596 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006597 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006598 if (mContext.checkCallingOrSelfPermission(
6599 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6600 != PackageManager.PERMISSION_GRANTED) {
6601 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6602 < Build.VERSION_CODES.FROYO) {
6603 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6604 + Binder.getCallingUid());
6605 return;
6606 }
6607 mContext.enforceCallingOrSelfPermission(
6608 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6609 }
6610
6611 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6613 mSettings.mPreferredActivities.addFilter(
6614 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006615 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 }
6617 }
6618
Satish Sampath8dbe6122009-06-02 23:35:54 +01006619 public void replacePreferredActivity(IntentFilter filter, int match,
6620 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006621 if (filter.countActions() != 1) {
6622 throw new IllegalArgumentException(
6623 "replacePreferredActivity expects filter to have only 1 action.");
6624 }
6625 if (filter.countCategories() != 1) {
6626 throw new IllegalArgumentException(
6627 "replacePreferredActivity expects filter to have only 1 category.");
6628 }
6629 if (filter.countDataAuthorities() != 0
6630 || filter.countDataPaths() != 0
6631 || filter.countDataSchemes() != 0
6632 || filter.countDataTypes() != 0) {
6633 throw new IllegalArgumentException(
6634 "replacePreferredActivity expects filter to have no data authorities, " +
6635 "paths, schemes or types.");
6636 }
6637 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006638 if (mContext.checkCallingOrSelfPermission(
6639 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6640 != PackageManager.PERMISSION_GRANTED) {
6641 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6642 < Build.VERSION_CODES.FROYO) {
6643 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6644 + Binder.getCallingUid());
6645 return;
6646 }
6647 mContext.enforceCallingOrSelfPermission(
6648 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6649 }
6650
Satish Sampath8dbe6122009-06-02 23:35:54 +01006651 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6652 String action = filter.getAction(0);
6653 String category = filter.getCategory(0);
6654 while (it.hasNext()) {
6655 PreferredActivity pa = it.next();
6656 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6657 it.remove();
6658 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6659 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6660 }
6661 }
6662 addPreferredActivity(filter, match, set, activity);
6663 }
6664 }
6665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006668 int uid = Binder.getCallingUid();
6669 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006670 if (pkg == null || pkg.applicationInfo.uid != uid) {
6671 if (mContext.checkCallingOrSelfPermission(
6672 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6673 != PackageManager.PERMISSION_GRANTED) {
6674 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6675 < Build.VERSION_CODES.FROYO) {
6676 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6677 + Binder.getCallingUid());
6678 return;
6679 }
6680 mContext.enforceCallingOrSelfPermission(
6681 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6682 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006683 }
6684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006686 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 }
6688 }
6689 }
6690
6691 boolean clearPackagePreferredActivitiesLP(String packageName) {
6692 boolean changed = false;
6693 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6694 while (it.hasNext()) {
6695 PreferredActivity pa = it.next();
6696 if (pa.mActivity.getPackageName().equals(packageName)) {
6697 it.remove();
6698 changed = true;
6699 }
6700 }
6701 return changed;
6702 }
6703
6704 public int getPreferredActivities(List<IntentFilter> outFilters,
6705 List<ComponentName> outActivities, String packageName) {
6706
6707 int num = 0;
6708 synchronized (mPackages) {
6709 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6710 while (it.hasNext()) {
6711 PreferredActivity pa = it.next();
6712 if (packageName == null
6713 || pa.mActivity.getPackageName().equals(packageName)) {
6714 if (outFilters != null) {
6715 outFilters.add(new IntentFilter(pa));
6716 }
6717 if (outActivities != null) {
6718 outActivities.add(pa.mActivity);
6719 }
6720 }
6721 }
6722 }
6723
6724 return num;
6725 }
6726
6727 public void setApplicationEnabledSetting(String appPackageName,
6728 int newState, int flags) {
6729 setEnabledSetting(appPackageName, null, newState, flags);
6730 }
6731
6732 public void setComponentEnabledSetting(ComponentName componentName,
6733 int newState, int flags) {
6734 setEnabledSetting(componentName.getPackageName(),
6735 componentName.getClassName(), newState, flags);
6736 }
6737
6738 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006739 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6741 || newState == COMPONENT_ENABLED_STATE_ENABLED
6742 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6743 throw new IllegalArgumentException("Invalid new component state: "
6744 + newState);
6745 }
6746 PackageSetting pkgSetting;
6747 final int uid = Binder.getCallingUid();
6748 final int permission = mContext.checkCallingPermission(
6749 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6750 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006751 boolean sendNow = false;
6752 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006753 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006755 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006756 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006757 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006759 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006761 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006762 }
6763 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006764 "Unknown component: " + packageName
6765 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 }
6767 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6768 throw new SecurityException(
6769 "Permission Denial: attempt to change component state from pid="
6770 + Binder.getCallingPid()
6771 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6772 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006773 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006775 if (pkgSetting.enabled == newState) {
6776 // Nothing to do
6777 return;
6778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006779 pkgSetting.enabled = newState;
6780 } else {
6781 // We're dealing with a component level state change
6782 switch (newState) {
6783 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006784 if (!pkgSetting.enableComponentLP(className)) {
6785 return;
6786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 break;
6788 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006789 if (!pkgSetting.disableComponentLP(className)) {
6790 return;
6791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006792 break;
6793 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006794 if (!pkgSetting.restoreComponentLP(className)) {
6795 return;
6796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006797 break;
6798 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006799 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006800 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 }
6802 }
6803 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006804 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006805 components = mPendingBroadcasts.get(packageName);
6806 boolean newPackage = components == null;
6807 if (newPackage) {
6808 components = new ArrayList<String>();
6809 }
6810 if (!components.contains(componentName)) {
6811 components.add(componentName);
6812 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006813 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6814 sendNow = true;
6815 // Purge entry from pending broadcast list if another one exists already
6816 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006817 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006818 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006819 if (newPackage) {
6820 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006821 }
6822 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6823 // Schedule a message
6824 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6825 }
6826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006827 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006829 long callingId = Binder.clearCallingIdentity();
6830 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006831 if (sendNow) {
6832 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006833 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006835 } finally {
6836 Binder.restoreCallingIdentity(callingId);
6837 }
6838 }
6839
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006840 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006841 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6842 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6843 + " components=" + componentNames);
6844 Bundle extras = new Bundle(4);
6845 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6846 String nameList[] = new String[componentNames.size()];
6847 componentNames.toArray(nameList);
6848 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006849 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6850 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006851 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006852 }
6853
Jacek Surazski65e13172009-04-28 15:26:38 +02006854 public String getInstallerPackageName(String packageName) {
6855 synchronized (mPackages) {
6856 PackageSetting pkg = mSettings.mPackages.get(packageName);
6857 if (pkg == null) {
6858 throw new IllegalArgumentException("Unknown package: " + packageName);
6859 }
6860 return pkg.installerPackageName;
6861 }
6862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006864 public int getApplicationEnabledSetting(String appPackageName) {
6865 synchronized (mPackages) {
6866 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6867 if (pkg == null) {
6868 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6869 }
6870 return pkg.enabled;
6871 }
6872 }
6873
6874 public int getComponentEnabledSetting(ComponentName componentName) {
6875 synchronized (mPackages) {
6876 final String packageNameStr = componentName.getPackageName();
6877 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6878 if (pkg == null) {
6879 throw new IllegalArgumentException("Unknown component: " + componentName);
6880 }
6881 final String classNameStr = componentName.getClassName();
6882 return pkg.currentEnabledStateLP(classNameStr);
6883 }
6884 }
6885
6886 public void enterSafeMode() {
6887 if (!mSystemReady) {
6888 mSafeMode = true;
6889 }
6890 }
6891
6892 public void systemReady() {
6893 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006894
6895 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006896 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006897 mContext.getContentResolver(),
6898 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006899 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006900 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006901 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 }
6904
6905 public boolean isSafeMode() {
6906 return mSafeMode;
6907 }
6908
6909 public boolean hasSystemUidErrors() {
6910 return mHasSystemUidErrors;
6911 }
6912
6913 static String arrayToString(int[] array) {
6914 StringBuffer buf = new StringBuffer(128);
6915 buf.append('[');
6916 if (array != null) {
6917 for (int i=0; i<array.length; i++) {
6918 if (i > 0) buf.append(", ");
6919 buf.append(array[i]);
6920 }
6921 }
6922 buf.append(']');
6923 return buf.toString();
6924 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 @Override
6927 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6928 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6929 != PackageManager.PERMISSION_GRANTED) {
6930 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6931 + Binder.getCallingPid()
6932 + ", uid=" + Binder.getCallingUid()
6933 + " without permission "
6934 + android.Manifest.permission.DUMP);
6935 return;
6936 }
6937
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006938 String packageName = null;
6939
6940 int opti = 0;
6941 while (opti < args.length) {
6942 String opt = args[opti];
6943 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6944 break;
6945 }
6946 opti++;
6947 if ("-a".equals(opt)) {
6948 // Right now we only know how to print all.
6949 } else if ("-h".equals(opt)) {
6950 pw.println("Package manager dump options:");
6951 pw.println(" [-h] [cmd] ...");
6952 pw.println(" cmd may be one of:");
6953 pw.println(" [package.name]: info about given package");
6954 return;
6955 } else {
6956 pw.println("Unknown argument: " + opt + "; use -h for help");
6957 }
6958 }
6959
6960 // Is the caller requesting to dump a particular piece of data?
6961 if (opti < args.length) {
6962 String cmd = args[opti];
6963 opti++;
6964 // Is this a package name?
6965 if ("android".equals(cmd) || cmd.contains(".")) {
6966 packageName = cmd;
6967 }
6968 }
6969
6970 boolean printedTitle = false;
6971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006972 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006973 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6974 printedTitle = true;
6975 }
6976 if (mReceivers.dump(pw, printedTitle
6977 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6978 " ", packageName)) {
6979 printedTitle = true;
6980 }
6981 if (mServices.dump(pw, printedTitle
6982 ? "\nService Resolver Table:" : "Service Resolver Table:",
6983 " ", packageName)) {
6984 printedTitle = true;
6985 }
6986 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6987 ? "\nPreferred Activities:" : "Preferred Activities:",
6988 " ", packageName)) {
6989 printedTitle = true;
6990 }
6991 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006992 {
6993 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006994 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6995 continue;
6996 }
6997 if (!printedSomething) {
6998 if (printedTitle) pw.println(" ");
6999 pw.println("Permissions:");
7000 printedSomething = true;
7001 printedTitle = true;
7002 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007003 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7004 pw.print(Integer.toHexString(System.identityHashCode(p)));
7005 pw.println("):");
7006 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7007 pw.print(" uid="); pw.print(p.uid);
7008 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007009 pw.print(" type="); pw.print(p.type);
7010 pw.print(" prot="); pw.println(p.protectionLevel);
7011 if (p.packageSetting != null) {
7012 pw.print(" packageSetting="); pw.println(p.packageSetting);
7013 }
7014 if (p.perm != null) {
7015 pw.print(" perm="); pw.println(p.perm);
7016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017 }
7018 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007019 printedSomething = false;
7020 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 {
7022 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007023 if (packageName != null && !packageName.equals(ps.realName)
7024 && !packageName.equals(ps.name)) {
7025 continue;
7026 }
7027 if (!printedSomething) {
7028 if (printedTitle) pw.println(" ");
7029 pw.println("Packages:");
7030 printedSomething = true;
7031 printedTitle = true;
7032 }
7033 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007034 pw.print(" Package [");
7035 pw.print(ps.realName != null ? ps.realName : ps.name);
7036 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007037 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7038 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007039 if (ps.realName != null) {
7040 pw.print(" compat name="); pw.println(ps.name);
7041 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007042 pw.print(" userId="); pw.print(ps.userId);
7043 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7044 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7045 pw.print(" pkg="); pw.println(ps.pkg);
7046 pw.print(" codePath="); pw.println(ps.codePathString);
7047 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007048 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007049 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007050 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007051 pw.print(" supportsScreens=[");
7052 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007053 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007054 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007055 if (!first) pw.print(", ");
7056 first = false;
7057 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007058 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007059 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007060 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007061 if (!first) pw.print(", ");
7062 first = false;
7063 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007064 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007065 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007066 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007067 if (!first) pw.print(", ");
7068 first = false;
7069 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007070 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007071 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007072 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007073 if (!first) pw.print(", ");
7074 first = false;
7075 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007076 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007077 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007078 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7079 if (!first) pw.print(", ");
7080 first = false;
7081 pw.print("anyDensity");
7082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007084 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007085 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7086 pw.print(" signatures="); pw.println(ps.signatures);
7087 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007088 pw.print(" haveGids="); pw.println(ps.haveGids);
7089 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007090 pw.print(" installStatus="); pw.print(ps.installStatus);
7091 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 if (ps.disabledComponents.size() > 0) {
7093 pw.println(" disabledComponents:");
7094 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007095 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007096 }
7097 }
7098 if (ps.enabledComponents.size() > 0) {
7099 pw.println(" enabledComponents:");
7100 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007101 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007102 }
7103 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007104 if (ps.grantedPermissions.size() > 0) {
7105 pw.println(" grantedPermissions:");
7106 for (String s : ps.grantedPermissions) {
7107 pw.print(" "); pw.println(s);
7108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007110 }
7111 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007112 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007113 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007114 for (HashMap.Entry<String, String> e
7115 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007116 if (packageName != null && !packageName.equals(e.getKey())
7117 && !packageName.equals(e.getValue())) {
7118 continue;
7119 }
7120 if (!printedSomething) {
7121 if (printedTitle) pw.println(" ");
7122 pw.println("Renamed packages:");
7123 printedSomething = true;
7124 printedTitle = true;
7125 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007126 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7127 pw.println(e.getValue());
7128 }
7129 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007130 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007131 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007132 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007133 if (packageName != null && !packageName.equals(ps.realName)
7134 && !packageName.equals(ps.name)) {
7135 continue;
7136 }
7137 if (!printedSomething) {
7138 if (printedTitle) pw.println(" ");
7139 pw.println("Hidden system packages:");
7140 printedSomething = true;
7141 printedTitle = true;
7142 }
7143 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007144 pw.print(ps.realName != null ? ps.realName : ps.name);
7145 pw.print("] (");
7146 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7147 pw.println("):");
7148 if (ps.realName != null) {
7149 pw.print(" compat name="); pw.println(ps.name);
7150 }
7151 pw.print(" userId="); pw.println(ps.userId);
7152 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7153 pw.print(" codePath="); pw.println(ps.codePathString);
7154 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7155 }
7156 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007157 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007158 {
7159 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007160 if (packageName != null && su != packageSharedUser) {
7161 continue;
7162 }
7163 if (!printedSomething) {
7164 if (printedTitle) pw.println(" ");
7165 pw.println("Shared users:");
7166 printedSomething = true;
7167 printedTitle = true;
7168 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007169 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7170 pw.print(Integer.toHexString(System.identityHashCode(su)));
7171 pw.println("):");
7172 pw.print(" userId="); pw.print(su.userId);
7173 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007174 pw.println(" grantedPermissions:");
7175 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007176 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 }
7179 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007180
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007181 if (packageName == null) {
7182 if (printedTitle) pw.println(" ");
7183 printedTitle = true;
7184 pw.println("Settings parse messages:");
7185 pw.println(mSettings.mReadMessages.toString());
7186
7187 pw.println(" ");
7188 pw.println("Package warning messages:");
7189 File fname = getSettingsProblemFile();
7190 FileInputStream in;
7191 try {
7192 in = new FileInputStream(fname);
7193 int avail = in.available();
7194 byte[] data = new byte[avail];
7195 in.read(data);
7196 pw.println(new String(data));
7197 } catch (FileNotFoundException e) {
7198 } catch (IOException e) {
7199 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007201 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007202
7203 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007204 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007205 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007206 if (packageName != null && !packageName.equals(p.info.packageName)) {
7207 continue;
7208 }
7209 if (!printedSomething) {
7210 if (printedTitle) pw.println(" ");
7211 pw.println("Registered ContentProviders:");
7212 printedSomething = true;
7213 printedTitle = true;
7214 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007215 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007216 pw.println(p.toString());
7217 }
7218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 }
7220
7221 static final class BasePermission {
7222 final static int TYPE_NORMAL = 0;
7223 final static int TYPE_BUILTIN = 1;
7224 final static int TYPE_DYNAMIC = 2;
7225
7226 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007227 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007228 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007229 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007230 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007231 PackageParser.Permission perm;
7232 PermissionInfo pendingInfo;
7233 int uid;
7234 int[] gids;
7235
7236 BasePermission(String _name, String _sourcePackage, int _type) {
7237 name = _name;
7238 sourcePackage = _sourcePackage;
7239 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007240 // Default to most conservative protection level.
7241 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7242 }
7243
7244 public String toString() {
7245 return "BasePermission{"
7246 + Integer.toHexString(System.identityHashCode(this))
7247 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007248 }
7249 }
7250
7251 static class PackageSignatures {
7252 private Signature[] mSignatures;
7253
7254 PackageSignatures(Signature[] sigs) {
7255 assignSignatures(sigs);
7256 }
7257
7258 PackageSignatures() {
7259 }
7260
7261 void writeXml(XmlSerializer serializer, String tagName,
7262 ArrayList<Signature> pastSignatures) throws IOException {
7263 if (mSignatures == null) {
7264 return;
7265 }
7266 serializer.startTag(null, tagName);
7267 serializer.attribute(null, "count",
7268 Integer.toString(mSignatures.length));
7269 for (int i=0; i<mSignatures.length; i++) {
7270 serializer.startTag(null, "cert");
7271 final Signature sig = mSignatures[i];
7272 final int sigHash = sig.hashCode();
7273 final int numPast = pastSignatures.size();
7274 int j;
7275 for (j=0; j<numPast; j++) {
7276 Signature pastSig = pastSignatures.get(j);
7277 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7278 serializer.attribute(null, "index", Integer.toString(j));
7279 break;
7280 }
7281 }
7282 if (j >= numPast) {
7283 pastSignatures.add(sig);
7284 serializer.attribute(null, "index", Integer.toString(numPast));
7285 serializer.attribute(null, "key", sig.toCharsString());
7286 }
7287 serializer.endTag(null, "cert");
7288 }
7289 serializer.endTag(null, tagName);
7290 }
7291
7292 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7293 throws IOException, XmlPullParserException {
7294 String countStr = parser.getAttributeValue(null, "count");
7295 if (countStr == null) {
7296 reportSettingsProblem(Log.WARN,
7297 "Error in package manager settings: <signatures> has"
7298 + " no count at " + parser.getPositionDescription());
7299 XmlUtils.skipCurrentTag(parser);
7300 }
7301 final int count = Integer.parseInt(countStr);
7302 mSignatures = new Signature[count];
7303 int pos = 0;
7304
7305 int outerDepth = parser.getDepth();
7306 int type;
7307 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7308 && (type != XmlPullParser.END_TAG
7309 || parser.getDepth() > outerDepth)) {
7310 if (type == XmlPullParser.END_TAG
7311 || type == XmlPullParser.TEXT) {
7312 continue;
7313 }
7314
7315 String tagName = parser.getName();
7316 if (tagName.equals("cert")) {
7317 if (pos < count) {
7318 String index = parser.getAttributeValue(null, "index");
7319 if (index != null) {
7320 try {
7321 int idx = Integer.parseInt(index);
7322 String key = parser.getAttributeValue(null, "key");
7323 if (key == null) {
7324 if (idx >= 0 && idx < pastSignatures.size()) {
7325 Signature sig = pastSignatures.get(idx);
7326 if (sig != null) {
7327 mSignatures[pos] = pastSignatures.get(idx);
7328 pos++;
7329 } else {
7330 reportSettingsProblem(Log.WARN,
7331 "Error in package manager settings: <cert> "
7332 + "index " + index + " is not defined at "
7333 + parser.getPositionDescription());
7334 }
7335 } else {
7336 reportSettingsProblem(Log.WARN,
7337 "Error in package manager settings: <cert> "
7338 + "index " + index + " is out of bounds at "
7339 + parser.getPositionDescription());
7340 }
7341 } else {
7342 while (pastSignatures.size() <= idx) {
7343 pastSignatures.add(null);
7344 }
7345 Signature sig = new Signature(key);
7346 pastSignatures.set(idx, sig);
7347 mSignatures[pos] = sig;
7348 pos++;
7349 }
7350 } catch (NumberFormatException e) {
7351 reportSettingsProblem(Log.WARN,
7352 "Error in package manager settings: <cert> "
7353 + "index " + index + " is not a number at "
7354 + parser.getPositionDescription());
7355 }
7356 } else {
7357 reportSettingsProblem(Log.WARN,
7358 "Error in package manager settings: <cert> has"
7359 + " no index at " + parser.getPositionDescription());
7360 }
7361 } else {
7362 reportSettingsProblem(Log.WARN,
7363 "Error in package manager settings: too "
7364 + "many <cert> tags, expected " + count
7365 + " at " + parser.getPositionDescription());
7366 }
7367 } else {
7368 reportSettingsProblem(Log.WARN,
7369 "Unknown element under <cert>: "
7370 + parser.getName());
7371 }
7372 XmlUtils.skipCurrentTag(parser);
7373 }
7374
7375 if (pos < count) {
7376 // Should never happen -- there is an error in the written
7377 // settings -- but if it does we don't want to generate
7378 // a bad array.
7379 Signature[] newSigs = new Signature[pos];
7380 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7381 mSignatures = newSigs;
7382 }
7383 }
7384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007385 private void assignSignatures(Signature[] sigs) {
7386 if (sigs == null) {
7387 mSignatures = null;
7388 return;
7389 }
7390 mSignatures = new Signature[sigs.length];
7391 for (int i=0; i<sigs.length; i++) {
7392 mSignatures[i] = sigs[i];
7393 }
7394 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007396 @Override
7397 public String toString() {
7398 StringBuffer buf = new StringBuffer(128);
7399 buf.append("PackageSignatures{");
7400 buf.append(Integer.toHexString(System.identityHashCode(this)));
7401 buf.append(" [");
7402 if (mSignatures != null) {
7403 for (int i=0; i<mSignatures.length; i++) {
7404 if (i > 0) buf.append(", ");
7405 buf.append(Integer.toHexString(
7406 System.identityHashCode(mSignatures[i])));
7407 }
7408 }
7409 buf.append("]}");
7410 return buf.toString();
7411 }
7412 }
7413
7414 static class PreferredActivity extends IntentFilter {
7415 final int mMatch;
7416 final String[] mSetPackages;
7417 final String[] mSetClasses;
7418 final String[] mSetComponents;
7419 final ComponentName mActivity;
7420 final String mShortActivity;
7421 String mParseError;
7422
7423 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7424 ComponentName activity) {
7425 super(filter);
7426 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7427 mActivity = activity;
7428 mShortActivity = activity.flattenToShortString();
7429 mParseError = null;
7430 if (set != null) {
7431 final int N = set.length;
7432 String[] myPackages = new String[N];
7433 String[] myClasses = new String[N];
7434 String[] myComponents = new String[N];
7435 for (int i=0; i<N; i++) {
7436 ComponentName cn = set[i];
7437 if (cn == null) {
7438 mSetPackages = null;
7439 mSetClasses = null;
7440 mSetComponents = null;
7441 return;
7442 }
7443 myPackages[i] = cn.getPackageName().intern();
7444 myClasses[i] = cn.getClassName().intern();
7445 myComponents[i] = cn.flattenToShortString().intern();
7446 }
7447 mSetPackages = myPackages;
7448 mSetClasses = myClasses;
7449 mSetComponents = myComponents;
7450 } else {
7451 mSetPackages = null;
7452 mSetClasses = null;
7453 mSetComponents = null;
7454 }
7455 }
7456
7457 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7458 IOException {
7459 mShortActivity = parser.getAttributeValue(null, "name");
7460 mActivity = ComponentName.unflattenFromString(mShortActivity);
7461 if (mActivity == null) {
7462 mParseError = "Bad activity name " + mShortActivity;
7463 }
7464 String matchStr = parser.getAttributeValue(null, "match");
7465 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7466 String setCountStr = parser.getAttributeValue(null, "set");
7467 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7468
7469 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7470 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7471 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7472
7473 int setPos = 0;
7474
7475 int outerDepth = parser.getDepth();
7476 int type;
7477 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7478 && (type != XmlPullParser.END_TAG
7479 || parser.getDepth() > outerDepth)) {
7480 if (type == XmlPullParser.END_TAG
7481 || type == XmlPullParser.TEXT) {
7482 continue;
7483 }
7484
7485 String tagName = parser.getName();
7486 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7487 // + parser.getDepth() + " tag=" + tagName);
7488 if (tagName.equals("set")) {
7489 String name = parser.getAttributeValue(null, "name");
7490 if (name == null) {
7491 if (mParseError == null) {
7492 mParseError = "No name in set tag in preferred activity "
7493 + mShortActivity;
7494 }
7495 } else if (setPos >= setCount) {
7496 if (mParseError == null) {
7497 mParseError = "Too many set tags in preferred activity "
7498 + mShortActivity;
7499 }
7500 } else {
7501 ComponentName cn = ComponentName.unflattenFromString(name);
7502 if (cn == null) {
7503 if (mParseError == null) {
7504 mParseError = "Bad set name " + name + " in preferred activity "
7505 + mShortActivity;
7506 }
7507 } else {
7508 myPackages[setPos] = cn.getPackageName();
7509 myClasses[setPos] = cn.getClassName();
7510 myComponents[setPos] = name;
7511 setPos++;
7512 }
7513 }
7514 XmlUtils.skipCurrentTag(parser);
7515 } else if (tagName.equals("filter")) {
7516 //Log.i(TAG, "Starting to parse filter...");
7517 readFromXml(parser);
7518 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7519 // + parser.getDepth() + " tag=" + parser.getName());
7520 } else {
7521 reportSettingsProblem(Log.WARN,
7522 "Unknown element under <preferred-activities>: "
7523 + parser.getName());
7524 XmlUtils.skipCurrentTag(parser);
7525 }
7526 }
7527
7528 if (setPos != setCount) {
7529 if (mParseError == null) {
7530 mParseError = "Not enough set tags (expected " + setCount
7531 + " but found " + setPos + ") in " + mShortActivity;
7532 }
7533 }
7534
7535 mSetPackages = myPackages;
7536 mSetClasses = myClasses;
7537 mSetComponents = myComponents;
7538 }
7539
7540 public void writeToXml(XmlSerializer serializer) throws IOException {
7541 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7542 serializer.attribute(null, "name", mShortActivity);
7543 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7544 serializer.attribute(null, "set", Integer.toString(NS));
7545 for (int s=0; s<NS; s++) {
7546 serializer.startTag(null, "set");
7547 serializer.attribute(null, "name", mSetComponents[s]);
7548 serializer.endTag(null, "set");
7549 }
7550 serializer.startTag(null, "filter");
7551 super.writeToXml(serializer);
7552 serializer.endTag(null, "filter");
7553 }
7554
7555 boolean sameSet(List<ResolveInfo> query, int priority) {
7556 if (mSetPackages == null) return false;
7557 final int NQ = query.size();
7558 final int NS = mSetPackages.length;
7559 int numMatch = 0;
7560 for (int i=0; i<NQ; i++) {
7561 ResolveInfo ri = query.get(i);
7562 if (ri.priority != priority) continue;
7563 ActivityInfo ai = ri.activityInfo;
7564 boolean good = false;
7565 for (int j=0; j<NS; j++) {
7566 if (mSetPackages[j].equals(ai.packageName)
7567 && mSetClasses[j].equals(ai.name)) {
7568 numMatch++;
7569 good = true;
7570 break;
7571 }
7572 }
7573 if (!good) return false;
7574 }
7575 return numMatch == NS;
7576 }
7577 }
7578
7579 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007580 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582 HashSet<String> grantedPermissions = new HashSet<String>();
7583 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007586 setFlags(pkgFlags);
7587 }
7588
7589 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007590 this.pkgFlags = pkgFlags & (
7591 ApplicationInfo.FLAG_SYSTEM |
7592 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007593 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007594 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007595 }
7596 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007598 /**
7599 * Settings base class for pending and resolved classes.
7600 */
7601 static class PackageSettingBase extends GrantedPermissions {
7602 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007603 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007604 File codePath;
7605 String codePathString;
7606 File resourcePath;
7607 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 private long timeStamp;
7609 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007610 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007612 boolean uidError;
7613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007614 PackageSignatures signatures = new PackageSignatures();
7615
7616 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007617 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007619 /* Explicitly disabled components */
7620 HashSet<String> disabledComponents = new HashSet<String>(0);
7621 /* Explicitly enabled components */
7622 HashSet<String> enabledComponents = new HashSet<String>(0);
7623 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7624 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007625
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007626 PackageSettingBase origPackage;
7627
Jacek Surazski65e13172009-04-28 15:26:38 +02007628 /* package name of the app that installed this package */
7629 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007630
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007631 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007632 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007633 super(pkgFlags);
7634 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007635 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007636 init(codePath, resourcePath, pVersionCode);
7637 }
7638
7639 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007640 this.codePath = codePath;
7641 this.codePathString = codePath.toString();
7642 this.resourcePath = resourcePath;
7643 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007644 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007646
Jacek Surazski65e13172009-04-28 15:26:38 +02007647 public void setInstallerPackageName(String packageName) {
7648 installerPackageName = packageName;
7649 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007650
Jacek Surazski65e13172009-04-28 15:26:38 +02007651 String getInstallerPackageName() {
7652 return installerPackageName;
7653 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007655 public void setInstallStatus(int newStatus) {
7656 installStatus = newStatus;
7657 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007659 public int getInstallStatus() {
7660 return installStatus;
7661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007663 public void setTimeStamp(long newStamp) {
7664 if (newStamp != timeStamp) {
7665 timeStamp = newStamp;
7666 timeStampString = Long.toString(newStamp);
7667 }
7668 }
7669
7670 public void setTimeStamp(long newStamp, String newStampStr) {
7671 timeStamp = newStamp;
7672 timeStampString = newStampStr;
7673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 public long getTimeStamp() {
7676 return timeStamp;
7677 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679 public String getTimeStampStr() {
7680 return timeStampString;
7681 }
7682
7683 public void copyFrom(PackageSettingBase base) {
7684 grantedPermissions = base.grantedPermissions;
7685 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 timeStamp = base.timeStamp;
7688 timeStampString = base.timeStampString;
7689 signatures = base.signatures;
7690 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007691 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 disabledComponents = base.disabledComponents;
7693 enabledComponents = base.enabledComponents;
7694 enabled = base.enabled;
7695 installStatus = base.installStatus;
7696 }
7697
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007698 boolean enableComponentLP(String componentClassName) {
7699 boolean changed = disabledComponents.remove(componentClassName);
7700 changed |= enabledComponents.add(componentClassName);
7701 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007702 }
7703
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007704 boolean disableComponentLP(String componentClassName) {
7705 boolean changed = enabledComponents.remove(componentClassName);
7706 changed |= disabledComponents.add(componentClassName);
7707 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 }
7709
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007710 boolean restoreComponentLP(String componentClassName) {
7711 boolean changed = enabledComponents.remove(componentClassName);
7712 changed |= disabledComponents.remove(componentClassName);
7713 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 }
7715
7716 int currentEnabledStateLP(String componentName) {
7717 if (enabledComponents.contains(componentName)) {
7718 return COMPONENT_ENABLED_STATE_ENABLED;
7719 } else if (disabledComponents.contains(componentName)) {
7720 return COMPONENT_ENABLED_STATE_DISABLED;
7721 } else {
7722 return COMPONENT_ENABLED_STATE_DEFAULT;
7723 }
7724 }
7725 }
7726
7727 /**
7728 * Settings data for a particular package we know about.
7729 */
7730 static final class PackageSetting extends PackageSettingBase {
7731 int userId;
7732 PackageParser.Package pkg;
7733 SharedUserSetting sharedUser;
7734
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007735 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007736 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007737 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 @Override
7741 public String toString() {
7742 return "PackageSetting{"
7743 + Integer.toHexString(System.identityHashCode(this))
7744 + " " + name + "/" + userId + "}";
7745 }
7746 }
7747
7748 /**
7749 * Settings data for a particular shared user ID we know about.
7750 */
7751 static final class SharedUserSetting extends GrantedPermissions {
7752 final String name;
7753 int userId;
7754 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7755 final PackageSignatures signatures = new PackageSignatures();
7756
7757 SharedUserSetting(String _name, int _pkgFlags) {
7758 super(_pkgFlags);
7759 name = _name;
7760 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007762 @Override
7763 public String toString() {
7764 return "SharedUserSetting{"
7765 + Integer.toHexString(System.identityHashCode(this))
7766 + " " + name + "/" + userId + "}";
7767 }
7768 }
7769
7770 /**
7771 * Holds information about dynamic settings.
7772 */
7773 private static final class Settings {
7774 private final File mSettingsFilename;
7775 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007776 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007777 private final HashMap<String, PackageSetting> mPackages =
7778 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 // List of replaced system applications
7780 final HashMap<String, PackageSetting> mDisabledSysPackages =
7781 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007782
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007783 // These are the last platform API version we were using for
7784 // the apps installed on internal and external storage. It is
7785 // used to grant newer permissions one time during a system upgrade.
7786 int mInternalSdkPlatform;
7787 int mExternalSdkPlatform;
7788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007789 // The user's preferred activities associated with particular intent
7790 // filters.
7791 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7792 new IntentResolver<PreferredActivity, PreferredActivity>() {
7793 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007794 protected String packageForFilter(PreferredActivity filter) {
7795 return filter.mActivity.getPackageName();
7796 }
7797 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007798 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007799 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007800 out.print(prefix); out.print(
7801 Integer.toHexString(System.identityHashCode(filter)));
7802 out.print(' ');
7803 out.print(filter.mActivity.flattenToShortString());
7804 out.print(" match=0x");
7805 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007806 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007807 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007808 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007809 out.print(prefix); out.print(" ");
7810 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007811 }
7812 }
7813 }
7814 };
7815 private final HashMap<String, SharedUserSetting> mSharedUsers =
7816 new HashMap<String, SharedUserSetting>();
7817 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7818 private final SparseArray<Object> mOtherUserIds =
7819 new SparseArray<Object>();
7820
7821 // For reading/writing settings file.
7822 private final ArrayList<Signature> mPastSignatures =
7823 new ArrayList<Signature>();
7824
7825 // Mapping from permission names to info about them.
7826 final HashMap<String, BasePermission> mPermissions =
7827 new HashMap<String, BasePermission>();
7828
7829 // Mapping from permission tree names to info about them.
7830 final HashMap<String, BasePermission> mPermissionTrees =
7831 new HashMap<String, BasePermission>();
7832
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007833 // Packages that have been uninstalled and still need their external
7834 // storage data deleted.
7835 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7836
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007837 // Packages that have been renamed since they were first installed.
7838 // Keys are the new names of the packages, values are the original
7839 // names. The packages appear everwhere else under their original
7840 // names.
7841 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 private final StringBuilder mReadMessages = new StringBuilder();
7844
7845 private static final class PendingPackage extends PackageSettingBase {
7846 final int sharedId;
7847
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007848 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007849 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007850 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 this.sharedId = sharedId;
7852 }
7853 }
7854 private final ArrayList<PendingPackage> mPendingPackages
7855 = new ArrayList<PendingPackage>();
7856
7857 Settings() {
7858 File dataDir = Environment.getDataDirectory();
7859 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007860 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7861 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007863 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 FileUtils.setPermissions(systemDir.toString(),
7865 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7866 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7867 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007868 FileUtils.setPermissions(systemSecureDir.toString(),
7869 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7870 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7871 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 mSettingsFilename = new File(systemDir, "packages.xml");
7873 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007874 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007875 }
7876
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007877 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007878 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879 int pkgFlags, boolean create, boolean add) {
7880 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007881 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007882 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 return p;
7884 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007885
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007886 PackageSetting peekPackageLP(String name) {
7887 return mPackages.get(name);
7888 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 PackageSetting p = mPackages.get(name);
7890 if (p != null && p.codePath.getPath().equals(codePath)) {
7891 return p;
7892 }
7893 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007894 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007895 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007897 void setInstallStatus(String pkgName, int status) {
7898 PackageSetting p = mPackages.get(pkgName);
7899 if(p != null) {
7900 if(p.getInstallStatus() != status) {
7901 p.setInstallStatus(status);
7902 }
7903 }
7904 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007905
Jacek Surazski65e13172009-04-28 15:26:38 +02007906 void setInstallerPackageName(String pkgName,
7907 String installerPkgName) {
7908 PackageSetting p = mPackages.get(pkgName);
7909 if(p != null) {
7910 p.setInstallerPackageName(installerPkgName);
7911 }
7912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007913
Jacek Surazski65e13172009-04-28 15:26:38 +02007914 String getInstallerPackageName(String pkgName) {
7915 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007916 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007917 }
7918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919 int getInstallStatus(String pkgName) {
7920 PackageSetting p = mPackages.get(pkgName);
7921 if(p != null) {
7922 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 return -1;
7925 }
7926
7927 SharedUserSetting getSharedUserLP(String name,
7928 int pkgFlags, boolean create) {
7929 SharedUserSetting s = mSharedUsers.get(name);
7930 if (s == null) {
7931 if (!create) {
7932 return null;
7933 }
7934 s = new SharedUserSetting(name, pkgFlags);
7935 if (MULTIPLE_APPLICATION_UIDS) {
7936 s.userId = newUserIdLP(s);
7937 } else {
7938 s.userId = FIRST_APPLICATION_UID;
7939 }
7940 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7941 // < 0 means we couldn't assign a userid; fall out and return
7942 // s, which is currently null
7943 if (s.userId >= 0) {
7944 mSharedUsers.put(name, s);
7945 }
7946 }
7947
7948 return s;
7949 }
7950
7951 int disableSystemPackageLP(String name) {
7952 PackageSetting p = mPackages.get(name);
7953 if(p == null) {
7954 Log.w(TAG, "Package:"+name+" is not an installed package");
7955 return -1;
7956 }
7957 PackageSetting dp = mDisabledSysPackages.get(name);
7958 // always make sure the system package code and resource paths dont change
7959 if(dp == null) {
7960 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7961 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7962 }
7963 mDisabledSysPackages.put(name, p);
7964 }
7965 return removePackageLP(name);
7966 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 PackageSetting enableSystemPackageLP(String name) {
7969 PackageSetting p = mDisabledSysPackages.get(name);
7970 if(p == null) {
7971 Log.w(TAG, "Package:"+name+" is not disabled");
7972 return null;
7973 }
7974 // Reset flag in ApplicationInfo object
7975 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7976 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7977 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007978 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007979 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 mDisabledSysPackages.remove(name);
7981 return ret;
7982 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007983
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007984 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007985 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986 PackageSetting p = mPackages.get(name);
7987 if (p != null) {
7988 if (p.userId == uid) {
7989 return p;
7990 }
7991 reportSettingsProblem(Log.ERROR,
7992 "Adding duplicate package, keeping first: " + name);
7993 return null;
7994 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007995 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 p.userId = uid;
7997 if (addUserIdLP(uid, p, name)) {
7998 mPackages.put(name, p);
7999 return p;
8000 }
8001 return null;
8002 }
8003
8004 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8005 SharedUserSetting s = mSharedUsers.get(name);
8006 if (s != null) {
8007 if (s.userId == uid) {
8008 return s;
8009 }
8010 reportSettingsProblem(Log.ERROR,
8011 "Adding duplicate shared user, keeping first: " + name);
8012 return null;
8013 }
8014 s = new SharedUserSetting(name, pkgFlags);
8015 s.userId = uid;
8016 if (addUserIdLP(uid, s, name)) {
8017 mSharedUsers.put(name, s);
8018 return s;
8019 }
8020 return null;
8021 }
8022
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008023 // Transfer ownership of permissions from one package to another.
8024 private void transferPermissions(String origPkg, String newPkg) {
8025 // Transfer ownership of permissions to the new package.
8026 for (int i=0; i<2; i++) {
8027 HashMap<String, BasePermission> permissions =
8028 i == 0 ? mPermissionTrees : mPermissions;
8029 for (BasePermission bp : permissions.values()) {
8030 if (origPkg.equals(bp.sourcePackage)) {
8031 if (DEBUG_UPGRADE) Log.v(TAG,
8032 "Moving permission " + bp.name
8033 + " from pkg " + bp.sourcePackage
8034 + " to " + newPkg);
8035 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008036 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008037 bp.perm = null;
8038 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008039 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008040 }
8041 bp.uid = 0;
8042 bp.gids = null;
8043 }
8044 }
8045 }
8046 }
8047
8048 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008049 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008050 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008051 PackageSetting p = mPackages.get(name);
8052 if (p != null) {
8053 if (!p.codePath.equals(codePath)) {
8054 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008055 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008056 // This is an updated system app with versions in both system
8057 // and data partition. Just let the most recent version
8058 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008059 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008060 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008061 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008062 // Just a change in the code path is not an issue, but
8063 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008064 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008065 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008066 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008067 }
8068 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008069 reportSettingsProblem(Log.WARN,
8070 "Package " + name + " shared user changed from "
8071 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8072 + " to "
8073 + (sharedUser != null ? sharedUser.name : "<nothing>")
8074 + "; replacing with new");
8075 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008076 } else {
8077 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8078 // If what we are scanning is a system package, then
8079 // make it so, regardless of whether it was previously
8080 // installed only in the data partition.
8081 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008083 }
8084 }
8085 if (p == null) {
8086 // Create a new PackageSettings entry. this can end up here because
8087 // of code path mismatch or user id mismatch of an updated system partition
8088 if (!create) {
8089 return null;
8090 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008091 if (origPackage != null) {
8092 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008093 p = new PackageSetting(origPackage.name, name, codePath,
8094 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008095 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8096 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008097 // Note that we will retain the new package's signature so
8098 // that we can keep its data.
8099 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008100 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008101 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008102 p.sharedUser = origPackage.sharedUser;
8103 p.userId = origPackage.userId;
8104 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008105 mRenamedPackages.put(name, origPackage.name);
8106 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008107 // Update new package state.
8108 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008109 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008110 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008111 p.setTimeStamp(codePath.lastModified());
8112 p.sharedUser = sharedUser;
8113 if (sharedUser != null) {
8114 p.userId = sharedUser.userId;
8115 } else if (MULTIPLE_APPLICATION_UIDS) {
8116 // Clone the setting here for disabled system packages
8117 PackageSetting dis = mDisabledSysPackages.get(name);
8118 if (dis != null) {
8119 // For disabled packages a new setting is created
8120 // from the existing user id. This still has to be
8121 // added to list of user id's
8122 // Copy signatures from previous setting
8123 if (dis.signatures.mSignatures != null) {
8124 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8125 }
8126 p.userId = dis.userId;
8127 // Clone permissions
8128 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008129 // Clone component info
8130 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8131 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8132 // Add new setting to list of user ids
8133 addUserIdLP(p.userId, p, name);
8134 } else {
8135 // Assign new user id
8136 p.userId = newUserIdLP(p);
8137 }
8138 } else {
8139 p.userId = FIRST_APPLICATION_UID;
8140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 }
8142 if (p.userId < 0) {
8143 reportSettingsProblem(Log.WARN,
8144 "Package " + name + " could not be assigned a valid uid");
8145 return null;
8146 }
8147 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008148 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008150 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 }
8152 }
8153 return p;
8154 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008155
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008156 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008157 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008158 String codePath = pkg.applicationInfo.sourceDir;
8159 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008160 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008161 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008162 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008163 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008164 p.codePath = new File(codePath);
8165 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008166 }
8167 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008168 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008169 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008170 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008171 p.resourcePath = new File(resourcePath);
8172 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008173 }
8174 // Update version code if needed
8175 if (pkg.mVersionCode != p.versionCode) {
8176 p.versionCode = pkg.mVersionCode;
8177 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008178 // Update signatures if needed.
8179 if (p.signatures.mSignatures == null) {
8180 p.signatures.assignSignatures(pkg.mSignatures);
8181 }
8182 // If this app defines a shared user id initialize
8183 // the shared user signatures as well.
8184 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8185 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8186 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008187 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8188 }
8189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008190 // Utility method that adds a PackageSetting to mPackages and
8191 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008192 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 SharedUserSetting sharedUser) {
8194 mPackages.put(name, p);
8195 if (sharedUser != null) {
8196 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8197 reportSettingsProblem(Log.ERROR,
8198 "Package " + p.name + " was user "
8199 + p.sharedUser + " but is now " + sharedUser
8200 + "; I am not changing its files so it will probably fail!");
8201 p.sharedUser.packages.remove(p);
8202 } else if (p.userId != sharedUser.userId) {
8203 reportSettingsProblem(Log.ERROR,
8204 "Package " + p.name + " was user id " + p.userId
8205 + " but is now user " + sharedUser
8206 + " with id " + sharedUser.userId
8207 + "; I am not changing its files so it will probably fail!");
8208 }
8209
8210 sharedUser.packages.add(p);
8211 p.sharedUser = sharedUser;
8212 p.userId = sharedUser.userId;
8213 }
8214 }
8215
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008216 /*
8217 * Update the shared user setting when a package using
8218 * specifying the shared user id is removed. The gids
8219 * associated with each permission of the deleted package
8220 * are removed from the shared user's gid list only if its
8221 * not in use by other permissions of packages in the
8222 * shared user setting.
8223 */
8224 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008226 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008227 return;
8228 }
8229 // No sharedUserId
8230 if (deletedPs.sharedUser == null) {
8231 return;
8232 }
8233 SharedUserSetting sus = deletedPs.sharedUser;
8234 // Update permissions
8235 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8236 boolean used = false;
8237 if (!sus.grantedPermissions.contains (eachPerm)) {
8238 continue;
8239 }
8240 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008241 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008242 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008243 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008244 used = true;
8245 break;
8246 }
8247 }
8248 if (!used) {
8249 // can safely delete this permission from list
8250 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008251 }
8252 }
8253 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008254 int newGids[] = globalGids;
8255 for (String eachPerm : sus.grantedPermissions) {
8256 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008257 if (bp != null) {
8258 newGids = appendInts(newGids, bp.gids);
8259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008260 }
8261 sus.gids = newGids;
8262 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008264 private int removePackageLP(String name) {
8265 PackageSetting p = mPackages.get(name);
8266 if (p != null) {
8267 mPackages.remove(name);
8268 if (p.sharedUser != null) {
8269 p.sharedUser.packages.remove(p);
8270 if (p.sharedUser.packages.size() == 0) {
8271 mSharedUsers.remove(p.sharedUser.name);
8272 removeUserIdLP(p.sharedUser.userId);
8273 return p.sharedUser.userId;
8274 }
8275 } else {
8276 removeUserIdLP(p.userId);
8277 return p.userId;
8278 }
8279 }
8280 return -1;
8281 }
8282
8283 private boolean addUserIdLP(int uid, Object obj, Object name) {
8284 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8285 return false;
8286 }
8287
8288 if (uid >= FIRST_APPLICATION_UID) {
8289 int N = mUserIds.size();
8290 final int index = uid - FIRST_APPLICATION_UID;
8291 while (index >= N) {
8292 mUserIds.add(null);
8293 N++;
8294 }
8295 if (mUserIds.get(index) != null) {
8296 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008297 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008298 + " name=" + name);
8299 return false;
8300 }
8301 mUserIds.set(index, obj);
8302 } else {
8303 if (mOtherUserIds.get(uid) != null) {
8304 reportSettingsProblem(Log.ERROR,
8305 "Adding duplicate shared id: " + uid
8306 + " name=" + name);
8307 return false;
8308 }
8309 mOtherUserIds.put(uid, obj);
8310 }
8311 return true;
8312 }
8313
8314 public Object getUserIdLP(int uid) {
8315 if (uid >= FIRST_APPLICATION_UID) {
8316 int N = mUserIds.size();
8317 final int index = uid - FIRST_APPLICATION_UID;
8318 return index < N ? mUserIds.get(index) : null;
8319 } else {
8320 return mOtherUserIds.get(uid);
8321 }
8322 }
8323
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008324 private Set<String> findPackagesWithFlag(int flag) {
8325 Set<String> ret = new HashSet<String>();
8326 for (PackageSetting ps : mPackages.values()) {
8327 // Has to match atleast all the flag bits set on flag
8328 if ((ps.pkgFlags & flag) == flag) {
8329 ret.add(ps.name);
8330 }
8331 }
8332 return ret;
8333 }
8334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008335 private void removeUserIdLP(int uid) {
8336 if (uid >= FIRST_APPLICATION_UID) {
8337 int N = mUserIds.size();
8338 final int index = uid - FIRST_APPLICATION_UID;
8339 if (index < N) mUserIds.set(index, null);
8340 } else {
8341 mOtherUserIds.remove(uid);
8342 }
8343 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008345 void writeLP() {
8346 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8347
8348 // Keep the old settings around until we know the new ones have
8349 // been successfully written.
8350 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008351 // Presence of backup settings file indicates that we failed
8352 // to persist settings earlier. So preserve the older
8353 // backup for future reference since the current settings
8354 // might have been corrupted.
8355 if (!mBackupSettingsFilename.exists()) {
8356 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008357 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008358 return;
8359 }
8360 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008361 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008362 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008364 }
8365
8366 mPastSignatures.clear();
8367
8368 try {
8369 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8370
8371 //XmlSerializer serializer = XmlUtils.serializerInstance();
8372 XmlSerializer serializer = new FastXmlSerializer();
8373 serializer.setOutput(str, "utf-8");
8374 serializer.startDocument(null, true);
8375 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8376
8377 serializer.startTag(null, "packages");
8378
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008379 serializer.startTag(null, "last-platform-version");
8380 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8381 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8382 serializer.endTag(null, "last-platform-version");
8383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008384 serializer.startTag(null, "permission-trees");
8385 for (BasePermission bp : mPermissionTrees.values()) {
8386 writePermission(serializer, bp);
8387 }
8388 serializer.endTag(null, "permission-trees");
8389
8390 serializer.startTag(null, "permissions");
8391 for (BasePermission bp : mPermissions.values()) {
8392 writePermission(serializer, bp);
8393 }
8394 serializer.endTag(null, "permissions");
8395
8396 for (PackageSetting pkg : mPackages.values()) {
8397 writePackage(serializer, pkg);
8398 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008400 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8401 writeDisabledSysPackage(serializer, pkg);
8402 }
8403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008404 serializer.startTag(null, "preferred-activities");
8405 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8406 serializer.startTag(null, "item");
8407 pa.writeToXml(serializer);
8408 serializer.endTag(null, "item");
8409 }
8410 serializer.endTag(null, "preferred-activities");
8411
8412 for (SharedUserSetting usr : mSharedUsers.values()) {
8413 serializer.startTag(null, "shared-user");
8414 serializer.attribute(null, "name", usr.name);
8415 serializer.attribute(null, "userId",
8416 Integer.toString(usr.userId));
8417 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8418 serializer.startTag(null, "perms");
8419 for (String name : usr.grantedPermissions) {
8420 serializer.startTag(null, "item");
8421 serializer.attribute(null, "name", name);
8422 serializer.endTag(null, "item");
8423 }
8424 serializer.endTag(null, "perms");
8425 serializer.endTag(null, "shared-user");
8426 }
8427
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008428 if (mPackagesToBeCleaned.size() > 0) {
8429 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8430 serializer.startTag(null, "cleaning-package");
8431 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8432 serializer.endTag(null, "cleaning-package");
8433 }
8434 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008435
8436 if (mRenamedPackages.size() > 0) {
8437 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8438 serializer.startTag(null, "renamed-package");
8439 serializer.attribute(null, "new", e.getKey());
8440 serializer.attribute(null, "old", e.getValue());
8441 serializer.endTag(null, "renamed-package");
8442 }
8443 }
8444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008445 serializer.endTag(null, "packages");
8446
8447 serializer.endDocument();
8448
8449 str.flush();
8450 str.close();
8451
8452 // New settings successfully written, old ones are no longer
8453 // needed.
8454 mBackupSettingsFilename.delete();
8455 FileUtils.setPermissions(mSettingsFilename.toString(),
8456 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8457 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8458 |FileUtils.S_IROTH,
8459 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008460
8461 // Write package list file now, use a JournaledFile.
8462 //
8463 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8464 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8465
8466 str = new FileOutputStream(journal.chooseForWrite());
8467 try {
8468 StringBuilder sb = new StringBuilder();
8469 for (PackageSetting pkg : mPackages.values()) {
8470 ApplicationInfo ai = pkg.pkg.applicationInfo;
8471 String dataPath = ai.dataDir;
8472 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8473
8474 // Avoid any application that has a space in its path
8475 // or that is handled by the system.
8476 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8477 continue;
8478
8479 // we store on each line the following information for now:
8480 //
8481 // pkgName - package name
8482 // userId - application-specific user id
8483 // debugFlag - 0 or 1 if the package is debuggable.
8484 // dataPath - path to package's data path
8485 //
8486 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8487 //
8488 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8489 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8490 // system/core/run-as/run-as.c
8491 //
8492 sb.setLength(0);
8493 sb.append(ai.packageName);
8494 sb.append(" ");
8495 sb.append((int)ai.uid);
8496 sb.append(isDebug ? " 1 " : " 0 ");
8497 sb.append(dataPath);
8498 sb.append("\n");
8499 str.write(sb.toString().getBytes());
8500 }
8501 str.flush();
8502 str.close();
8503 journal.commit();
8504 }
8505 catch (Exception e) {
8506 journal.rollback();
8507 }
8508
8509 FileUtils.setPermissions(mPackageListFilename.toString(),
8510 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8511 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8512 |FileUtils.S_IROTH,
8513 -1, -1);
8514
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008515 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516
8517 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008518 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 -08008519 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008520 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 -08008521 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008522 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008523 if (mSettingsFilename.exists()) {
8524 if (!mSettingsFilename.delete()) {
8525 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8526 }
8527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008528 //Debug.stopMethodTracing();
8529 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008530
8531 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008532 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 serializer.startTag(null, "updated-package");
8534 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008535 if (pkg.realName != null) {
8536 serializer.attribute(null, "realName", pkg.realName);
8537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008538 serializer.attribute(null, "codePath", pkg.codePathString);
8539 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008540 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008541 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8542 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8543 }
8544 if (pkg.sharedUser == null) {
8545 serializer.attribute(null, "userId",
8546 Integer.toString(pkg.userId));
8547 } else {
8548 serializer.attribute(null, "sharedUserId",
8549 Integer.toString(pkg.userId));
8550 }
8551 serializer.startTag(null, "perms");
8552 if (pkg.sharedUser == null) {
8553 // If this is a shared user, the permissions will
8554 // be written there. We still need to write an
8555 // empty permissions list so permissionsFixed will
8556 // be set.
8557 for (final String name : pkg.grantedPermissions) {
8558 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008559 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008560 // We only need to write signature or system permissions but this wont
8561 // match the semantics of grantedPermissions. So write all permissions.
8562 serializer.startTag(null, "item");
8563 serializer.attribute(null, "name", name);
8564 serializer.endTag(null, "item");
8565 }
8566 }
8567 }
8568 serializer.endTag(null, "perms");
8569 serializer.endTag(null, "updated-package");
8570 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008571
8572 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008573 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 serializer.startTag(null, "package");
8575 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008576 if (pkg.realName != null) {
8577 serializer.attribute(null, "realName", pkg.realName);
8578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 serializer.attribute(null, "codePath", pkg.codePathString);
8580 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8581 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8582 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008583 serializer.attribute(null, "flags",
8584 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008585 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008586 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 if (pkg.sharedUser == null) {
8588 serializer.attribute(null, "userId",
8589 Integer.toString(pkg.userId));
8590 } else {
8591 serializer.attribute(null, "sharedUserId",
8592 Integer.toString(pkg.userId));
8593 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008594 if (pkg.uidError) {
8595 serializer.attribute(null, "uidError", "true");
8596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008597 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8598 serializer.attribute(null, "enabled",
8599 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8600 ? "true" : "false");
8601 }
8602 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8603 serializer.attribute(null, "installStatus", "false");
8604 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008605 if (pkg.installerPackageName != null) {
8606 serializer.attribute(null, "installer", pkg.installerPackageName);
8607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008608 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8609 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8610 serializer.startTag(null, "perms");
8611 if (pkg.sharedUser == null) {
8612 // If this is a shared user, the permissions will
8613 // be written there. We still need to write an
8614 // empty permissions list so permissionsFixed will
8615 // be set.
8616 for (final String name : pkg.grantedPermissions) {
8617 serializer.startTag(null, "item");
8618 serializer.attribute(null, "name", name);
8619 serializer.endTag(null, "item");
8620 }
8621 }
8622 serializer.endTag(null, "perms");
8623 }
8624 if (pkg.disabledComponents.size() > 0) {
8625 serializer.startTag(null, "disabled-components");
8626 for (final String name : pkg.disabledComponents) {
8627 serializer.startTag(null, "item");
8628 serializer.attribute(null, "name", name);
8629 serializer.endTag(null, "item");
8630 }
8631 serializer.endTag(null, "disabled-components");
8632 }
8633 if (pkg.enabledComponents.size() > 0) {
8634 serializer.startTag(null, "enabled-components");
8635 for (final String name : pkg.enabledComponents) {
8636 serializer.startTag(null, "item");
8637 serializer.attribute(null, "name", name);
8638 serializer.endTag(null, "item");
8639 }
8640 serializer.endTag(null, "enabled-components");
8641 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008643 serializer.endTag(null, "package");
8644 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 void writePermission(XmlSerializer serializer, BasePermission bp)
8647 throws XmlPullParserException, java.io.IOException {
8648 if (bp.type != BasePermission.TYPE_BUILTIN
8649 && bp.sourcePackage != null) {
8650 serializer.startTag(null, "item");
8651 serializer.attribute(null, "name", bp.name);
8652 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008653 if (bp.protectionLevel !=
8654 PermissionInfo.PROTECTION_NORMAL) {
8655 serializer.attribute(null, "protection",
8656 Integer.toString(bp.protectionLevel));
8657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008658 if (DEBUG_SETTINGS) Log.v(TAG,
8659 "Writing perm: name=" + bp.name + " type=" + bp.type);
8660 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8661 PermissionInfo pi = bp.perm != null ? bp.perm.info
8662 : bp.pendingInfo;
8663 if (pi != null) {
8664 serializer.attribute(null, "type", "dynamic");
8665 if (pi.icon != 0) {
8666 serializer.attribute(null, "icon",
8667 Integer.toString(pi.icon));
8668 }
8669 if (pi.nonLocalizedLabel != null) {
8670 serializer.attribute(null, "label",
8671 pi.nonLocalizedLabel.toString());
8672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008673 }
8674 }
8675 serializer.endTag(null, "item");
8676 }
8677 }
8678
8679 String getReadMessagesLP() {
8680 return mReadMessages.toString();
8681 }
8682
Oscar Montemayora8529f62009-11-18 10:14:20 -08008683 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8685 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008686 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008687 while(its.hasNext()) {
8688 String key = its.next();
8689 PackageSetting ps = mPackages.get(key);
8690 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008691 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008692 }
8693 }
8694 return ret;
8695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008697 boolean readLP() {
8698 FileInputStream str = null;
8699 if (mBackupSettingsFilename.exists()) {
8700 try {
8701 str = new FileInputStream(mBackupSettingsFilename);
8702 mReadMessages.append("Reading from backup settings file\n");
8703 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008704 if (mSettingsFilename.exists()) {
8705 // If both the backup and settings file exist, we
8706 // ignore the settings since it might have been
8707 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008708 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008709 mSettingsFilename.delete();
8710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008711 } catch (java.io.IOException e) {
8712 // We'll try for the normal settings file.
8713 }
8714 }
8715
8716 mPastSignatures.clear();
8717
8718 try {
8719 if (str == null) {
8720 if (!mSettingsFilename.exists()) {
8721 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008722 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723 return false;
8724 }
8725 str = new FileInputStream(mSettingsFilename);
8726 }
8727 XmlPullParser parser = Xml.newPullParser();
8728 parser.setInput(str, null);
8729
8730 int type;
8731 while ((type=parser.next()) != XmlPullParser.START_TAG
8732 && type != XmlPullParser.END_DOCUMENT) {
8733 ;
8734 }
8735
8736 if (type != XmlPullParser.START_TAG) {
8737 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008738 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008739 return false;
8740 }
8741
8742 int outerDepth = parser.getDepth();
8743 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8744 && (type != XmlPullParser.END_TAG
8745 || parser.getDepth() > outerDepth)) {
8746 if (type == XmlPullParser.END_TAG
8747 || type == XmlPullParser.TEXT) {
8748 continue;
8749 }
8750
8751 String tagName = parser.getName();
8752 if (tagName.equals("package")) {
8753 readPackageLP(parser);
8754 } else if (tagName.equals("permissions")) {
8755 readPermissionsLP(mPermissions, parser);
8756 } else if (tagName.equals("permission-trees")) {
8757 readPermissionsLP(mPermissionTrees, parser);
8758 } else if (tagName.equals("shared-user")) {
8759 readSharedUserLP(parser);
8760 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008761 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008762 } else if (tagName.equals("preferred-activities")) {
8763 readPreferredActivitiesLP(parser);
8764 } else if(tagName.equals("updated-package")) {
8765 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008766 } else if (tagName.equals("cleaning-package")) {
8767 String name = parser.getAttributeValue(null, "name");
8768 if (name != null) {
8769 mPackagesToBeCleaned.add(name);
8770 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008771 } else if (tagName.equals("renamed-package")) {
8772 String nname = parser.getAttributeValue(null, "new");
8773 String oname = parser.getAttributeValue(null, "old");
8774 if (nname != null && oname != null) {
8775 mRenamedPackages.put(nname, oname);
8776 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008777 } else if (tagName.equals("last-platform-version")) {
8778 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8779 try {
8780 String internal = parser.getAttributeValue(null, "internal");
8781 if (internal != null) {
8782 mInternalSdkPlatform = Integer.parseInt(internal);
8783 }
8784 String external = parser.getAttributeValue(null, "external");
8785 if (external != null) {
8786 mInternalSdkPlatform = Integer.parseInt(external);
8787 }
8788 } catch (NumberFormatException e) {
8789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008790 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008791 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008792 + parser.getName());
8793 XmlUtils.skipCurrentTag(parser);
8794 }
8795 }
8796
8797 str.close();
8798
8799 } catch(XmlPullParserException e) {
8800 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008801 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008802
8803 } catch(java.io.IOException e) {
8804 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008805 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008806
8807 }
8808
8809 int N = mPendingPackages.size();
8810 for (int i=0; i<N; i++) {
8811 final PendingPackage pp = mPendingPackages.get(i);
8812 Object idObj = getUserIdLP(pp.sharedId);
8813 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008814 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008815 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008816 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008817 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008818 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008819 + pp.name);
8820 continue;
8821 }
8822 p.copyFrom(pp);
8823 } else if (idObj != null) {
8824 String msg = "Bad package setting: package " + pp.name
8825 + " has shared uid " + pp.sharedId
8826 + " that is not a shared uid\n";
8827 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008828 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008829 } else {
8830 String msg = "Bad package setting: package " + pp.name
8831 + " has shared uid " + pp.sharedId
8832 + " that is not defined\n";
8833 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008834 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008835 }
8836 }
8837 mPendingPackages.clear();
8838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008839 mReadMessages.append("Read completed successfully: "
8840 + mPackages.size() + " packages, "
8841 + mSharedUsers.size() + " shared uids\n");
8842
8843 return true;
8844 }
8845
8846 private int readInt(XmlPullParser parser, String ns, String name,
8847 int defValue) {
8848 String v = parser.getAttributeValue(ns, name);
8849 try {
8850 if (v == null) {
8851 return defValue;
8852 }
8853 return Integer.parseInt(v);
8854 } catch (NumberFormatException e) {
8855 reportSettingsProblem(Log.WARN,
8856 "Error in package manager settings: attribute " +
8857 name + " has bad integer value " + v + " at "
8858 + parser.getPositionDescription());
8859 }
8860 return defValue;
8861 }
8862
8863 private void readPermissionsLP(HashMap<String, BasePermission> out,
8864 XmlPullParser parser)
8865 throws IOException, XmlPullParserException {
8866 int outerDepth = parser.getDepth();
8867 int type;
8868 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8869 && (type != XmlPullParser.END_TAG
8870 || parser.getDepth() > outerDepth)) {
8871 if (type == XmlPullParser.END_TAG
8872 || type == XmlPullParser.TEXT) {
8873 continue;
8874 }
8875
8876 String tagName = parser.getName();
8877 if (tagName.equals("item")) {
8878 String name = parser.getAttributeValue(null, "name");
8879 String sourcePackage = parser.getAttributeValue(null, "package");
8880 String ptype = parser.getAttributeValue(null, "type");
8881 if (name != null && sourcePackage != null) {
8882 boolean dynamic = "dynamic".equals(ptype);
8883 BasePermission bp = new BasePermission(name, sourcePackage,
8884 dynamic
8885 ? BasePermission.TYPE_DYNAMIC
8886 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008887 bp.protectionLevel = readInt(parser, null, "protection",
8888 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008889 if (dynamic) {
8890 PermissionInfo pi = new PermissionInfo();
8891 pi.packageName = sourcePackage.intern();
8892 pi.name = name.intern();
8893 pi.icon = readInt(parser, null, "icon", 0);
8894 pi.nonLocalizedLabel = parser.getAttributeValue(
8895 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008896 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008897 bp.pendingInfo = pi;
8898 }
8899 out.put(bp.name, bp);
8900 } else {
8901 reportSettingsProblem(Log.WARN,
8902 "Error in package manager settings: permissions has"
8903 + " no name at " + parser.getPositionDescription());
8904 }
8905 } else {
8906 reportSettingsProblem(Log.WARN,
8907 "Unknown element reading permissions: "
8908 + parser.getName() + " at "
8909 + parser.getPositionDescription());
8910 }
8911 XmlUtils.skipCurrentTag(parser);
8912 }
8913 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008916 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008917 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008918 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008919 String codePathStr = parser.getAttributeValue(null, "codePath");
8920 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008921 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008922 resourcePathStr = codePathStr;
8923 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008924 String version = parser.getAttributeValue(null, "version");
8925 int versionCode = 0;
8926 if (version != null) {
8927 try {
8928 versionCode = Integer.parseInt(version);
8929 } catch (NumberFormatException e) {
8930 }
8931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008933 int pkgFlags = 0;
8934 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008935 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008936 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008937 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008938 String timeStampStr = parser.getAttributeValue(null, "ts");
8939 if (timeStampStr != null) {
8940 try {
8941 long timeStamp = Long.parseLong(timeStampStr);
8942 ps.setTimeStamp(timeStamp, timeStampStr);
8943 } catch (NumberFormatException e) {
8944 }
8945 }
8946 String idStr = parser.getAttributeValue(null, "userId");
8947 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8948 if(ps.userId <= 0) {
8949 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8950 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8951 }
8952 int outerDepth = parser.getDepth();
8953 int type;
8954 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8955 && (type != XmlPullParser.END_TAG
8956 || parser.getDepth() > outerDepth)) {
8957 if (type == XmlPullParser.END_TAG
8958 || type == XmlPullParser.TEXT) {
8959 continue;
8960 }
8961
8962 String tagName = parser.getName();
8963 if (tagName.equals("perms")) {
8964 readGrantedPermissionsLP(parser,
8965 ps.grantedPermissions);
8966 } else {
8967 reportSettingsProblem(Log.WARN,
8968 "Unknown element under <updated-package>: "
8969 + parser.getName());
8970 XmlUtils.skipCurrentTag(parser);
8971 }
8972 }
8973 mDisabledSysPackages.put(name, ps);
8974 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008976 private void readPackageLP(XmlPullParser parser)
8977 throws XmlPullParserException, IOException {
8978 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008979 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008980 String idStr = null;
8981 String sharedIdStr = null;
8982 String codePathStr = null;
8983 String resourcePathStr = null;
8984 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008985 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008986 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008987 int pkgFlags = 0;
8988 String timeStampStr;
8989 long timeStamp = 0;
8990 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008991 String version = null;
8992 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008993 try {
8994 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008995 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008996 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008997 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008998 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8999 codePathStr = parser.getAttributeValue(null, "codePath");
9000 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009001 version = parser.getAttributeValue(null, "version");
9002 if (version != null) {
9003 try {
9004 versionCode = Integer.parseInt(version);
9005 } catch (NumberFormatException e) {
9006 }
9007 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009008 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009009
9010 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009011 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009012 try {
9013 pkgFlags = Integer.parseInt(systemStr);
9014 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009015 }
9016 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009017 // For backward compatibility
9018 systemStr = parser.getAttributeValue(null, "system");
9019 if (systemStr != null) {
9020 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9021 } else {
9022 // Old settings that don't specify system... just treat
9023 // them as system, good enough.
9024 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009026 }
9027 timeStampStr = parser.getAttributeValue(null, "ts");
9028 if (timeStampStr != null) {
9029 try {
9030 timeStamp = Long.parseLong(timeStampStr);
9031 } catch (NumberFormatException e) {
9032 }
9033 }
9034 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9035 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9036 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9037 if (resourcePathStr == null) {
9038 resourcePathStr = codePathStr;
9039 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009040 if (realName != null) {
9041 realName = realName.intern();
9042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009043 if (name == null) {
9044 reportSettingsProblem(Log.WARN,
9045 "Error in package manager settings: <package> has no name at "
9046 + parser.getPositionDescription());
9047 } else if (codePathStr == null) {
9048 reportSettingsProblem(Log.WARN,
9049 "Error in package manager settings: <package> has no codePath at "
9050 + parser.getPositionDescription());
9051 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009052 packageSetting = addPackageLP(name.intern(), realName,
9053 new File(codePathStr), new File(resourcePathStr),
9054 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009055 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9056 + ": userId=" + userId + " pkg=" + packageSetting);
9057 if (packageSetting == null) {
9058 reportSettingsProblem(Log.ERROR,
9059 "Failure adding uid " + userId
9060 + " while parsing settings at "
9061 + parser.getPositionDescription());
9062 } else {
9063 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9064 }
9065 } else if (sharedIdStr != null) {
9066 userId = sharedIdStr != null
9067 ? Integer.parseInt(sharedIdStr) : 0;
9068 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009069 packageSetting = new PendingPackage(name.intern(), realName,
9070 new File(codePathStr), new File(resourcePathStr),
9071 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009072 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9073 mPendingPackages.add((PendingPackage) packageSetting);
9074 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9075 + ": sharedUserId=" + userId + " pkg="
9076 + packageSetting);
9077 } else {
9078 reportSettingsProblem(Log.WARN,
9079 "Error in package manager settings: package "
9080 + name + " has bad sharedId " + sharedIdStr
9081 + " at " + parser.getPositionDescription());
9082 }
9083 } else {
9084 reportSettingsProblem(Log.WARN,
9085 "Error in package manager settings: package "
9086 + name + " has bad userId " + idStr + " at "
9087 + parser.getPositionDescription());
9088 }
9089 } catch (NumberFormatException e) {
9090 reportSettingsProblem(Log.WARN,
9091 "Error in package manager settings: package "
9092 + name + " has bad userId " + idStr + " at "
9093 + parser.getPositionDescription());
9094 }
9095 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009096 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009097 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009098 final String enabledStr = parser.getAttributeValue(null, "enabled");
9099 if (enabledStr != null) {
9100 if (enabledStr.equalsIgnoreCase("true")) {
9101 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9102 } else if (enabledStr.equalsIgnoreCase("false")) {
9103 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9104 } else if (enabledStr.equalsIgnoreCase("default")) {
9105 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9106 } else {
9107 reportSettingsProblem(Log.WARN,
9108 "Error in package manager settings: package "
9109 + name + " has bad enabled value: " + idStr
9110 + " at " + parser.getPositionDescription());
9111 }
9112 } else {
9113 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9114 }
9115 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9116 if (installStatusStr != null) {
9117 if (installStatusStr.equalsIgnoreCase("false")) {
9118 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9119 } else {
9120 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9121 }
9122 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009124 int outerDepth = parser.getDepth();
9125 int type;
9126 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9127 && (type != XmlPullParser.END_TAG
9128 || parser.getDepth() > outerDepth)) {
9129 if (type == XmlPullParser.END_TAG
9130 || type == XmlPullParser.TEXT) {
9131 continue;
9132 }
9133
9134 String tagName = parser.getName();
9135 if (tagName.equals("disabled-components")) {
9136 readDisabledComponentsLP(packageSetting, parser);
9137 } else if (tagName.equals("enabled-components")) {
9138 readEnabledComponentsLP(packageSetting, parser);
9139 } else if (tagName.equals("sigs")) {
9140 packageSetting.signatures.readXml(parser, mPastSignatures);
9141 } else if (tagName.equals("perms")) {
9142 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009143 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009144 packageSetting.permissionsFixed = true;
9145 } else {
9146 reportSettingsProblem(Log.WARN,
9147 "Unknown element under <package>: "
9148 + parser.getName());
9149 XmlUtils.skipCurrentTag(parser);
9150 }
9151 }
9152 } else {
9153 XmlUtils.skipCurrentTag(parser);
9154 }
9155 }
9156
9157 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9158 XmlPullParser parser)
9159 throws IOException, XmlPullParserException {
9160 int outerDepth = parser.getDepth();
9161 int type;
9162 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9163 && (type != XmlPullParser.END_TAG
9164 || parser.getDepth() > outerDepth)) {
9165 if (type == XmlPullParser.END_TAG
9166 || type == XmlPullParser.TEXT) {
9167 continue;
9168 }
9169
9170 String tagName = parser.getName();
9171 if (tagName.equals("item")) {
9172 String name = parser.getAttributeValue(null, "name");
9173 if (name != null) {
9174 packageSetting.disabledComponents.add(name.intern());
9175 } else {
9176 reportSettingsProblem(Log.WARN,
9177 "Error in package manager settings: <disabled-components> has"
9178 + " no name at " + parser.getPositionDescription());
9179 }
9180 } else {
9181 reportSettingsProblem(Log.WARN,
9182 "Unknown element under <disabled-components>: "
9183 + parser.getName());
9184 }
9185 XmlUtils.skipCurrentTag(parser);
9186 }
9187 }
9188
9189 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9190 XmlPullParser parser)
9191 throws IOException, XmlPullParserException {
9192 int outerDepth = parser.getDepth();
9193 int type;
9194 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9195 && (type != XmlPullParser.END_TAG
9196 || parser.getDepth() > outerDepth)) {
9197 if (type == XmlPullParser.END_TAG
9198 || type == XmlPullParser.TEXT) {
9199 continue;
9200 }
9201
9202 String tagName = parser.getName();
9203 if (tagName.equals("item")) {
9204 String name = parser.getAttributeValue(null, "name");
9205 if (name != null) {
9206 packageSetting.enabledComponents.add(name.intern());
9207 } else {
9208 reportSettingsProblem(Log.WARN,
9209 "Error in package manager settings: <enabled-components> has"
9210 + " no name at " + parser.getPositionDescription());
9211 }
9212 } else {
9213 reportSettingsProblem(Log.WARN,
9214 "Unknown element under <enabled-components>: "
9215 + parser.getName());
9216 }
9217 XmlUtils.skipCurrentTag(parser);
9218 }
9219 }
9220
9221 private void readSharedUserLP(XmlPullParser parser)
9222 throws XmlPullParserException, IOException {
9223 String name = null;
9224 String idStr = null;
9225 int pkgFlags = 0;
9226 SharedUserSetting su = null;
9227 try {
9228 name = parser.getAttributeValue(null, "name");
9229 idStr = parser.getAttributeValue(null, "userId");
9230 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9231 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9232 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9233 }
9234 if (name == null) {
9235 reportSettingsProblem(Log.WARN,
9236 "Error in package manager settings: <shared-user> has no name at "
9237 + parser.getPositionDescription());
9238 } else if (userId == 0) {
9239 reportSettingsProblem(Log.WARN,
9240 "Error in package manager settings: shared-user "
9241 + name + " has bad userId " + idStr + " at "
9242 + parser.getPositionDescription());
9243 } else {
9244 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9245 reportSettingsProblem(Log.ERROR,
9246 "Occurred while parsing settings at "
9247 + parser.getPositionDescription());
9248 }
9249 }
9250 } catch (NumberFormatException e) {
9251 reportSettingsProblem(Log.WARN,
9252 "Error in package manager settings: package "
9253 + name + " has bad userId " + idStr + " at "
9254 + parser.getPositionDescription());
9255 };
9256
9257 if (su != null) {
9258 int outerDepth = parser.getDepth();
9259 int type;
9260 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9261 && (type != XmlPullParser.END_TAG
9262 || parser.getDepth() > outerDepth)) {
9263 if (type == XmlPullParser.END_TAG
9264 || type == XmlPullParser.TEXT) {
9265 continue;
9266 }
9267
9268 String tagName = parser.getName();
9269 if (tagName.equals("sigs")) {
9270 su.signatures.readXml(parser, mPastSignatures);
9271 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009272 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009273 } else {
9274 reportSettingsProblem(Log.WARN,
9275 "Unknown element under <shared-user>: "
9276 + parser.getName());
9277 XmlUtils.skipCurrentTag(parser);
9278 }
9279 }
9280
9281 } else {
9282 XmlUtils.skipCurrentTag(parser);
9283 }
9284 }
9285
9286 private void readGrantedPermissionsLP(XmlPullParser parser,
9287 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9288 int outerDepth = parser.getDepth();
9289 int type;
9290 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9291 && (type != XmlPullParser.END_TAG
9292 || parser.getDepth() > outerDepth)) {
9293 if (type == XmlPullParser.END_TAG
9294 || type == XmlPullParser.TEXT) {
9295 continue;
9296 }
9297
9298 String tagName = parser.getName();
9299 if (tagName.equals("item")) {
9300 String name = parser.getAttributeValue(null, "name");
9301 if (name != null) {
9302 outPerms.add(name.intern());
9303 } else {
9304 reportSettingsProblem(Log.WARN,
9305 "Error in package manager settings: <perms> has"
9306 + " no name at " + parser.getPositionDescription());
9307 }
9308 } else {
9309 reportSettingsProblem(Log.WARN,
9310 "Unknown element under <perms>: "
9311 + parser.getName());
9312 }
9313 XmlUtils.skipCurrentTag(parser);
9314 }
9315 }
9316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 private void readPreferredActivitiesLP(XmlPullParser parser)
9318 throws XmlPullParserException, IOException {
9319 int outerDepth = parser.getDepth();
9320 int type;
9321 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9322 && (type != XmlPullParser.END_TAG
9323 || parser.getDepth() > outerDepth)) {
9324 if (type == XmlPullParser.END_TAG
9325 || type == XmlPullParser.TEXT) {
9326 continue;
9327 }
9328
9329 String tagName = parser.getName();
9330 if (tagName.equals("item")) {
9331 PreferredActivity pa = new PreferredActivity(parser);
9332 if (pa.mParseError == null) {
9333 mPreferredActivities.addFilter(pa);
9334 } else {
9335 reportSettingsProblem(Log.WARN,
9336 "Error in package manager settings: <preferred-activity> "
9337 + pa.mParseError + " at "
9338 + parser.getPositionDescription());
9339 }
9340 } else {
9341 reportSettingsProblem(Log.WARN,
9342 "Unknown element under <preferred-activities>: "
9343 + parser.getName());
9344 XmlUtils.skipCurrentTag(parser);
9345 }
9346 }
9347 }
9348
9349 // Returns -1 if we could not find an available UserId to assign
9350 private int newUserIdLP(Object obj) {
9351 // Let's be stupidly inefficient for now...
9352 final int N = mUserIds.size();
9353 for (int i=0; i<N; i++) {
9354 if (mUserIds.get(i) == null) {
9355 mUserIds.set(i, obj);
9356 return FIRST_APPLICATION_UID + i;
9357 }
9358 }
9359
9360 // None left?
9361 if (N >= MAX_APPLICATION_UIDS) {
9362 return -1;
9363 }
9364
9365 mUserIds.add(obj);
9366 return FIRST_APPLICATION_UID + N;
9367 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009369 public PackageSetting getDisabledSystemPkg(String name) {
9370 synchronized(mPackages) {
9371 PackageSetting ps = mDisabledSysPackages.get(name);
9372 return ps;
9373 }
9374 }
9375
9376 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9377 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9378 if (Config.LOGV) {
9379 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9380 + " componentName = " + componentInfo.name);
9381 Log.v(TAG, "enabledComponents: "
9382 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9383 Log.v(TAG, "disabledComponents: "
9384 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9385 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009386 if (packageSettings == null) {
9387 if (false) {
9388 Log.w(TAG, "WAITING FOR DEBUGGER");
9389 Debug.waitForDebugger();
9390 Log.i(TAG, "We will crash!");
9391 }
9392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009393 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9394 || ((componentInfo.enabled
9395 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9396 || (componentInfo.applicationInfo.enabled
9397 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9398 && !packageSettings.disabledComponents.contains(componentInfo.name))
9399 || packageSettings.enabledComponents.contains(componentInfo.name));
9400 }
9401 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009402
9403 // ------- apps on sdcard specific code -------
9404 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009405 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009406 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009407 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009408 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009409
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009410 private String getEncryptKey() {
9411 try {
9412 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9413 if (sdEncKey == null) {
9414 sdEncKey = SystemKeyStore.getInstance().
9415 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9416 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009417 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009418 return null;
9419 }
9420 }
9421 return sdEncKey;
9422 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009423 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009424 return null;
9425 }
9426 }
9427
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009428 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009429 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009430 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009431 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009432 if (list != null) {
9433 int idx = 0;
9434 int idList[] = new int[MAX_CONTAINERS];
9435 boolean neverFound = true;
9436 for (String name : list) {
9437 // Ignore null entries
9438 if (name == null) {
9439 continue;
9440 }
9441 int sidx = name.indexOf(prefix);
9442 if (sidx == -1) {
9443 // Not a temp file. just ignore
9444 continue;
9445 }
9446 String subStr = name.substring(sidx + prefix.length());
9447 idList[idx] = -1;
9448 if (subStr != null) {
9449 try {
9450 int cid = Integer.parseInt(subStr);
9451 idList[idx++] = cid;
9452 neverFound = false;
9453 } catch (NumberFormatException e) {
9454 }
9455 }
9456 }
9457 if (!neverFound) {
9458 // Sort idList
9459 Arrays.sort(idList);
9460 for (int j = 1; j <= idList.length; j++) {
9461 if (idList[j-1] != j) {
9462 tmpIdx = j;
9463 break;
9464 }
9465 }
9466 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009467 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009468 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009469 }
9470
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009471 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009472 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009473 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009474 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9475 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9476 throw new SecurityException("Media status can only be updated by the system");
9477 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009478 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009479 Log.i(TAG, "Updating external media status from " +
9480 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9481 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009482 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9483 mediaStatus+", mMediaMounted=" + mMediaMounted);
9484 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009485 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9486 reportStatus ? 1 : 0, -1);
9487 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009488 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009489 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009490 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009491 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009492 // Queue up an async operation since the package installation may take a little while.
9493 mHandler.post(new Runnable() {
9494 public void run() {
9495 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009496 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009497 }
9498 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009499 }
9500
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009501 /*
9502 * Collect information of applications on external media, map them
9503 * against existing containers and update information based on current
9504 * mount status. Please note that we always have to report status
9505 * if reportStatus has been set to true especially when unloading packages.
9506 */
9507 private void updateExternalMediaStatusInner(boolean mediaStatus,
9508 boolean reportStatus) {
9509 // Collection of uids
9510 int uidArr[] = null;
9511 // Collection of stale containers
9512 HashSet<String> removeCids = new HashSet<String>();
9513 // Collection of packages on external media with valid containers.
9514 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9515 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009516 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009517 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009518 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009519 } else {
9520 // Process list of secure containers and categorize them
9521 // as active or stale based on their package internal state.
9522 int uidList[] = new int[list.length];
9523 int num = 0;
9524 synchronized (mPackages) {
9525 for (String cid : list) {
9526 SdInstallArgs args = new SdInstallArgs(cid);
9527 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009528 String pkgName = args.getPackageName();
9529 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009530 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9531 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009532 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009533 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009534 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9535 PackageSetting ps = mSettings.mPackages.get(pkgName);
9536 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009537 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009538 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9539 " corresponds to pkg : " + pkgName +
9540 " at code path: " + ps.codePathString);
9541 // We do have a valid package installed on sdcard
9542 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009543 int uid = ps.userId;
9544 if (uid != -1) {
9545 uidList[num++] = uid;
9546 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009547 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009548 // Stale container on sdcard. Just delete
9549 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9550 removeCids.add(cid);
9551 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009552 }
9553 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009554
9555 if (num > 0) {
9556 // Sort uid list
9557 Arrays.sort(uidList, 0, num);
9558 // Throw away duplicates
9559 uidArr = new int[num];
9560 uidArr[0] = uidList[0];
9561 int di = 0;
9562 for (int i = 1; i < num; i++) {
9563 if (uidList[i-1] != uidList[i]) {
9564 uidArr[di++] = uidList[i];
9565 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009566 }
9567 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009568 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009569 // Process packages with valid entries.
9570 if (mediaStatus) {
9571 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009572 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009573 startCleaningPackages();
9574 } else {
9575 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009576 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009577 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009578 }
9579
9580 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009581 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009582 int size = pkgList.size();
9583 if (size > 0) {
9584 // Send broadcasts here
9585 Bundle extras = new Bundle();
9586 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9587 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009588 if (uidArr != null) {
9589 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9590 }
9591 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9592 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009593 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009594 }
9595 }
9596
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009597 /*
9598 * Look at potentially valid container ids from processCids
9599 * If package information doesn't match the one on record
9600 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009601 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009602 */
9603 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009604 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009605 ArrayList<String> pkgList = new ArrayList<String>();
9606 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009607 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009608 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009609 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009610 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9611 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009612 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009613 try {
9614 // Make sure there are no container errors first.
9615 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9616 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009617 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009618 " when installing from sdcard");
9619 continue;
9620 }
9621 // Check code path here.
9622 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009623 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009624 " does not match one in settings " + codePath);
9625 continue;
9626 }
9627 // Parse package
9628 int parseFlags = PackageParser.PARSE_CHATTY |
Jeff Brown07330792010-03-30 19:57:08 -07009629 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009630 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009631 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009632 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9633 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009634 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009635 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009636 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009637 retCode = PackageManager.INSTALL_SUCCEEDED;
9638 pkgList.add(pkg.packageName);
9639 // Post process args
9640 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9641 }
9642 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009643 Slog.i(TAG, "Failed to install pkg from " +
9644 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009645 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009646 }
9647
9648 } finally {
9649 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9650 // Don't destroy container here. Wait till gc clears things up.
9651 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009652 }
9653 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009654 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009655 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009656 // If the platform SDK has changed since the last time we booted,
9657 // we need to re-grant app permission to catch any new ones that
9658 // appear. This is really a hack, and means that apps can in some
9659 // cases get permissions that the user didn't initially explicitly
9660 // allow... it would be nice to have some better way to handle
9661 // this situation.
9662 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9663 != mSdkVersion;
9664 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9665 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9666 + "; regranting permissions for external storage");
9667 mSettings.mExternalSdkPlatform = mSdkVersion;
9668
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009669 // Make sure group IDs have been assigned, and any permission
9670 // changes in other apps are accounted for
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009671 updatePermissionsLP(null, null, true, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009672 // Persist settings
9673 mSettings.writeLP();
9674 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009675 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009676 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009677 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009678 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009679 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009680 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009681 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009682 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009683 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009684 if (removeCids != null) {
9685 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009686 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009687 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009688 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009689 }
9690
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009691 /*
9692 * Utility method to unload a list of specified containers
9693 */
9694 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9695 // Just unmount all valid containers.
9696 for (SdInstallArgs arg : cidArgs) {
9697 synchronized (mInstallLock) {
9698 arg.doPostDeleteLI(false);
9699 }
9700 }
9701 }
9702
9703 /*
9704 * Unload packages mounted on external media. This involves deleting
9705 * package data from internal structures, sending broadcasts about
9706 * diabled packages, gc'ing to free up references, unmounting all
9707 * secure containers corresponding to packages on external media, and
9708 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9709 * Please note that we always have to post this message if status has
9710 * been requested no matter what.
9711 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009712 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009713 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009714 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009715 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009716 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009717 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009718 for (SdInstallArgs args : keys) {
9719 String cid = args.cid;
9720 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009721 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009722 // Delete package internally
9723 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9724 synchronized (mInstallLock) {
9725 boolean res = deletePackageLI(pkgName, false,
9726 PackageManager.DONT_DELETE_DATA, outInfo);
9727 if (res) {
9728 pkgList.add(pkgName);
9729 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009730 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009731 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009732 }
9733 }
9734 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009735 // We have to absolutely send UPDATED_MEDIA_STATUS only
9736 // after confirming that all the receivers processed the ordered
9737 // broadcast when packages get disabled, force a gc to clean things up.
9738 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009739 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009740 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9741 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9742 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009743 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9744 reportStatus ? 1 : 0, 1, keys);
9745 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009746 }
9747 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009748 } else {
9749 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9750 reportStatus ? 1 : 0, -1, keys);
9751 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009752 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009753 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009754
9755 public void movePackage(final String packageName,
9756 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009757 mContext.enforceCallingOrSelfPermission(
9758 android.Manifest.permission.MOVE_PACKAGE, null);
9759 int returnCode = PackageManager.MOVE_SUCCEEDED;
9760 int currFlags = 0;
9761 int newFlags = 0;
9762 synchronized (mPackages) {
9763 PackageParser.Package pkg = mPackages.get(packageName);
9764 if (pkg == null) {
9765 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009766 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009767 // Disable moving fwd locked apps and system packages
9768 if (pkg.applicationInfo != null &&
9769 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9770 Slog.w(TAG, "Cannot move system application");
9771 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9772 } else if (pkg.applicationInfo != null &&
9773 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9774 Slog.w(TAG, "Cannot move forward locked app.");
9775 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009776 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009777 // Find install location first
9778 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9779 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9780 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009781 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009782 } else {
9783 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9784 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9785 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9786 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9787 if (newFlags == currFlags) {
9788 Slog.w(TAG, "No move required. Trying to move to same location");
9789 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9790 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009791 }
9792 }
9793 }
9794 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9795 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9796 } else {
9797 Message msg = mHandler.obtainMessage(INIT_COPY);
9798 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9799 pkg.applicationInfo.publicSourceDir);
9800 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9801 packageName);
9802 msg.obj = mp;
9803 mHandler.sendMessage(msg);
9804 }
9805 }
9806 }
9807
9808 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9809 // Queue up an async operation since the package deletion may take a little while.
9810 mHandler.post(new Runnable() {
9811 public void run() {
9812 mHandler.removeCallbacks(this);
9813 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009814 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9815 int uidArr[] = null;
9816 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009817 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009818 PackageParser.Package pkg = mPackages.get(mp.packageName);
9819 if (pkg == null ) {
9820 Slog.w(TAG, " Package " + mp.packageName +
9821 " doesn't exist. Aborting move");
9822 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9823 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9824 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9825 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9826 " Aborting move and returning error");
9827 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9828 } else {
9829 uidArr = new int[] { pkg.applicationInfo.uid };
9830 pkgList = new ArrayList<String>();
9831 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009832 }
9833 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009834 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9835 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009836 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009837 // Update package code and resource paths
9838 synchronized (mInstallLock) {
9839 synchronized (mPackages) {
9840 PackageParser.Package pkg = mPackages.get(mp.packageName);
9841 // Recheck for package again.
9842 if (pkg == null ) {
9843 Slog.w(TAG, " Package " + mp.packageName +
9844 " doesn't exist. Aborting move");
9845 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9846 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9847 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9848 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9849 " Aborting move and returning error");
9850 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9851 } else {
9852 String oldCodePath = pkg.mPath;
9853 String newCodePath = mp.targetArgs.getCodePath();
9854 String newResPath = mp.targetArgs.getResourcePath();
9855 pkg.mPath = newCodePath;
9856 // Move dex files around
9857 if (moveDexFilesLI(pkg)
9858 != PackageManager.INSTALL_SUCCEEDED) {
9859 // Moving of dex files failed. Set
9860 // error code and abort move.
9861 pkg.mPath = pkg.mScanPath;
9862 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9863 } else {
9864 pkg.mScanPath = newCodePath;
9865 pkg.applicationInfo.sourceDir = newCodePath;
9866 pkg.applicationInfo.publicSourceDir = newResPath;
9867 PackageSetting ps = (PackageSetting) pkg.mExtras;
9868 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9869 ps.codePathString = ps.codePath.getPath();
9870 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9871 ps.resourcePathString = ps.resourcePath.getPath();
9872 // Set the application info flag correctly.
9873 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9874 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9875 } else {
9876 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9877 }
9878 ps.setFlags(pkg.applicationInfo.flags);
9879 mAppDirs.remove(oldCodePath);
9880 mAppDirs.put(newCodePath, pkg);
9881 // Persist settings
9882 mSettings.writeLP();
9883 }
9884 }
9885 }
9886 // Send resources available broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009887 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009888 }
9889 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009890 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009891 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009892 // Clean up failed installation
9893 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009894 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009895 }
9896 } else {
9897 // Force a gc to clear things up.
9898 Runtime.getRuntime().gc();
9899 // Delete older code
9900 synchronized (mInstallLock) {
9901 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009902 }
9903 }
9904 IPackageMoveObserver observer = mp.observer;
9905 if (observer != null) {
9906 try {
9907 observer.packageMoved(mp.packageName, returnCode);
9908 } catch (RemoteException e) {
9909 Log.i(TAG, "Observer no longer exists.");
9910 }
9911 }
9912 }
9913 });
9914 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009915
9916 public boolean setInstallLocation(int loc) {
9917 mContext.enforceCallingOrSelfPermission(
9918 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9919 if (getInstallLocation() == loc) {
9920 return true;
9921 }
9922 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9923 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9924 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9925 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9926 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9927 return true;
9928 }
9929 return false;
9930 }
9931
9932 public int getInstallLocation() {
9933 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9934 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009936}
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009937