blob: 78f7b33b6fdff65e5b9c0f9c432fcd55ec8fa5c2 [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
152 private static final int REMOVE_EVENTS =
153 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
154 private static final int ADD_EVENTS =
155 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
156
157 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800158 // Suffix used during package installation when copying/moving
159 // package apks to install directory.
160 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800162 /**
163 * Indicates the state of installation. Used by PackageManager to
164 * figure out incomplete installations. Say a package is being installed
165 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
166 * the package installation is successful or unsuccesful lin which case
167 * the PackageManager will no longer maintain state information associated
168 * with the package. If some exception(like device freeze or battery being
169 * pulled out) occurs during installation of a package, the PackageManager
170 * needs this information to clean up the previously failed installation.
171 */
172 private static final int PKG_INSTALL_INCOMPLETE = 0;
173 private static final int PKG_INSTALL_COMPLETE = 1;
174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final int SCAN_MONITOR = 1<<0;
176 static final int SCAN_NO_DEX = 1<<1;
177 static final int SCAN_FORCE_DEX = 1<<2;
178 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800179 static final int SCAN_NEW_INSTALL = 1<<4;
180 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800182 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
183 "com.android.defcontainer",
184 "com.android.defcontainer.DefaultContainerService");
185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
187 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700188 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
Dianne Hackborn851a5412009-05-08 12:06:44 -0700190 final int mSdkVersion = Build.VERSION.SDK_INT;
191 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
192 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 final Context mContext;
195 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700196 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 final DisplayMetrics mMetrics;
198 final int mDefParseFlags;
199 final String[] mSeparateProcesses;
200
201 // This is where all application persistent data goes.
202 final File mAppDataDir;
203
204 // This is the object monitoring the framework dir.
205 final FileObserver mFrameworkInstallObserver;
206
207 // This is the object monitoring the system app dir.
208 final FileObserver mSystemInstallObserver;
209
210 // This is the object monitoring mAppInstallDir.
211 final FileObserver mAppInstallObserver;
212
213 // This is the object monitoring mDrmAppPrivateInstallDir.
214 final FileObserver mDrmAppInstallObserver;
215
216 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
217 // LOCK HELD. Can be called with mInstallLock held.
218 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 final File mFrameworkDir;
221 final File mSystemAppDir;
222 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700223 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224
225 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
226 // apps.
227 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 // Lock for state used when installing and doing other long running
232 // operations. Methods that must be called with this lock held have
233 // the prefix "LI".
234 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 // These are the directories in the 3rd party applications installed dir
237 // that we have currently loaded packages from. Keys are the application's
238 // installed zip file (absolute codePath), and values are Package.
239 final HashMap<String, PackageParser.Package> mAppDirs =
240 new HashMap<String, PackageParser.Package>();
241
242 // Information for the parser to write more useful error messages.
243 File mScanningPath;
244 int mLastScanError;
245
246 final int[] mOutPermissions = new int[3];
247
248 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 // Keys are String (package name), values are Package. This also serves
251 // as the lock for the global state. Methods that must be called with
252 // this lock held have the prefix "LP".
253 final HashMap<String, PackageParser.Package> mPackages =
254 new HashMap<String, PackageParser.Package>();
255
256 final Settings mSettings;
257 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
259 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
260 int[] mGlobalGids;
261
262 // These are the built-in uid -> permission mappings that were read from the
263 // etc/permissions.xml file.
264 final SparseArray<HashSet<String>> mSystemPermissions =
265 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 // These are the built-in shared libraries that were read from the
268 // etc/permissions.xml file.
269 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800270
Dianne Hackborn49237342009-08-27 20:08:01 -0700271 // Temporary for building the final shared libraries for an .apk.
272 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800273
Dianne Hackborn49237342009-08-27 20:08:01 -0700274 // These are the features this devices supports that were read from the
275 // etc/permissions.xml file.
276 final HashMap<String, FeatureInfo> mAvailableFeatures =
277 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 // All available activities, for your resolving pleasure.
280 final ActivityIntentResolver mActivities =
281 new ActivityIntentResolver();
282
283 // All available receivers, for your resolving pleasure.
284 final ActivityIntentResolver mReceivers =
285 new ActivityIntentResolver();
286
287 // All available services, for your resolving pleasure.
288 final ServiceIntentResolver mServices = new ServiceIntentResolver();
289
290 // Keys are String (provider class name), values are Provider.
291 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
292 new HashMap<ComponentName, PackageParser.Provider>();
293
294 // Mapping from provider base names (first directory in content URI codePath)
295 // to the provider information.
296 final HashMap<String, PackageParser.Provider> mProviders =
297 new HashMap<String, PackageParser.Provider>();
298
299 // Mapping from instrumentation class names to info about them.
300 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
301 new HashMap<ComponentName, PackageParser.Instrumentation>();
302
303 // Mapping from permission names to info about them.
304 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
305 new HashMap<String, PackageParser.PermissionGroup>();
306
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800307 // Packages whose data we have transfered into another package, thus
308 // should no longer exist.
309 final HashSet<String> mTransferedPackages = new HashSet<String>();
310
Dianne Hackborn854060af2009-07-09 18:14:31 -0700311 // Broadcast actions that are only available to the system.
312 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 boolean mSystemReady;
315 boolean mSafeMode;
316 boolean mHasSystemUidErrors;
317
318 ApplicationInfo mAndroidApplication;
319 final ActivityInfo mResolveActivity = new ActivityInfo();
320 final ResolveInfo mResolveInfo = new ResolveInfo();
321 ComponentName mResolveComponentName;
322 PackageParser.Package mPlatformPackage;
323
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700324 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800325 final HashMap<String, ArrayList<String>> mPendingBroadcasts
326 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800327 // Service Connection to remote media container service to copy
328 // package uri's from external media onto secure containers
329 // or internal storage.
330 private IMediaContainerService mContainerService = null;
331
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700332 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800333 static final int MCS_BOUND = 3;
334 static final int END_COPY = 4;
335 static final int INIT_COPY = 5;
336 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800337 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800338 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800339 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800340 static final int MCS_RECONNECT = 10;
341 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700342 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700343 static final int WRITE_SETTINGS = 13;
344
345 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800346
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700347 // Delay time in millisecs
348 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800349 final private DefaultContainerConnection mDefContainerConn =
350 new DefaultContainerConnection();
351 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800352 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800353 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800354 IMediaContainerService imcs =
355 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800356 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800357 }
358
359 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800360 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800361 }
362 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700363
Christopher Tate1bb69062010-02-19 17:02:12 -0800364 // Recordkeeping of restore-after-install operations that are currently in flight
365 // between the Package Manager and the Backup Manager
366 class PostInstallData {
367 public InstallArgs args;
368 public PackageInstalledInfo res;
369
370 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
371 args = _a;
372 res = _r;
373 }
374 };
375 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
376 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
377
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800379 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800380 final ArrayList<HandlerParams> mPendingInstalls =
381 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800382
383 private boolean connectToService() {
384 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
385 " DefaultContainerService");
386 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700387 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800388 if (mContext.bindService(service, mDefContainerConn,
389 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700390 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800391 mBound = true;
392 return true;
393 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700394 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800395 return false;
396 }
397
398 private void disconnectService() {
399 mContainerService = null;
400 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700401 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700403 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800404 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800405
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700406 PackageHandler(Looper looper) {
407 super(looper);
408 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700409
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700410 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700411 try {
412 doHandleMessage(msg);
413 } finally {
414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
415 }
416 }
417
418 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700419 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800420 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800421 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800422 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800423 int idx = mPendingInstalls.size();
424 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
425 // If a bind was already initiated we dont really
426 // need to do anything. The pending install
427 // will be processed later on.
428 if (!mBound) {
429 // If this is the only one pending we might
430 // have to bind to the service again.
431 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800432 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800433 params.serviceError();
434 return;
435 } else {
436 // Once we bind to the service, the first
437 // pending request will be processed.
438 mPendingInstalls.add(idx, params);
439 }
440 } else {
441 mPendingInstalls.add(idx, params);
442 // Already bound to the service. Just make
443 // sure we trigger off processing the first request.
444 if (idx == 0) {
445 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800446 }
447 }
448 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800449 }
450 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800451 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800452 if (msg.obj != null) {
453 mContainerService = (IMediaContainerService) msg.obj;
454 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800455 if (mContainerService == null) {
456 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800457 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800458 for (HandlerParams params : mPendingInstalls) {
459 mPendingInstalls.remove(0);
460 // Indicate service bind error
461 params.serviceError();
462 }
463 mPendingInstalls.clear();
464 } else if (mPendingInstalls.size() > 0) {
465 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800466 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800467 params.startCopy();
468 }
469 } else {
470 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800471 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800472 }
473 break;
474 }
475 case MCS_RECONNECT : {
476 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
477 if (mPendingInstalls.size() > 0) {
478 if (mBound) {
479 disconnectService();
480 }
481 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800482 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800483 for (HandlerParams params : mPendingInstalls) {
484 mPendingInstalls.remove(0);
485 // Indicate service bind error
486 params.serviceError();
487 }
488 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800489 }
490 }
491 break;
492 }
493 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800494 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
495 // Delete pending install
496 if (mPendingInstalls.size() > 0) {
497 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800498 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800499 if (mPendingInstalls.size() == 0) {
500 if (mBound) {
501 disconnectService();
502 }
503 } else {
504 // There are more pending requests in queue.
505 // Just post MCS_BOUND message to trigger processing
506 // of next pending install.
507 mHandler.sendEmptyMessage(MCS_BOUND);
508 }
509 break;
510 }
511 case MCS_GIVE_UP: {
512 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
513 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800514 break;
515 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700516 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800517 String packages[];
518 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700519 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700520 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700521 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700522 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800523 if (mPendingBroadcasts == null) {
524 return;
525 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700526 size = mPendingBroadcasts.size();
527 if (size <= 0) {
528 // Nothing to be done. Just return
529 return;
530 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800531 packages = new String[size];
532 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700533 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800534 Iterator<HashMap.Entry<String, ArrayList<String>>>
535 it = mPendingBroadcasts.entrySet().iterator();
536 int i = 0;
537 while (it.hasNext() && i < size) {
538 HashMap.Entry<String, ArrayList<String>> ent = it.next();
539 packages[i] = ent.getKey();
540 components[i] = ent.getValue();
541 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700542 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800543 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700544 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800545 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700546 mPendingBroadcasts.clear();
547 }
548 // Send broadcasts
549 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800550 sendPackageChangedBroadcast(packages[i], true,
551 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700552 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700553 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700554 break;
555 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800556 case START_CLEANING_PACKAGE: {
557 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700558 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800559 synchronized (mPackages) {
560 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
561 mSettings.mPackagesToBeCleaned.add(packageName);
562 }
563 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700564 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800565 startCleaningPackages();
566 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800567 case POST_INSTALL: {
568 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
569 PostInstallData data = mRunningInstalls.get(msg.arg1);
570 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800571 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800572
573 if (data != null) {
574 InstallArgs args = data.args;
575 PackageInstalledInfo res = data.res;
576
577 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
578 res.removedInfo.sendBroadcast(false, true);
579 Bundle extras = new Bundle(1);
580 extras.putInt(Intent.EXTRA_UID, res.uid);
581 final boolean update = res.removedInfo.removedPackage != null;
582 if (update) {
583 extras.putBoolean(Intent.EXTRA_REPLACING, true);
584 }
585 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
586 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700587 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800588 if (update) {
589 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
590 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700591 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800592 }
593 if (res.removedInfo.args != null) {
594 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800595 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800596 }
597 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800598 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800599 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800600 // We delete after a gc for applications on sdcard.
601 if (deleteOld) {
602 synchronized (mInstallLock) {
603 res.removedInfo.args.doPostDeleteLI(true);
604 }
605 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800606 if (args.observer != null) {
607 try {
608 args.observer.packageInstalled(res.name, res.returnCode);
609 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800610 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800611 }
612 }
613 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800614 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800615 }
616 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700617 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700618 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
619 boolean reportStatus = msg.arg1 == 1;
620 boolean doGc = msg.arg2 == 1;
621 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
622 if (doGc) {
623 // Force a gc to clear up stale containers.
624 Runtime.getRuntime().gc();
625 }
626 if (msg.obj != null) {
627 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
628 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
629 // Unload containers
630 unloadAllContainers(args);
631 }
632 if (reportStatus) {
633 try {
634 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
635 PackageHelper.getMountService().finishMediaUpdate();
636 } catch (RemoteException e) {
637 Log.e(TAG, "MountService not running?");
638 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700639 }
640 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700641 case WRITE_SETTINGS: {
642 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
643 synchronized (mPackages) {
644 removeMessages(WRITE_SETTINGS);
645 mSettings.writeLP();
646 }
647 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
648 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700649 }
650 }
651 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800652
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700653 void scheduleWriteSettingsLocked() {
654 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
655 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
656 }
657 }
658
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800659 static boolean installOnSd(int flags) {
660 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700661 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800662 return false;
663 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700664 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
665 return true;
666 }
667 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800668 }
669
670 static boolean isFwdLocked(int flags) {
671 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
672 return true;
673 }
674 return false;
675 }
676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 public static final IPackageManager main(Context context, boolean factoryTest) {
678 PackageManagerService m = new PackageManagerService(context, factoryTest);
679 ServiceManager.addService("package", m);
680 return m;
681 }
682
683 static String[] splitString(String str, char sep) {
684 int count = 1;
685 int i = 0;
686 while ((i=str.indexOf(sep, i)) >= 0) {
687 count++;
688 i++;
689 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 String[] res = new String[count];
692 i=0;
693 count = 0;
694 int lastI=0;
695 while ((i=str.indexOf(sep, i)) >= 0) {
696 res[count] = str.substring(lastI, i);
697 count++;
698 i++;
699 lastI = i;
700 }
701 res[count] = str.substring(lastI, str.length());
702 return res;
703 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800706 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800710 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 mContext = context;
714 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700715 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 mMetrics = new DisplayMetrics();
717 mSettings = new Settings();
718 mSettings.addSharedUserLP("android.uid.system",
719 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
720 mSettings.addSharedUserLP("android.uid.phone",
721 MULTIPLE_APPLICATION_UIDS
722 ? RADIO_UID : FIRST_APPLICATION_UID,
723 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400724 mSettings.addSharedUserLP("android.uid.log",
725 MULTIPLE_APPLICATION_UIDS
726 ? LOG_UID : FIRST_APPLICATION_UID,
727 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728
729 String separateProcesses = SystemProperties.get("debug.separate_processes");
730 if (separateProcesses != null && separateProcesses.length() > 0) {
731 if ("*".equals(separateProcesses)) {
732 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
733 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800734 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 } else {
736 mDefParseFlags = 0;
737 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800738 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 + separateProcesses);
740 }
741 } else {
742 mDefParseFlags = 0;
743 mSeparateProcesses = null;
744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 Installer installer = new Installer();
747 // Little hacky thing to check if installd is here, to determine
748 // whether we are running on the simulator and thus need to take
749 // care of building the /data file structure ourself.
750 // (apparently the sim now has a working installer)
751 if (installer.ping() && Process.supportsProcesses()) {
752 mInstaller = installer;
753 } else {
754 mInstaller = null;
755 }
756
757 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
758 Display d = wm.getDefaultDisplay();
759 d.getMetrics(mMetrics);
760
761 synchronized (mInstallLock) {
762 synchronized (mPackages) {
763 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700764 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 File dataDir = Environment.getDataDirectory();
767 mAppDataDir = new File(dataDir, "data");
768 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
769
770 if (mInstaller == null) {
771 // Make sure these dirs exist, when we are running in
772 // the simulator.
773 // Make a wide-open directory for random misc stuff.
774 File miscDir = new File(dataDir, "misc");
775 miscDir.mkdirs();
776 mAppDataDir.mkdirs();
777 mDrmAppPrivateInstallDir.mkdirs();
778 }
779
780 readPermissions();
781
782 mRestoredSettings = mSettings.readLP();
783 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800784
785 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800787
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800788 // Set flag to monitor and not change apk file paths when
789 // scanning install directories.
790 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700791 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800792 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800793 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700794 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700799 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700802 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 /**
805 * Out of paranoia, ensure that everything in the boot class
806 * path has been dexed.
807 */
808 String bootClassPath = System.getProperty("java.boot.class.path");
809 if (bootClassPath != null) {
810 String[] paths = splitString(bootClassPath, ':');
811 for (int i=0; i<paths.length; i++) {
812 try {
813 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
814 libFiles.add(paths[i]);
815 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700816 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 }
818 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800819 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800821 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 }
823 }
824 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800825 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 /**
829 * Also ensure all external libraries have had dexopt run on them.
830 */
831 if (mSharedLibraries.size() > 0) {
832 Iterator<String> libs = mSharedLibraries.values().iterator();
833 while (libs.hasNext()) {
834 String lib = libs.next();
835 try {
836 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
837 libFiles.add(lib);
838 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700839 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 }
841 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800842 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800844 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 }
846 }
847 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 // Gross hack for now: we know this file doesn't contain any
850 // code, so don't dexopt it to avoid the resulting log spew.
851 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 /**
854 * And there are a number of commands implemented in Java, which
855 * we currently need to do the dexopt on so that they can be
856 * run from a non-root shell.
857 */
858 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700859 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 for (int i=0; i<frameworkFiles.length; i++) {
861 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
862 String path = libPath.getPath();
863 // Skip the file if we alrady did it.
864 if (libFiles.contains(path)) {
865 continue;
866 }
867 // Skip the file if it is not a type we want to dexopt.
868 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
869 continue;
870 }
871 try {
872 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
873 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700874 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 }
876 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800877 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800879 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 }
881 }
882 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800883
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700884 if (didDexOpt) {
885 // If we had to do a dexopt of one of the previous
886 // things, then something on the system has changed.
887 // Consider this significant, and wipe away all other
888 // existing dexopt files to ensure we don't leave any
889 // dangling around.
890 String[] files = mDalvikCacheDir.list();
891 if (files != null) {
892 for (int i=0; i<files.length; i++) {
893 String fn = files[i];
894 if (fn.startsWith("data@app@")
895 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800896 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700897 (new File(mDalvikCacheDir, fn)).delete();
898 }
899 }
900 }
901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800903
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800904 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 mFrameworkInstallObserver = new AppDirObserver(
906 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
907 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700908 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
909 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800910 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800911
912 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
914 mSystemInstallObserver = new AppDirObserver(
915 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
916 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700917 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
918 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800919
920 if (mInstaller != null) {
921 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
922 mInstaller.moveFiles();
923 }
924
925 // Prune any system packages that no longer exist.
926 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
927 while (psit.hasNext()) {
928 PackageSetting ps = psit.next();
929 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800930 && !mPackages.containsKey(ps.name)
931 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800932 psit.remove();
933 String msg = "System package " + ps.name
934 + " no longer exists; wiping its data";
935 reportSettingsProblem(Log.WARN, msg);
936 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -0700937 mInstaller.remove(ps.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800938 }
939 }
940 }
941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 mAppInstallDir = new File(dataDir, "app");
943 if (mInstaller == null) {
944 // Make sure these dirs exist, when we are running in
945 // the simulator.
946 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
947 }
948 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800949 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 //clean up list
951 for(int i = 0; i < deletePkgsList.size(); i++) {
952 //clean up here
953 cleanupInstallFailedPackage(deletePkgsList.get(i));
954 }
955 //delete tmp files
956 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800957
958 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 SystemClock.uptimeMillis());
960 mAppInstallObserver = new AppDirObserver(
961 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
962 mAppInstallObserver.startWatching();
963 scanDirLI(mAppInstallDir, 0, scanMode);
964
965 mDrmAppInstallObserver = new AppDirObserver(
966 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
967 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800968 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800970 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800972 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 + ((SystemClock.uptimeMillis()-startTime)/1000f)
974 + " seconds");
975
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700976 // If the platform SDK has changed since the last time we booted,
977 // we need to re-grant app permission to catch any new ones that
978 // appear. This is really a hack, and means that apps can in some
979 // cases get permissions that the user didn't initially explicitly
980 // allow... it would be nice to have some better way to handle
981 // this situation.
982 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
983 != mSdkVersion;
984 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
985 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
986 + "; regranting permissions for internal storage");
987 mSettings.mInternalSdkPlatform = mSdkVersion;
988
989 updatePermissionsLP(null, null, true, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990
991 mSettings.writeLP();
992
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800993 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 // Now after opening every single application zip, make sure they
997 // are all flushed. Not really needed, but keeps things nice and
998 // tidy.
999 Runtime.getRuntime().gc();
1000 } // synchronized (mPackages)
1001 } // synchronized (mInstallLock)
1002 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 @Override
1005 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1006 throws RemoteException {
1007 try {
1008 return super.onTransact(code, data, reply, flags);
1009 } catch (RuntimeException e) {
1010 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001011 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 }
1013 throw e;
1014 }
1015 }
1016
Dianne Hackborne6620b22010-01-22 14:46:21 -08001017 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001018 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07001020 int retCode = mInstaller.remove(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001022 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001023 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025 } else {
1026 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001027 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 File dataDir = new File(pkg.applicationInfo.dataDir);
1029 dataDir.delete();
1030 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001031 if (ps.codePath != null) {
1032 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001033 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001034 }
1035 }
1036 if (ps.resourcePath != null) {
1037 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001038 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001039 }
1040 }
1041 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043
1044 void readPermissions() {
1045 // Read permissions from .../etc/permission directory.
1046 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1047 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001048 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 return;
1050 }
1051 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001052 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 return;
1054 }
1055
1056 // Iterate over the files in the directory and scan .xml files
1057 for (File f : libraryDir.listFiles()) {
1058 // We'll read platform.xml last
1059 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1060 continue;
1061 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001064 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 continue;
1066 }
1067 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001068 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 continue;
1070 }
1071
1072 readPermissionsFromXml(f);
1073 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1076 final File permFile = new File(Environment.getRootDirectory(),
1077 "etc/permissions/platform.xml");
1078 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001079
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001080 StringBuilder sb = new StringBuilder(128);
1081 sb.append("Libs:");
1082 Iterator<String> it = mSharedLibraries.keySet().iterator();
1083 while (it.hasNext()) {
1084 sb.append(' ');
1085 String name = it.next();
1086 sb.append(name);
1087 sb.append(':');
1088 sb.append(mSharedLibraries.get(name));
1089 }
1090 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001091
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001092 sb.setLength(0);
1093 sb.append("Features:");
1094 it = mAvailableFeatures.keySet().iterator();
1095 while (it.hasNext()) {
1096 sb.append(' ');
1097 sb.append(it.next());
1098 }
1099 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001101
1102 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 FileReader permReader = null;
1104 try {
1105 permReader = new FileReader(permFile);
1106 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001107 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 return;
1109 }
1110
1111 try {
1112 XmlPullParser parser = Xml.newPullParser();
1113 parser.setInput(permReader);
1114
1115 XmlUtils.beginDocument(parser, "permissions");
1116
1117 while (true) {
1118 XmlUtils.nextElement(parser);
1119 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1120 break;
1121 }
1122
1123 String name = parser.getName();
1124 if ("group".equals(name)) {
1125 String gidStr = parser.getAttributeValue(null, "gid");
1126 if (gidStr != null) {
1127 int gid = Integer.parseInt(gidStr);
1128 mGlobalGids = appendInt(mGlobalGids, gid);
1129 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001130 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 + parser.getPositionDescription());
1132 }
1133
1134 XmlUtils.skipCurrentTag(parser);
1135 continue;
1136 } else if ("permission".equals(name)) {
1137 String perm = parser.getAttributeValue(null, "name");
1138 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001139 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 + parser.getPositionDescription());
1141 XmlUtils.skipCurrentTag(parser);
1142 continue;
1143 }
1144 perm = perm.intern();
1145 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 } else if ("assign-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, "<assign-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 String uidStr = parser.getAttributeValue(null, "uid");
1156 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001157 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 + parser.getPositionDescription());
1159 XmlUtils.skipCurrentTag(parser);
1160 continue;
1161 }
1162 int uid = Process.getUidForName(uidStr);
1163 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001164 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 + uidStr + "\" at "
1166 + parser.getPositionDescription());
1167 XmlUtils.skipCurrentTag(parser);
1168 continue;
1169 }
1170 perm = perm.intern();
1171 HashSet<String> perms = mSystemPermissions.get(uid);
1172 if (perms == null) {
1173 perms = new HashSet<String>();
1174 mSystemPermissions.put(uid, perms);
1175 }
1176 perms.add(perm);
1177 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 } else if ("library".equals(name)) {
1180 String lname = parser.getAttributeValue(null, "name");
1181 String lfile = parser.getAttributeValue(null, "file");
1182 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001183 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 + parser.getPositionDescription());
1185 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001186 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 + parser.getPositionDescription());
1188 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001189 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001190 mSharedLibraries.put(lname, lfile);
1191 }
1192 XmlUtils.skipCurrentTag(parser);
1193 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001194
Dianne Hackborn49237342009-08-27 20:08:01 -07001195 } else if ("feature".equals(name)) {
1196 String fname = parser.getAttributeValue(null, "name");
1197 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001198 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001199 + parser.getPositionDescription());
1200 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001201 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001202 FeatureInfo fi = new FeatureInfo();
1203 fi.name = fname;
1204 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 }
1206 XmlUtils.skipCurrentTag(parser);
1207 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 } else {
1210 XmlUtils.skipCurrentTag(parser);
1211 continue;
1212 }
1213
1214 }
1215 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001216 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001218 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 }
1220 }
1221
1222 void readPermission(XmlPullParser parser, String name)
1223 throws IOException, XmlPullParserException {
1224
1225 name = name.intern();
1226
1227 BasePermission bp = mSettings.mPermissions.get(name);
1228 if (bp == null) {
1229 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1230 mSettings.mPermissions.put(name, bp);
1231 }
1232 int outerDepth = parser.getDepth();
1233 int type;
1234 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1235 && (type != XmlPullParser.END_TAG
1236 || parser.getDepth() > outerDepth)) {
1237 if (type == XmlPullParser.END_TAG
1238 || type == XmlPullParser.TEXT) {
1239 continue;
1240 }
1241
1242 String tagName = parser.getName();
1243 if ("group".equals(tagName)) {
1244 String gidStr = parser.getAttributeValue(null, "gid");
1245 if (gidStr != null) {
1246 int gid = Process.getGidForName(gidStr);
1247 bp.gids = appendInt(bp.gids, gid);
1248 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001249 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 + parser.getPositionDescription());
1251 }
1252 }
1253 XmlUtils.skipCurrentTag(parser);
1254 }
1255 }
1256
1257 static int[] appendInt(int[] cur, int val) {
1258 if (cur == null) {
1259 return new int[] { val };
1260 }
1261 final int N = cur.length;
1262 for (int i=0; i<N; i++) {
1263 if (cur[i] == val) {
1264 return cur;
1265 }
1266 }
1267 int[] ret = new int[N+1];
1268 System.arraycopy(cur, 0, ret, 0, N);
1269 ret[N] = val;
1270 return ret;
1271 }
1272
1273 static int[] appendInts(int[] cur, int[] add) {
1274 if (add == null) return cur;
1275 if (cur == null) return add;
1276 final int N = add.length;
1277 for (int i=0; i<N; i++) {
1278 cur = appendInt(cur, add[i]);
1279 }
1280 return cur;
1281 }
1282
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001283 static int[] removeInt(int[] cur, int val) {
1284 if (cur == null) {
1285 return null;
1286 }
1287 final int N = cur.length;
1288 for (int i=0; i<N; i++) {
1289 if (cur[i] == val) {
1290 int[] ret = new int[N-1];
1291 if (i > 0) {
1292 System.arraycopy(cur, 0, ret, 0, i);
1293 }
1294 if (i < (N-1)) {
1295 System.arraycopy(cur, i, ret, i+1, N-i-1);
1296 }
1297 return ret;
1298 }
1299 }
1300 return cur;
1301 }
1302
1303 static int[] removeInts(int[] cur, int[] rem) {
1304 if (rem == null) return cur;
1305 if (cur == null) return cur;
1306 final int N = rem.length;
1307 for (int i=0; i<N; i++) {
1308 cur = removeInt(cur, rem[i]);
1309 }
1310 return cur;
1311 }
1312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001314 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1315 // The package has been uninstalled but has retained data and resources.
1316 return PackageParser.generatePackageInfo(p, null, flags);
1317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 final PackageSetting ps = (PackageSetting)p.mExtras;
1319 if (ps == null) {
1320 return null;
1321 }
1322 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1323 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1324 }
1325
1326 public PackageInfo getPackageInfo(String packageName, int flags) {
1327 synchronized (mPackages) {
1328 PackageParser.Package p = mPackages.get(packageName);
1329 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001330 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 + ": " + p);
1332 if (p != null) {
1333 return generatePackageInfo(p, flags);
1334 }
1335 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1336 return generatePackageInfoFromSettingsLP(packageName, flags);
1337 }
1338 }
1339 return null;
1340 }
1341
Dianne Hackborn47096932010-02-11 15:57:09 -08001342 public String[] currentToCanonicalPackageNames(String[] names) {
1343 String[] out = new String[names.length];
1344 synchronized (mPackages) {
1345 for (int i=names.length-1; i>=0; i--) {
1346 PackageSetting ps = mSettings.mPackages.get(names[i]);
1347 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1348 }
1349 }
1350 return out;
1351 }
1352
1353 public String[] canonicalToCurrentPackageNames(String[] names) {
1354 String[] out = new String[names.length];
1355 synchronized (mPackages) {
1356 for (int i=names.length-1; i>=0; i--) {
1357 String cur = mSettings.mRenamedPackages.get(names[i]);
1358 out[i] = cur != null ? cur : names[i];
1359 }
1360 }
1361 return out;
1362 }
1363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 public int getPackageUid(String packageName) {
1365 synchronized (mPackages) {
1366 PackageParser.Package p = mPackages.get(packageName);
1367 if(p != null) {
1368 return p.applicationInfo.uid;
1369 }
1370 PackageSetting ps = mSettings.mPackages.get(packageName);
1371 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1372 return -1;
1373 }
1374 p = ps.pkg;
1375 return p != null ? p.applicationInfo.uid : -1;
1376 }
1377 }
1378
1379 public int[] getPackageGids(String packageName) {
1380 synchronized (mPackages) {
1381 PackageParser.Package p = mPackages.get(packageName);
1382 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001383 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 + ": " + p);
1385 if (p != null) {
1386 final PackageSetting ps = (PackageSetting)p.mExtras;
1387 final SharedUserSetting suid = ps.sharedUser;
1388 return suid != null ? suid.gids : ps.gids;
1389 }
1390 }
1391 // stupid thing to indicate an error.
1392 return new int[0];
1393 }
1394
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001395 static final PermissionInfo generatePermissionInfo(
1396 BasePermission bp, int flags) {
1397 if (bp.perm != null) {
1398 return PackageParser.generatePermissionInfo(bp.perm, flags);
1399 }
1400 PermissionInfo pi = new PermissionInfo();
1401 pi.name = bp.name;
1402 pi.packageName = bp.sourcePackage;
1403 pi.nonLocalizedLabel = bp.name;
1404 pi.protectionLevel = bp.protectionLevel;
1405 return pi;
1406 }
1407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 public PermissionInfo getPermissionInfo(String name, int flags) {
1409 synchronized (mPackages) {
1410 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001411 if (p != null) {
1412 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 }
1414 return null;
1415 }
1416 }
1417
1418 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1419 synchronized (mPackages) {
1420 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1421 for (BasePermission p : mSettings.mPermissions.values()) {
1422 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001423 if (p.perm == null || p.perm.info.group == null) {
1424 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 }
1426 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001427 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1429 }
1430 }
1431 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 if (out.size() > 0) {
1434 return out;
1435 }
1436 return mPermissionGroups.containsKey(group) ? out : null;
1437 }
1438 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1441 synchronized (mPackages) {
1442 return PackageParser.generatePermissionGroupInfo(
1443 mPermissionGroups.get(name), flags);
1444 }
1445 }
1446
1447 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1448 synchronized (mPackages) {
1449 final int N = mPermissionGroups.size();
1450 ArrayList<PermissionGroupInfo> out
1451 = new ArrayList<PermissionGroupInfo>(N);
1452 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1453 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1454 }
1455 return out;
1456 }
1457 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1460 PackageSetting ps = mSettings.mPackages.get(packageName);
1461 if(ps != null) {
1462 if(ps.pkg == null) {
1463 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1464 if(pInfo != null) {
1465 return pInfo.applicationInfo;
1466 }
1467 return null;
1468 }
1469 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1470 }
1471 return null;
1472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1475 PackageSetting ps = mSettings.mPackages.get(packageName);
1476 if(ps != null) {
1477 if(ps.pkg == null) {
1478 ps.pkg = new PackageParser.Package(packageName);
1479 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001480 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1481 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1482 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1483 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 }
1485 return generatePackageInfo(ps.pkg, flags);
1486 }
1487 return null;
1488 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1491 synchronized (mPackages) {
1492 PackageParser.Package p = mPackages.get(packageName);
1493 if (Config.LOGV) Log.v(
1494 TAG, "getApplicationInfo " + packageName
1495 + ": " + p);
1496 if (p != null) {
1497 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001498 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500 if ("android".equals(packageName)||"system".equals(packageName)) {
1501 return mAndroidApplication;
1502 }
1503 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1504 return generateApplicationInfoFromSettingsLP(packageName, flags);
1505 }
1506 }
1507 return null;
1508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001509
1510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1512 mContext.enforceCallingOrSelfPermission(
1513 android.Manifest.permission.CLEAR_APP_CACHE, null);
1514 // Queue up an async operation since clearing cache may take a little while.
1515 mHandler.post(new Runnable() {
1516 public void run() {
1517 mHandler.removeCallbacks(this);
1518 int retCode = -1;
1519 if (mInstaller != null) {
1520 retCode = mInstaller.freeCache(freeStorageSize);
1521 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001522 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 }
1524 } //end if mInstaller
1525 if (observer != null) {
1526 try {
1527 observer.onRemoveCompleted(null, (retCode >= 0));
1528 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001529 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 }
1531 }
1532 }
1533 });
1534 }
1535
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001536 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001537 mContext.enforceCallingOrSelfPermission(
1538 android.Manifest.permission.CLEAR_APP_CACHE, null);
1539 // Queue up an async operation since clearing cache may take a little while.
1540 mHandler.post(new Runnable() {
1541 public void run() {
1542 mHandler.removeCallbacks(this);
1543 int retCode = -1;
1544 if (mInstaller != null) {
1545 retCode = mInstaller.freeCache(freeStorageSize);
1546 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001547 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001548 }
1549 }
1550 if(pi != null) {
1551 try {
1552 // Callback via pending intent
1553 int code = (retCode >= 0) ? 1 : 0;
1554 pi.sendIntent(null, code, null,
1555 null, null);
1556 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001557 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001558 }
1559 }
1560 }
1561 });
1562 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1565 synchronized (mPackages) {
1566 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001567
1568 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001570 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 }
1572 if (mResolveComponentName.equals(component)) {
1573 return mResolveActivity;
1574 }
1575 }
1576 return null;
1577 }
1578
1579 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1580 synchronized (mPackages) {
1581 PackageParser.Activity a = mReceivers.mActivities.get(component);
1582 if (Config.LOGV) Log.v(
1583 TAG, "getReceiverInfo " + component + ": " + a);
1584 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1585 return PackageParser.generateActivityInfo(a, flags);
1586 }
1587 }
1588 return null;
1589 }
1590
1591 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1592 synchronized (mPackages) {
1593 PackageParser.Service s = mServices.mServices.get(component);
1594 if (Config.LOGV) Log.v(
1595 TAG, "getServiceInfo " + component + ": " + s);
1596 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1597 return PackageParser.generateServiceInfo(s, flags);
1598 }
1599 }
1600 return null;
1601 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 public String[] getSystemSharedLibraryNames() {
1604 Set<String> libSet;
1605 synchronized (mPackages) {
1606 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001607 int size = libSet.size();
1608 if (size > 0) {
1609 String[] libs = new String[size];
1610 libSet.toArray(libs);
1611 return libs;
1612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001614 return null;
1615 }
1616
1617 public FeatureInfo[] getSystemAvailableFeatures() {
1618 Collection<FeatureInfo> featSet;
1619 synchronized (mPackages) {
1620 featSet = mAvailableFeatures.values();
1621 int size = featSet.size();
1622 if (size > 0) {
1623 FeatureInfo[] features = new FeatureInfo[size+1];
1624 featSet.toArray(features);
1625 FeatureInfo fi = new FeatureInfo();
1626 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1627 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1628 features[size] = fi;
1629 return features;
1630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 }
1632 return null;
1633 }
1634
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001635 public boolean hasSystemFeature(String name) {
1636 synchronized (mPackages) {
1637 return mAvailableFeatures.containsKey(name);
1638 }
1639 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 public int checkPermission(String permName, String pkgName) {
1642 synchronized (mPackages) {
1643 PackageParser.Package p = mPackages.get(pkgName);
1644 if (p != null && p.mExtras != null) {
1645 PackageSetting ps = (PackageSetting)p.mExtras;
1646 if (ps.sharedUser != null) {
1647 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1648 return PackageManager.PERMISSION_GRANTED;
1649 }
1650 } else if (ps.grantedPermissions.contains(permName)) {
1651 return PackageManager.PERMISSION_GRANTED;
1652 }
1653 }
1654 }
1655 return PackageManager.PERMISSION_DENIED;
1656 }
1657
1658 public int checkUidPermission(String permName, int uid) {
1659 synchronized (mPackages) {
1660 Object obj = mSettings.getUserIdLP(uid);
1661 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001662 GrantedPermissions gp = (GrantedPermissions)obj;
1663 if (gp.grantedPermissions.contains(permName)) {
1664 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 }
1666 } else {
1667 HashSet<String> perms = mSystemPermissions.get(uid);
1668 if (perms != null && perms.contains(permName)) {
1669 return PackageManager.PERMISSION_GRANTED;
1670 }
1671 }
1672 }
1673 return PackageManager.PERMISSION_DENIED;
1674 }
1675
1676 private BasePermission findPermissionTreeLP(String permName) {
1677 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1678 if (permName.startsWith(bp.name) &&
1679 permName.length() > bp.name.length() &&
1680 permName.charAt(bp.name.length()) == '.') {
1681 return bp;
1682 }
1683 }
1684 return null;
1685 }
1686
1687 private BasePermission checkPermissionTreeLP(String permName) {
1688 if (permName != null) {
1689 BasePermission bp = findPermissionTreeLP(permName);
1690 if (bp != null) {
1691 if (bp.uid == Binder.getCallingUid()) {
1692 return bp;
1693 }
1694 throw new SecurityException("Calling uid "
1695 + Binder.getCallingUid()
1696 + " is not allowed to add to permission tree "
1697 + bp.name + " owned by uid " + bp.uid);
1698 }
1699 }
1700 throw new SecurityException("No permission tree found for " + permName);
1701 }
1702
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001703 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1704 if (s1 == null) {
1705 return s2 == null;
1706 }
1707 if (s2 == null) {
1708 return false;
1709 }
1710 if (s1.getClass() != s2.getClass()) {
1711 return false;
1712 }
1713 return s1.equals(s2);
1714 }
1715
1716 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1717 if (pi1.icon != pi2.icon) return false;
1718 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1719 if (!compareStrings(pi1.name, pi2.name)) return false;
1720 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1721 // We'll take care of setting this one.
1722 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1723 // These are not currently stored in settings.
1724 //if (!compareStrings(pi1.group, pi2.group)) return false;
1725 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1726 //if (pi1.labelRes != pi2.labelRes) return false;
1727 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1728 return true;
1729 }
1730
1731 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1732 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1733 throw new SecurityException("Label must be specified in permission");
1734 }
1735 BasePermission tree = checkPermissionTreeLP(info.name);
1736 BasePermission bp = mSettings.mPermissions.get(info.name);
1737 boolean added = bp == null;
1738 boolean changed = true;
1739 if (added) {
1740 bp = new BasePermission(info.name, tree.sourcePackage,
1741 BasePermission.TYPE_DYNAMIC);
1742 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1743 throw new SecurityException(
1744 "Not allowed to modify non-dynamic permission "
1745 + info.name);
1746 } else {
1747 if (bp.protectionLevel == info.protectionLevel
1748 && bp.perm.owner.equals(tree.perm.owner)
1749 && bp.uid == tree.uid
1750 && comparePermissionInfos(bp.perm.info, info)) {
1751 changed = false;
1752 }
1753 }
1754 bp.protectionLevel = info.protectionLevel;
1755 bp.perm = new PackageParser.Permission(tree.perm.owner,
1756 new PermissionInfo(info));
1757 bp.perm.info.packageName = tree.perm.info.packageName;
1758 bp.uid = tree.uid;
1759 if (added) {
1760 mSettings.mPermissions.put(info.name, bp);
1761 }
1762 if (changed) {
1763 if (!async) {
1764 mSettings.writeLP();
1765 } else {
1766 scheduleWriteSettingsLocked();
1767 }
1768 }
1769 return added;
1770 }
1771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 public boolean addPermission(PermissionInfo info) {
1773 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001774 return addPermissionLocked(info, false);
1775 }
1776 }
1777
1778 public boolean addPermissionAsync(PermissionInfo info) {
1779 synchronized (mPackages) {
1780 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 }
1782 }
1783
1784 public void removePermission(String name) {
1785 synchronized (mPackages) {
1786 checkPermissionTreeLP(name);
1787 BasePermission bp = mSettings.mPermissions.get(name);
1788 if (bp != null) {
1789 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1790 throw new SecurityException(
1791 "Not allowed to modify non-dynamic permission "
1792 + name);
1793 }
1794 mSettings.mPermissions.remove(name);
1795 mSettings.writeLP();
1796 }
1797 }
1798 }
1799
Dianne Hackborn854060af2009-07-09 18:14:31 -07001800 public boolean isProtectedBroadcast(String actionName) {
1801 synchronized (mPackages) {
1802 return mProtectedBroadcasts.contains(actionName);
1803 }
1804 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 public int checkSignatures(String pkg1, String pkg2) {
1807 synchronized (mPackages) {
1808 PackageParser.Package p1 = mPackages.get(pkg1);
1809 PackageParser.Package p2 = mPackages.get(pkg2);
1810 if (p1 == null || p1.mExtras == null
1811 || p2 == null || p2.mExtras == null) {
1812 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1813 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001814 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 }
1816 }
1817
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001818 public int checkUidSignatures(int uid1, int uid2) {
1819 synchronized (mPackages) {
1820 Signature[] s1;
1821 Signature[] s2;
1822 Object obj = mSettings.getUserIdLP(uid1);
1823 if (obj != null) {
1824 if (obj instanceof SharedUserSetting) {
1825 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1826 } else if (obj instanceof PackageSetting) {
1827 s1 = ((PackageSetting)obj).signatures.mSignatures;
1828 } else {
1829 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1830 }
1831 } else {
1832 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1833 }
1834 obj = mSettings.getUserIdLP(uid2);
1835 if (obj != null) {
1836 if (obj instanceof SharedUserSetting) {
1837 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1838 } else if (obj instanceof PackageSetting) {
1839 s2 = ((PackageSetting)obj).signatures.mSignatures;
1840 } else {
1841 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1842 }
1843 } else {
1844 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1845 }
1846 return checkSignaturesLP(s1, s2);
1847 }
1848 }
1849
1850 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1851 if (s1 == null) {
1852 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1854 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1855 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001856 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1858 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001859 HashSet<Signature> set1 = new HashSet<Signature>();
1860 for (Signature sig : s1) {
1861 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001863 HashSet<Signature> set2 = new HashSet<Signature>();
1864 for (Signature sig : s2) {
1865 set2.add(sig);
1866 }
1867 // Make sure s2 contains all signatures in s1.
1868 if (set1.equals(set2)) {
1869 return PackageManager.SIGNATURE_MATCH;
1870 }
1871 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 }
1873
1874 public String[] getPackagesForUid(int uid) {
1875 synchronized (mPackages) {
1876 Object obj = mSettings.getUserIdLP(uid);
1877 if (obj instanceof SharedUserSetting) {
1878 SharedUserSetting sus = (SharedUserSetting)obj;
1879 final int N = sus.packages.size();
1880 String[] res = new String[N];
1881 Iterator<PackageSetting> it = sus.packages.iterator();
1882 int i=0;
1883 while (it.hasNext()) {
1884 res[i++] = it.next().name;
1885 }
1886 return res;
1887 } else if (obj instanceof PackageSetting) {
1888 PackageSetting ps = (PackageSetting)obj;
1889 return new String[] { ps.name };
1890 }
1891 }
1892 return null;
1893 }
1894
1895 public String getNameForUid(int uid) {
1896 synchronized (mPackages) {
1897 Object obj = mSettings.getUserIdLP(uid);
1898 if (obj instanceof SharedUserSetting) {
1899 SharedUserSetting sus = (SharedUserSetting)obj;
1900 return sus.name + ":" + sus.userId;
1901 } else if (obj instanceof PackageSetting) {
1902 PackageSetting ps = (PackageSetting)obj;
1903 return ps.name;
1904 }
1905 }
1906 return null;
1907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 public int getUidForSharedUser(String sharedUserName) {
1910 if(sharedUserName == null) {
1911 return -1;
1912 }
1913 synchronized (mPackages) {
1914 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1915 if(suid == null) {
1916 return -1;
1917 }
1918 return suid.userId;
1919 }
1920 }
1921
1922 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1923 int flags) {
1924 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001925 return chooseBestActivity(intent, resolvedType, flags, query);
1926 }
1927
Mihai Predaeae850c2009-05-13 10:13:48 +02001928 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1929 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 if (query != null) {
1931 final int N = query.size();
1932 if (N == 1) {
1933 return query.get(0);
1934 } else if (N > 1) {
1935 // If there is more than one activity with the same priority,
1936 // then let the user decide between them.
1937 ResolveInfo r0 = query.get(0);
1938 ResolveInfo r1 = query.get(1);
1939 if (false) {
1940 System.out.println(r0.activityInfo.name +
1941 "=" + r0.priority + " vs " +
1942 r1.activityInfo.name +
1943 "=" + r1.priority);
1944 }
1945 // If the first activity has a higher priority, or a different
1946 // default, then it is always desireable to pick it.
1947 if (r0.priority != r1.priority
1948 || r0.preferredOrder != r1.preferredOrder
1949 || r0.isDefault != r1.isDefault) {
1950 return query.get(0);
1951 }
1952 // If we have saved a preference for a preferred activity for
1953 // this Intent, use that.
1954 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1955 flags, query, r0.priority);
1956 if (ri != null) {
1957 return ri;
1958 }
1959 return mResolveInfo;
1960 }
1961 }
1962 return null;
1963 }
1964
1965 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1966 int flags, List<ResolveInfo> query, int priority) {
1967 synchronized (mPackages) {
1968 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1969 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001970 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1972 if (prefs != null && prefs.size() > 0) {
1973 // First figure out how good the original match set is.
1974 // We will only allow preferred activities that came
1975 // from the same match quality.
1976 int match = 0;
1977 final int N = query.size();
1978 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1979 for (int j=0; j<N; j++) {
1980 ResolveInfo ri = query.get(j);
1981 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1982 + ": 0x" + Integer.toHexString(match));
1983 if (ri.match > match) match = ri.match;
1984 }
1985 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1986 + Integer.toHexString(match));
1987 match &= IntentFilter.MATCH_CATEGORY_MASK;
1988 final int M = prefs.size();
1989 for (int i=0; i<M; i++) {
1990 PreferredActivity pa = prefs.get(i);
1991 if (pa.mMatch != match) {
1992 continue;
1993 }
1994 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1995 if (DEBUG_PREFERRED) {
1996 Log.v(TAG, "Got preferred activity:");
1997 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1998 }
1999 if (ai != null) {
2000 for (int j=0; j<N; j++) {
2001 ResolveInfo ri = query.get(j);
2002 if (!ri.activityInfo.applicationInfo.packageName
2003 .equals(ai.applicationInfo.packageName)) {
2004 continue;
2005 }
2006 if (!ri.activityInfo.name.equals(ai.name)) {
2007 continue;
2008 }
2009
2010 // Okay we found a previously set preferred app.
2011 // If the result set is different from when this
2012 // was created, we need to clear it and re-ask the
2013 // user their preference.
2014 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002015 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 + intent + " type " + resolvedType);
2017 mSettings.mPreferredActivities.removeFilter(pa);
2018 return null;
2019 }
2020
2021 // Yay!
2022 return ri;
2023 }
2024 }
2025 }
2026 }
2027 }
2028 return null;
2029 }
2030
2031 public List<ResolveInfo> queryIntentActivities(Intent intent,
2032 String resolvedType, int flags) {
2033 ComponentName comp = intent.getComponent();
2034 if (comp != null) {
2035 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2036 ActivityInfo ai = getActivityInfo(comp, flags);
2037 if (ai != null) {
2038 ResolveInfo ri = new ResolveInfo();
2039 ri.activityInfo = ai;
2040 list.add(ri);
2041 }
2042 return list;
2043 }
2044
2045 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002046 String pkgName = intent.getPackage();
2047 if (pkgName == null) {
2048 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2049 resolvedType, flags);
2050 }
2051 PackageParser.Package pkg = mPackages.get(pkgName);
2052 if (pkg != null) {
2053 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2054 resolvedType, flags, pkg.activities);
2055 }
2056 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 }
2058 }
2059
2060 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2061 Intent[] specifics, String[] specificTypes, Intent intent,
2062 String resolvedType, int flags) {
2063 final String resultsAction = intent.getAction();
2064
2065 List<ResolveInfo> results = queryIntentActivities(
2066 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2067 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2068
2069 int specificsPos = 0;
2070 int N;
2071
2072 // todo: note that the algorithm used here is O(N^2). This
2073 // isn't a problem in our current environment, but if we start running
2074 // into situations where we have more than 5 or 10 matches then this
2075 // should probably be changed to something smarter...
2076
2077 // First we go through and resolve each of the specific items
2078 // that were supplied, taking care of removing any corresponding
2079 // duplicate items in the generic resolve list.
2080 if (specifics != null) {
2081 for (int i=0; i<specifics.length; i++) {
2082 final Intent sintent = specifics[i];
2083 if (sintent == null) {
2084 continue;
2085 }
2086
2087 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2088 String action = sintent.getAction();
2089 if (resultsAction != null && resultsAction.equals(action)) {
2090 // If this action was explicitly requested, then don't
2091 // remove things that have it.
2092 action = null;
2093 }
2094 ComponentName comp = sintent.getComponent();
2095 ResolveInfo ri = null;
2096 ActivityInfo ai = null;
2097 if (comp == null) {
2098 ri = resolveIntent(
2099 sintent,
2100 specificTypes != null ? specificTypes[i] : null,
2101 flags);
2102 if (ri == null) {
2103 continue;
2104 }
2105 if (ri == mResolveInfo) {
2106 // ACK! Must do something better with this.
2107 }
2108 ai = ri.activityInfo;
2109 comp = new ComponentName(ai.applicationInfo.packageName,
2110 ai.name);
2111 } else {
2112 ai = getActivityInfo(comp, flags);
2113 if (ai == null) {
2114 continue;
2115 }
2116 }
2117
2118 // Look for any generic query activities that are duplicates
2119 // of this specific one, and remove them from the results.
2120 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2121 N = results.size();
2122 int j;
2123 for (j=specificsPos; j<N; j++) {
2124 ResolveInfo sri = results.get(j);
2125 if ((sri.activityInfo.name.equals(comp.getClassName())
2126 && sri.activityInfo.applicationInfo.packageName.equals(
2127 comp.getPackageName()))
2128 || (action != null && sri.filter.matchAction(action))) {
2129 results.remove(j);
2130 if (Config.LOGV) Log.v(
2131 TAG, "Removing duplicate item from " + j
2132 + " due to specific " + specificsPos);
2133 if (ri == null) {
2134 ri = sri;
2135 }
2136 j--;
2137 N--;
2138 }
2139 }
2140
2141 // Add this specific item to its proper place.
2142 if (ri == null) {
2143 ri = new ResolveInfo();
2144 ri.activityInfo = ai;
2145 }
2146 results.add(specificsPos, ri);
2147 ri.specificIndex = i;
2148 specificsPos++;
2149 }
2150 }
2151
2152 // Now we go through the remaining generic results and remove any
2153 // duplicate actions that are found here.
2154 N = results.size();
2155 for (int i=specificsPos; i<N-1; i++) {
2156 final ResolveInfo rii = results.get(i);
2157 if (rii.filter == null) {
2158 continue;
2159 }
2160
2161 // Iterate over all of the actions of this result's intent
2162 // filter... typically this should be just one.
2163 final Iterator<String> it = rii.filter.actionsIterator();
2164 if (it == null) {
2165 continue;
2166 }
2167 while (it.hasNext()) {
2168 final String action = it.next();
2169 if (resultsAction != null && resultsAction.equals(action)) {
2170 // If this action was explicitly requested, then don't
2171 // remove things that have it.
2172 continue;
2173 }
2174 for (int j=i+1; j<N; j++) {
2175 final ResolveInfo rij = results.get(j);
2176 if (rij.filter != null && rij.filter.hasAction(action)) {
2177 results.remove(j);
2178 if (Config.LOGV) Log.v(
2179 TAG, "Removing duplicate item from " + j
2180 + " due to action " + action + " at " + i);
2181 j--;
2182 N--;
2183 }
2184 }
2185 }
2186
2187 // If the caller didn't request filter information, drop it now
2188 // so we don't have to marshall/unmarshall it.
2189 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2190 rii.filter = null;
2191 }
2192 }
2193
2194 // Filter out the caller activity if so requested.
2195 if (caller != null) {
2196 N = results.size();
2197 for (int i=0; i<N; i++) {
2198 ActivityInfo ainfo = results.get(i).activityInfo;
2199 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2200 && caller.getClassName().equals(ainfo.name)) {
2201 results.remove(i);
2202 break;
2203 }
2204 }
2205 }
2206
2207 // If the caller didn't request filter information,
2208 // drop them now so we don't have to
2209 // marshall/unmarshall it.
2210 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2211 N = results.size();
2212 for (int i=0; i<N; i++) {
2213 results.get(i).filter = null;
2214 }
2215 }
2216
2217 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2218 return results;
2219 }
2220
2221 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2222 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002223 ComponentName comp = intent.getComponent();
2224 if (comp != null) {
2225 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2226 ActivityInfo ai = getReceiverInfo(comp, flags);
2227 if (ai != null) {
2228 ResolveInfo ri = new ResolveInfo();
2229 ri.activityInfo = ai;
2230 list.add(ri);
2231 }
2232 return list;
2233 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002236 String pkgName = intent.getPackage();
2237 if (pkgName == null) {
2238 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2239 resolvedType, flags);
2240 }
2241 PackageParser.Package pkg = mPackages.get(pkgName);
2242 if (pkg != null) {
2243 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2244 resolvedType, flags, pkg.receivers);
2245 }
2246 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 }
2248 }
2249
2250 public ResolveInfo resolveService(Intent intent, String resolvedType,
2251 int flags) {
2252 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2253 flags);
2254 if (query != null) {
2255 if (query.size() >= 1) {
2256 // If there is more than one service with the same priority,
2257 // just arbitrarily pick the first one.
2258 return query.get(0);
2259 }
2260 }
2261 return null;
2262 }
2263
2264 public List<ResolveInfo> queryIntentServices(Intent intent,
2265 String resolvedType, int flags) {
2266 ComponentName comp = intent.getComponent();
2267 if (comp != null) {
2268 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2269 ServiceInfo si = getServiceInfo(comp, flags);
2270 if (si != null) {
2271 ResolveInfo ri = new ResolveInfo();
2272 ri.serviceInfo = si;
2273 list.add(ri);
2274 }
2275 return list;
2276 }
2277
2278 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002279 String pkgName = intent.getPackage();
2280 if (pkgName == null) {
2281 return (List<ResolveInfo>)mServices.queryIntent(intent,
2282 resolvedType, flags);
2283 }
2284 PackageParser.Package pkg = mPackages.get(pkgName);
2285 if (pkg != null) {
2286 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2287 resolvedType, flags, pkg.services);
2288 }
2289 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 }
2291 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293 public List<PackageInfo> getInstalledPackages(int flags) {
2294 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2295
2296 synchronized (mPackages) {
2297 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2298 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2299 while (i.hasNext()) {
2300 final PackageSetting ps = i.next();
2301 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2302 if(psPkg != null) {
2303 finalList.add(psPkg);
2304 }
2305 }
2306 }
2307 else {
2308 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2309 while (i.hasNext()) {
2310 final PackageParser.Package p = i.next();
2311 if (p.applicationInfo != null) {
2312 PackageInfo pi = generatePackageInfo(p, flags);
2313 if(pi != null) {
2314 finalList.add(pi);
2315 }
2316 }
2317 }
2318 }
2319 }
2320 return finalList;
2321 }
2322
2323 public List<ApplicationInfo> getInstalledApplications(int flags) {
2324 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2325 synchronized(mPackages) {
2326 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2327 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2328 while (i.hasNext()) {
2329 final PackageSetting ps = i.next();
2330 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2331 if(ai != null) {
2332 finalList.add(ai);
2333 }
2334 }
2335 }
2336 else {
2337 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2338 while (i.hasNext()) {
2339 final PackageParser.Package p = i.next();
2340 if (p.applicationInfo != null) {
2341 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2342 if(ai != null) {
2343 finalList.add(ai);
2344 }
2345 }
2346 }
2347 }
2348 }
2349 return finalList;
2350 }
2351
2352 public List<ApplicationInfo> getPersistentApplications(int flags) {
2353 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2354
2355 synchronized (mPackages) {
2356 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2357 while (i.hasNext()) {
2358 PackageParser.Package p = i.next();
2359 if (p.applicationInfo != null
2360 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2361 && (!mSafeMode || (p.applicationInfo.flags
2362 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2363 finalList.add(p.applicationInfo);
2364 }
2365 }
2366 }
2367
2368 return finalList;
2369 }
2370
2371 public ProviderInfo resolveContentProvider(String name, int flags) {
2372 synchronized (mPackages) {
2373 final PackageParser.Provider provider = mProviders.get(name);
2374 return provider != null
2375 && mSettings.isEnabledLP(provider.info, flags)
2376 && (!mSafeMode || (provider.info.applicationInfo.flags
2377 &ApplicationInfo.FLAG_SYSTEM) != 0)
2378 ? PackageParser.generateProviderInfo(provider, flags)
2379 : null;
2380 }
2381 }
2382
Fred Quintana718d8a22009-04-29 17:53:20 -07002383 /**
2384 * @deprecated
2385 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 public void querySyncProviders(List outNames, List outInfo) {
2387 synchronized (mPackages) {
2388 Iterator<Map.Entry<String, PackageParser.Provider>> i
2389 = mProviders.entrySet().iterator();
2390
2391 while (i.hasNext()) {
2392 Map.Entry<String, PackageParser.Provider> entry = i.next();
2393 PackageParser.Provider p = entry.getValue();
2394
2395 if (p.syncable
2396 && (!mSafeMode || (p.info.applicationInfo.flags
2397 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2398 outNames.add(entry.getKey());
2399 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2400 }
2401 }
2402 }
2403 }
2404
2405 public List<ProviderInfo> queryContentProviders(String processName,
2406 int uid, int flags) {
2407 ArrayList<ProviderInfo> finalList = null;
2408
2409 synchronized (mPackages) {
2410 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2411 while (i.hasNext()) {
2412 PackageParser.Provider p = i.next();
2413 if (p.info.authority != null
2414 && (processName == null ||
2415 (p.info.processName.equals(processName)
2416 && p.info.applicationInfo.uid == uid))
2417 && mSettings.isEnabledLP(p.info, flags)
2418 && (!mSafeMode || (p.info.applicationInfo.flags
2419 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2420 if (finalList == null) {
2421 finalList = new ArrayList<ProviderInfo>(3);
2422 }
2423 finalList.add(PackageParser.generateProviderInfo(p,
2424 flags));
2425 }
2426 }
2427 }
2428
2429 if (finalList != null) {
2430 Collections.sort(finalList, mProviderInitOrderSorter);
2431 }
2432
2433 return finalList;
2434 }
2435
2436 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2437 int flags) {
2438 synchronized (mPackages) {
2439 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2440 return PackageParser.generateInstrumentationInfo(i, flags);
2441 }
2442 }
2443
2444 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2445 int flags) {
2446 ArrayList<InstrumentationInfo> finalList =
2447 new ArrayList<InstrumentationInfo>();
2448
2449 synchronized (mPackages) {
2450 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2451 while (i.hasNext()) {
2452 PackageParser.Instrumentation p = i.next();
2453 if (targetPackage == null
2454 || targetPackage.equals(p.info.targetPackage)) {
2455 finalList.add(PackageParser.generateInstrumentationInfo(p,
2456 flags));
2457 }
2458 }
2459 }
2460
2461 return finalList;
2462 }
2463
2464 private void scanDirLI(File dir, int flags, int scanMode) {
2465 Log.d(TAG, "Scanning app dir " + dir);
2466
2467 String[] files = dir.list();
2468
2469 int i;
2470 for (i=0; i<files.length; i++) {
2471 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002472 if (!isPackageFilename(files[i])) {
2473 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002474 continue;
2475 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002476 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002478 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002479 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2480 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002481 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002482 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002483 file.delete();
2484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 }
2486 }
2487
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002488 private static File getSettingsProblemFile() {
2489 File dataDir = Environment.getDataDirectory();
2490 File systemDir = new File(dataDir, "system");
2491 File fname = new File(systemDir, "uiderrors.txt");
2492 return fname;
2493 }
2494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 private static void reportSettingsProblem(int priority, String msg) {
2496 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002497 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 FileOutputStream out = new FileOutputStream(fname, true);
2499 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002500 SimpleDateFormat formatter = new SimpleDateFormat();
2501 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2502 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 pw.close();
2504 FileUtils.setPermissions(
2505 fname.toString(),
2506 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2507 -1, -1);
2508 } catch (java.io.IOException e) {
2509 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002510 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 }
2512
2513 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2514 PackageParser.Package pkg, File srcFile, int parseFlags) {
2515 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002516 if (ps != null
2517 && ps.codePath.equals(srcFile)
2518 && ps.getTimeStamp() == srcFile.lastModified()) {
2519 if (ps.signatures.mSignatures != null
2520 && ps.signatures.mSignatures.length != 0) {
2521 // Optimization: reuse the existing cached certificates
2522 // if the package appears to be unchanged.
2523 pkg.mSignatures = ps.signatures.mSignatures;
2524 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 }
Jeff Browne7600722010-04-07 18:28:23 -07002526
2527 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002528 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002529 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2530 }
2531
2532 if (!pp.collectCertificates(pkg, parseFlags)) {
2533 mLastScanError = pp.getParseError();
2534 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 }
2536 }
2537 return true;
2538 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 /*
2541 * Scan a package and return the newly parsed package.
2542 * Returns null in case of errors and the error code is stored in mLastScanError
2543 */
2544 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002545 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002547 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002549 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002552 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 if (pkg == null) {
2554 mLastScanError = pp.getParseError();
2555 return null;
2556 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002557 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 PackageSetting updatedPkg;
2559 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002560 // Look to see if we already know about this package.
2561 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002562 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002563 // This package has been renamed to its original name. Let's
2564 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002565 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002566 }
2567 // If there was no original package, see one for the real package name.
2568 if (ps == null) {
2569 ps = mSettings.peekPackageLP(pkg.packageName);
2570 }
2571 // Check to see if this package could be hiding/updating a system
2572 // package. Must look for it either under the original or real
2573 // package name depending on our state.
2574 updatedPkg = mSettings.mDisabledSysPackages.get(
2575 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002577 // First check if this is a system package that may involve an update
2578 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2579 if (!ps.codePath.equals(scanFile)) {
2580 // The path has changed from what was last scanned... check the
2581 // version of the new path against what we have stored to determine
2582 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002583 if (pkg.mVersionCode < ps.versionCode) {
2584 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002585 // Ignore entry. Skip it.
2586 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2587 + "ignored: updated version " + ps.versionCode
2588 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002589 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2590 return null;
2591 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002592 // The current app on the system partion is better than
2593 // what we have updated to on the data partition; switch
2594 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002595 // At this point, its safely assumed that package installation for
2596 // apps in system partition will go through. If not there won't be a working
2597 // version of the app
2598 synchronized (mPackages) {
2599 // Just remove the loaded entries from package lists.
2600 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002601 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002602 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002603 + "reverting from " + ps.codePathString
2604 + ": new version " + pkg.mVersionCode
2605 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002606 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2607 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002608 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 }
2611 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002612 if (updatedPkg != null) {
2613 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2614 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2615 }
2616 // Verify certificates against what was last scanned
2617 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002618 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002619 return null;
2620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 // The apk is forward locked (not public) if its code and resources
2622 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002623 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002625 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002626 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002627
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002628 String codePath = null;
2629 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002630 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2631 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002632 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002633 } else {
2634 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002635 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002636 }
2637 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002638 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002639 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002640 codePath = pkg.mScanPath;
2641 // Set application objects path explicitly.
2642 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002644 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 }
2646
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002647 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2648 String destCodePath, String destResPath) {
2649 pkg.mPath = pkg.mScanPath = destCodePath;
2650 pkg.applicationInfo.sourceDir = destCodePath;
2651 pkg.applicationInfo.publicSourceDir = destResPath;
2652 }
2653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 private static String fixProcessName(String defProcessName,
2655 String processName, int uid) {
2656 if (processName == null) {
2657 return defProcessName;
2658 }
2659 return processName;
2660 }
2661
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002662 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002663 PackageParser.Package pkg) {
2664 if (pkgSetting.signatures.mSignatures != null) {
2665 // Already existing package. Make sure signatures match
2666 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2667 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002668 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002669 + " signatures do not match the previously installed version; ignoring!");
2670 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 return false;
2672 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002673 }
2674 // Check for shared user signatures
2675 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2676 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2677 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2678 Slog.e(TAG, "Package " + pkg.packageName
2679 + " has no signatures that match those in shared user "
2680 + pkgSetting.sharedUser.name + "; ignoring!");
2681 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2682 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 }
2685 return true;
2686 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002687
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002688 public boolean performDexOpt(String packageName) {
2689 if (!mNoDexOpt) {
2690 return false;
2691 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002692
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002693 PackageParser.Package p;
2694 synchronized (mPackages) {
2695 p = mPackages.get(packageName);
2696 if (p == null || p.mDidDexOpt) {
2697 return false;
2698 }
2699 }
2700 synchronized (mInstallLock) {
2701 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2702 }
2703 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002704
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002705 static final int DEX_OPT_SKIPPED = 0;
2706 static final int DEX_OPT_PERFORMED = 1;
2707 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002708
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002709 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2710 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002711 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002712 String path = pkg.mScanPath;
2713 int ret = 0;
2714 try {
2715 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002716 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002717 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002718 pkg.mDidDexOpt = true;
2719 performed = true;
2720 }
2721 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002722 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002723 ret = -1;
2724 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002725 Slog.w(TAG, "IOException reading apk: " + path, e);
2726 ret = -1;
2727 } catch (dalvik.system.StaleDexCacheError e) {
2728 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2729 ret = -1;
2730 } catch (Exception e) {
2731 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002732 ret = -1;
2733 }
2734 if (ret < 0) {
2735 //error from installer
2736 return DEX_OPT_FAILED;
2737 }
2738 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002739
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002740 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2741 }
2742
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002743 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2744 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002745 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002746 + " to " + newPkg.packageName
2747 + ": old package not in system partition");
2748 return false;
2749 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002750 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002751 + " to " + newPkg.packageName
2752 + ": old package still exists");
2753 return false;
2754 }
2755 return true;
2756 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002757
2758 private File getDataPathForPackage(PackageParser.Package pkg) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07002759 return new File(mAppDataDir, pkg.packageName);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002760 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002761
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002762 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2763 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002764 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002765 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2766 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002767 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002768 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002769 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2770 return null;
2771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 mScanningPath = scanFile;
2773 if (pkg == null) {
2774 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2775 return null;
2776 }
2777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2779 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2780 }
2781
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002782 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 synchronized (mPackages) {
2784 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002785 Slog.w(TAG, "*************************************************");
2786 Slog.w(TAG, "Core android package being redefined. Skipping.");
2787 Slog.w(TAG, " file=" + mScanningPath);
2788 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2790 return null;
2791 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 // Set up information for our fall-back user intent resolution
2794 // activity.
2795 mPlatformPackage = pkg;
2796 pkg.mVersionCode = mSdkVersion;
2797 mAndroidApplication = pkg.applicationInfo;
2798 mResolveActivity.applicationInfo = mAndroidApplication;
2799 mResolveActivity.name = ResolverActivity.class.getName();
2800 mResolveActivity.packageName = mAndroidApplication.packageName;
2801 mResolveActivity.processName = mAndroidApplication.processName;
2802 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2803 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2804 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2805 mResolveActivity.exported = true;
2806 mResolveActivity.enabled = true;
2807 mResolveInfo.activityInfo = mResolveActivity;
2808 mResolveInfo.priority = 0;
2809 mResolveInfo.preferredOrder = 0;
2810 mResolveInfo.match = 0;
2811 mResolveComponentName = new ComponentName(
2812 mAndroidApplication.packageName, mResolveActivity.name);
2813 }
2814 }
2815
2816 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002817 TAG, "Scanning package " + pkg.packageName);
2818 if (mPackages.containsKey(pkg.packageName)
2819 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002820 Slog.w(TAG, "*************************************************");
2821 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002823 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2825 return null;
2826 }
2827
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002828 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002829 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2830 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 SharedUserSetting suid = null;
2833 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002834
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002835 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2836 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002837 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002838 pkg.mRealPackage = null;
2839 pkg.mAdoptPermissions = null;
2840 }
2841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 synchronized (mPackages) {
2843 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002844 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2845 if (mTmpSharedLibraries == null ||
2846 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2847 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2848 }
2849 int num = 0;
2850 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2851 for (int i=0; i<N; i++) {
2852 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002854 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002856 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2858 return null;
2859 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002860 mTmpSharedLibraries[num] = file;
2861 num++;
2862 }
2863 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2864 for (int i=0; i<N; i++) {
2865 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2866 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002867 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002868 + " desires unavailable shared library "
2869 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2870 } else {
2871 mTmpSharedLibraries[num] = file;
2872 num++;
2873 }
2874 }
2875 if (num > 0) {
2876 pkg.usesLibraryFiles = new String[num];
2877 System.arraycopy(mTmpSharedLibraries, 0,
2878 pkg.usesLibraryFiles, 0, num);
2879 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002880
Dianne Hackborn49237342009-08-27 20:08:01 -07002881 if (pkg.reqFeatures != null) {
2882 N = pkg.reqFeatures.size();
2883 for (int i=0; i<N; i++) {
2884 FeatureInfo fi = pkg.reqFeatures.get(i);
2885 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2886 // Don't care.
2887 continue;
2888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002889
Dianne Hackborn49237342009-08-27 20:08:01 -07002890 if (fi.name != null) {
2891 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002892 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002893 + " requires unavailable feature "
2894 + fi.name + "; failing!");
2895 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2896 return null;
2897 }
2898 }
2899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 }
2901 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 if (pkg.mSharedUserId != null) {
2904 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2905 pkg.applicationInfo.flags, true);
2906 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002907 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 + " for shared user failed");
2909 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2910 return null;
2911 }
2912 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2913 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2914 + suid.userId + "): packages=" + suid.packages);
2915 }
2916 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002917
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002918 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002919 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002920 Log.w(TAG, "WAITING FOR DEBUGGER");
2921 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002922 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2923 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002924 }
2925 }
2926
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002927 // Check if we are renaming from an original package name.
2928 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002929 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002930 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002931 // This package may need to be renamed to a previously
2932 // installed name. Let's check on that...
2933 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002934 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002935 // This package had originally been installed as the
2936 // original name, and we have already taken care of
2937 // transitioning to the new one. Just update the new
2938 // one to continue using the old name.
2939 realName = pkg.mRealPackage;
2940 if (!pkg.packageName.equals(renamed)) {
2941 // Callers into this function may have already taken
2942 // care of renaming the package; only do it here if
2943 // it is not already done.
2944 pkg.setPackageName(renamed);
2945 }
2946
Dianne Hackbornc1552392010-03-03 16:19:01 -08002947 } else {
2948 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2949 if ((origPackage=mSettings.peekPackageLP(
2950 pkg.mOriginalPackages.get(i))) != null) {
2951 // We do have the package already installed under its
2952 // original name... should we use it?
2953 if (!verifyPackageUpdate(origPackage, pkg)) {
2954 // New package is not compatible with original.
2955 origPackage = null;
2956 continue;
2957 } else if (origPackage.sharedUser != null) {
2958 // Make sure uid is compatible between packages.
2959 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002960 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002961 + " to " + pkg.packageName + ": old uid "
2962 + origPackage.sharedUser.name
2963 + " differs from " + pkg.mSharedUserId);
2964 origPackage = null;
2965 continue;
2966 }
2967 } else {
2968 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2969 + pkg.packageName + " to old name " + origPackage.name);
2970 }
2971 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002972 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002973 }
2974 }
2975 }
2976
2977 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002978 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002979 + " was transferred to another, but its .apk remains");
2980 }
2981
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002982 // Just create the setting, don't add it yet. For already existing packages
2983 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002984 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 destResourceFile, pkg.applicationInfo.flags, true, false);
2986 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002987 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2989 return null;
2990 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002991
2992 if (pkgSetting.origPackage != null) {
2993 // If we are first transitioning from an original package,
2994 // fix up the new package's name now. We need to do this after
2995 // looking up the package under its new name, so getPackageLP
2996 // can take care of fiddling things correctly.
2997 pkg.setPackageName(origPackage.name);
2998
2999 // File a report about this.
3000 String msg = "New package " + pkgSetting.realName
3001 + " renamed to replace old package " + pkgSetting.name;
3002 reportSettingsProblem(Log.WARN, msg);
3003
3004 // Make a note of it.
3005 mTransferedPackages.add(origPackage.name);
3006
3007 // No longer need to retain this.
3008 pkgSetting.origPackage = null;
3009 }
3010
3011 if (realName != null) {
3012 // Make a note of it.
3013 mTransferedPackages.add(pkg.packageName);
3014 }
3015
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003016 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3018 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 pkg.applicationInfo.uid = pkgSetting.userId;
3021 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003022
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003023 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003024 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 return null;
3026 }
3027 // The signature has changed, but this package is in the system
3028 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003029 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 // However... if this package is part of a shared user, but it
3031 // doesn't match the signature of the shared user, let's fail.
3032 // What this means is that you can't change the signatures
3033 // associated with an overall shared user, which doesn't seem all
3034 // that unreasonable.
3035 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003036 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3037 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3038 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3040 return null;
3041 }
3042 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003043 // File a report about this.
3044 String msg = "System package " + pkg.packageName
3045 + " signature changed; retaining data.";
3046 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003048
The Android Open Source Project10592532009-03-18 17:39:46 -07003049 // Verify that this new package doesn't have any content providers
3050 // that conflict with existing packages. Only do this if the
3051 // package isn't already installed, since we don't want to break
3052 // things that are installed.
3053 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3054 int N = pkg.providers.size();
3055 int i;
3056 for (i=0; i<N; i++) {
3057 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003058 if (p.info.authority != null) {
3059 String names[] = p.info.authority.split(";");
3060 for (int j = 0; j < names.length; j++) {
3061 if (mProviders.containsKey(names[j])) {
3062 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003063 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003064 " (in package " + pkg.applicationInfo.packageName +
3065 ") is already used by "
3066 + ((other != null && other.getComponentName() != null)
3067 ? other.getComponentName().getPackageName() : "?"));
3068 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3069 return null;
3070 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003071 }
3072 }
3073 }
3074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 }
3076
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003077 final String pkgName = pkg.packageName;
3078
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003079 if (pkg.mAdoptPermissions != null) {
3080 // This package wants to adopt ownership of permissions from
3081 // another package.
3082 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3083 String origName = pkg.mAdoptPermissions.get(i);
3084 PackageSetting orig = mSettings.peekPackageLP(origName);
3085 if (orig != null) {
3086 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003087 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003088 + origName + " to " + pkg.packageName);
3089 mSettings.transferPermissions(origName, pkg.packageName);
3090 }
3091 }
3092 }
3093 }
3094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 long scanFileTime = scanFile.lastModified();
3096 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3097 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3098 pkg.applicationInfo.processName = fixProcessName(
3099 pkg.applicationInfo.packageName,
3100 pkg.applicationInfo.processName,
3101 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102
3103 File dataPath;
3104 if (mPlatformPackage == pkg) {
3105 // The system package is special.
3106 dataPath = new File (Environment.getDataDirectory(), "system");
3107 pkg.applicationInfo.dataDir = dataPath.getPath();
3108 } else {
3109 // This is a normal package, need to make its data directory.
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003110 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003111
3112 boolean uidError = false;
3113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003114 if (dataPath.exists()) {
3115 mOutPermissions[1] = 0;
3116 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3117 if (mOutPermissions[1] == pkg.applicationInfo.uid
3118 || !Process.supportsProcesses()) {
3119 pkg.applicationInfo.dataDir = dataPath.getPath();
3120 } else {
3121 boolean recovered = false;
3122 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3123 // If this is a system app, we can at least delete its
3124 // current data so the application will still work.
3125 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003126 int ret = mInstaller.remove(pkgName);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003127 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003128 // Old data gone!
3129 String msg = "System package " + pkg.packageName
3130 + " has changed from uid: "
3131 + mOutPermissions[1] + " to "
3132 + pkg.applicationInfo.uid + "; old data erased";
3133 reportSettingsProblem(Log.WARN, msg);
3134 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 // And now re-install the app.
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003137 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 pkg.applicationInfo.uid);
3139 if (ret == -1) {
3140 // Ack should not happen!
3141 msg = "System package " + pkg.packageName
3142 + " could not have data directory re-created after delete.";
3143 reportSettingsProblem(Log.WARN, msg);
3144 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3145 return null;
3146 }
3147 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 if (!recovered) {
3150 mHasSystemUidErrors = true;
3151 }
3152 }
3153 if (!recovered) {
3154 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3155 + pkg.applicationInfo.uid + "/fs_"
3156 + mOutPermissions[1];
3157 String msg = "Package " + pkg.packageName
3158 + " has mismatched uid: "
3159 + mOutPermissions[1] + " on disk, "
3160 + pkg.applicationInfo.uid + " in settings";
3161 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003162 mSettings.mReadMessages.append(msg);
3163 mSettings.mReadMessages.append('\n');
3164 uidError = true;
3165 if (!pkgSetting.uidError) {
3166 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 }
3169 }
3170 }
3171 pkg.applicationInfo.dataDir = dataPath.getPath();
3172 } else {
3173 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3174 Log.v(TAG, "Want this data dir: " + dataPath);
3175 //invoke installer to do the actual installation
3176 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003177 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 pkg.applicationInfo.uid);
3179 if(ret < 0) {
3180 // Error from installer
3181 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3182 return null;
3183 }
3184 } else {
3185 dataPath.mkdirs();
3186 if (dataPath.exists()) {
3187 FileUtils.setPermissions(
3188 dataPath.toString(),
3189 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3190 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3191 }
3192 }
3193 if (dataPath.exists()) {
3194 pkg.applicationInfo.dataDir = dataPath.getPath();
3195 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003196 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 pkg.applicationInfo.dataDir = null;
3198 }
3199 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003200
3201 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 }
3203
3204 // Perform shared library installation and dex validation and
3205 // optimization, if this is not a system app.
3206 if (mInstaller != null) {
3207 String path = scanFile.getPath();
3208 if (scanFileNewer) {
3209 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003210 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3211 if (err != PackageManager.INSTALL_SUCCEEDED) {
3212 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 return null;
3214 }
3215 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003216 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003217
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003218 if ((scanMode&SCAN_NO_DEX) == 0) {
3219 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3221 return null;
3222 }
3223 }
3224 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 if (mFactoryTest && pkg.requestedPermissions.contains(
3227 android.Manifest.permission.FACTORY_TEST)) {
3228 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3229 }
3230
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003231 // Request the ActivityManager to kill the process(only for existing packages)
3232 // so that we do not end up in a confused state while the user is still using the older
3233 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003234 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003235 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003236 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003237 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003240 // We don't expect installation to fail beyond this point,
3241 if ((scanMode&SCAN_MONITOR) != 0) {
3242 mAppDirs.put(pkg.mPath, pkg);
3243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003245 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003247 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003248 // Make sure we don't accidentally delete its data.
3249 mSettings.mPackagesToBeCleaned.remove(pkgName);
3250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 int N = pkg.providers.size();
3252 StringBuilder r = null;
3253 int i;
3254 for (i=0; i<N; i++) {
3255 PackageParser.Provider p = pkg.providers.get(i);
3256 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3257 p.info.processName, pkg.applicationInfo.uid);
3258 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3259 p.info.name), p);
3260 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003261 if (p.info.authority != null) {
3262 String names[] = p.info.authority.split(";");
3263 p.info.authority = null;
3264 for (int j = 0; j < names.length; j++) {
3265 if (j == 1 && p.syncable) {
3266 // We only want the first authority for a provider to possibly be
3267 // syncable, so if we already added this provider using a different
3268 // authority clear the syncable flag. We copy the provider before
3269 // changing it because the mProviders object contains a reference
3270 // to a provider that we don't want to change.
3271 // Only do this for the second authority since the resulting provider
3272 // object can be the same for all future authorities for this provider.
3273 p = new PackageParser.Provider(p);
3274 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003275 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003276 if (!mProviders.containsKey(names[j])) {
3277 mProviders.put(names[j], p);
3278 if (p.info.authority == null) {
3279 p.info.authority = names[j];
3280 } else {
3281 p.info.authority = p.info.authority + ";" + names[j];
3282 }
3283 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3284 Log.d(TAG, "Registered content provider: " + names[j] +
3285 ", className = " + p.info.name +
3286 ", isSyncable = " + p.info.isSyncable);
3287 } else {
3288 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003289 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003290 " (in package " + pkg.applicationInfo.packageName +
3291 "): name already used by "
3292 + ((other != null && other.getComponentName() != null)
3293 ? other.getComponentName().getPackageName() : "?"));
3294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 }
3296 }
3297 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3298 if (r == null) {
3299 r = new StringBuilder(256);
3300 } else {
3301 r.append(' ');
3302 }
3303 r.append(p.info.name);
3304 }
3305 }
3306 if (r != null) {
3307 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3308 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 N = pkg.services.size();
3311 r = null;
3312 for (i=0; i<N; i++) {
3313 PackageParser.Service s = pkg.services.get(i);
3314 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3315 s.info.processName, pkg.applicationInfo.uid);
3316 mServices.addService(s);
3317 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3318 if (r == null) {
3319 r = new StringBuilder(256);
3320 } else {
3321 r.append(' ');
3322 }
3323 r.append(s.info.name);
3324 }
3325 }
3326 if (r != null) {
3327 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 N = pkg.receivers.size();
3331 r = null;
3332 for (i=0; i<N; i++) {
3333 PackageParser.Activity a = pkg.receivers.get(i);
3334 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3335 a.info.processName, pkg.applicationInfo.uid);
3336 mReceivers.addActivity(a, "receiver");
3337 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3338 if (r == null) {
3339 r = new StringBuilder(256);
3340 } else {
3341 r.append(' ');
3342 }
3343 r.append(a.info.name);
3344 }
3345 }
3346 if (r != null) {
3347 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3348 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 N = pkg.activities.size();
3351 r = null;
3352 for (i=0; i<N; i++) {
3353 PackageParser.Activity a = pkg.activities.get(i);
3354 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3355 a.info.processName, pkg.applicationInfo.uid);
3356 mActivities.addActivity(a, "activity");
3357 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3358 if (r == null) {
3359 r = new StringBuilder(256);
3360 } else {
3361 r.append(' ');
3362 }
3363 r.append(a.info.name);
3364 }
3365 }
3366 if (r != null) {
3367 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3368 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 N = pkg.permissionGroups.size();
3371 r = null;
3372 for (i=0; i<N; i++) {
3373 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3374 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3375 if (cur == null) {
3376 mPermissionGroups.put(pg.info.name, pg);
3377 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3378 if (r == null) {
3379 r = new StringBuilder(256);
3380 } else {
3381 r.append(' ');
3382 }
3383 r.append(pg.info.name);
3384 }
3385 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003386 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 + pg.info.packageName + " ignored: original from "
3388 + cur.info.packageName);
3389 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3390 if (r == null) {
3391 r = new StringBuilder(256);
3392 } else {
3393 r.append(' ');
3394 }
3395 r.append("DUP:");
3396 r.append(pg.info.name);
3397 }
3398 }
3399 }
3400 if (r != null) {
3401 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3402 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 N = pkg.permissions.size();
3405 r = null;
3406 for (i=0; i<N; i++) {
3407 PackageParser.Permission p = pkg.permissions.get(i);
3408 HashMap<String, BasePermission> permissionMap =
3409 p.tree ? mSettings.mPermissionTrees
3410 : mSettings.mPermissions;
3411 p.group = mPermissionGroups.get(p.info.group);
3412 if (p.info.group == null || p.group != null) {
3413 BasePermission bp = permissionMap.get(p.info.name);
3414 if (bp == null) {
3415 bp = new BasePermission(p.info.name, p.info.packageName,
3416 BasePermission.TYPE_NORMAL);
3417 permissionMap.put(p.info.name, bp);
3418 }
3419 if (bp.perm == null) {
3420 if (bp.sourcePackage == null
3421 || bp.sourcePackage.equals(p.info.packageName)) {
3422 BasePermission tree = findPermissionTreeLP(p.info.name);
3423 if (tree == null
3424 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003425 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426 bp.perm = p;
3427 bp.uid = pkg.applicationInfo.uid;
3428 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3429 if (r == null) {
3430 r = new StringBuilder(256);
3431 } else {
3432 r.append(' ');
3433 }
3434 r.append(p.info.name);
3435 }
3436 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003437 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 + p.info.packageName + " ignored: base tree "
3439 + tree.name + " is from package "
3440 + tree.sourcePackage);
3441 }
3442 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003443 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 + p.info.packageName + " ignored: original from "
3445 + bp.sourcePackage);
3446 }
3447 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3448 if (r == null) {
3449 r = new StringBuilder(256);
3450 } else {
3451 r.append(' ');
3452 }
3453 r.append("DUP:");
3454 r.append(p.info.name);
3455 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003456 if (bp.perm == p) {
3457 bp.protectionLevel = p.info.protectionLevel;
3458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003459 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003460 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 + p.info.packageName + " ignored: no group "
3462 + p.group);
3463 }
3464 }
3465 if (r != null) {
3466 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 N = pkg.instrumentation.size();
3470 r = null;
3471 for (i=0; i<N; i++) {
3472 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3473 a.info.packageName = pkg.applicationInfo.packageName;
3474 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3475 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3476 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003477 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3479 if (r == null) {
3480 r = new StringBuilder(256);
3481 } else {
3482 r.append(' ');
3483 }
3484 r.append(a.info.name);
3485 }
3486 }
3487 if (r != null) {
3488 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3489 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003490
Dianne Hackborn854060af2009-07-09 18:14:31 -07003491 if (pkg.protectedBroadcasts != null) {
3492 N = pkg.protectedBroadcasts.size();
3493 for (i=0; i<N; i++) {
3494 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3495 }
3496 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 pkgSetting.setTimeStamp(scanFileTime);
3499 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 return pkg;
3502 }
3503
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003504 private void killApplication(String pkgName, int uid) {
3505 // Request the ActivityManager to kill the process(only for existing packages)
3506 // so that we do not end up in a confused state while the user is still using the older
3507 // version of the application while the new one gets installed.
3508 IActivityManager am = ActivityManagerNative.getDefault();
3509 if (am != null) {
3510 try {
3511 am.killApplicationWithUid(pkgName, uid);
3512 } catch (RemoteException e) {
3513 }
3514 }
3515 }
3516
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003517 // The following constants are returned by cachePackageSharedLibsForAbiLI
3518 // to indicate if native shared libraries were found in the package.
3519 // Values are:
3520 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3521 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3522 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3523 // in package (and not installed)
3524 //
3525 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3526 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3527 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003529 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3530 // and automatically copy them to /data/data/<appname>/lib if present.
3531 //
3532 // NOTE: this method may throw an IOException if the library cannot
3533 // be copied to its final destination, e.g. if there isn't enough
3534 // room left on the data partition, or a ZipException if the package
3535 // file is malformed.
3536 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003537 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3538 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003539 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3540 final String apkLib = "lib/";
3541 final int apkLibLen = apkLib.length();
3542 final int cpuAbiLen = cpuAbi.length();
3543 final String libPrefix = "lib";
3544 final int libPrefixLen = libPrefix.length();
3545 final String libSuffix = ".so";
3546 final int libSuffixLen = libSuffix.length();
3547 boolean hasNativeLibraries = false;
3548 boolean installedNativeLibraries = false;
3549
3550 // the minimum length of a valid native shared library of the form
3551 // lib/<something>/lib<name>.so.
3552 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3553
3554 ZipFile zipFile = new ZipFile(scanFile);
3555 Enumeration<ZipEntry> entries =
3556 (Enumeration<ZipEntry>) zipFile.entries();
3557
3558 while (entries.hasMoreElements()) {
3559 ZipEntry entry = entries.nextElement();
3560 // skip directories
3561 if (entry.isDirectory()) {
3562 continue;
3563 }
3564 String entryName = entry.getName();
3565
3566 // check that the entry looks like lib/<something>/lib<name>.so
3567 // here, but don't check the ABI just yet.
3568 //
3569 // - must be sufficiently long
3570 // - must end with libSuffix, i.e. ".so"
3571 // - must start with apkLib, i.e. "lib/"
3572 if (entryName.length() < minEntryLen ||
3573 !entryName.endsWith(libSuffix) ||
3574 !entryName.startsWith(apkLib) ) {
3575 continue;
3576 }
3577
3578 // file name must start with libPrefix, i.e. "lib"
3579 int lastSlash = entryName.lastIndexOf('/');
3580
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003581 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003582 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3583 continue;
3584 }
3585
3586 hasNativeLibraries = true;
3587
3588 // check the cpuAbi now, between lib/ and /lib<name>.so
3589 //
3590 if (lastSlash != apkLibLen + cpuAbiLen ||
3591 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3592 continue;
3593
3594 // extract the library file name, ensure it doesn't contain
3595 // weird characters. we're guaranteed here that it doesn't contain
3596 // a directory separator though.
3597 String libFileName = entryName.substring(lastSlash+1);
3598 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3599 continue;
3600 }
3601
3602 installedNativeLibraries = true;
3603
3604 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3605 File.separator + libFileName;
3606 File sharedLibraryFile = new File(sharedLibraryFilePath);
3607 if (! sharedLibraryFile.exists() ||
3608 sharedLibraryFile.length() != entry.getSize() ||
3609 sharedLibraryFile.lastModified() != entry.getTime()) {
3610 if (Config.LOGD) {
3611 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003613 if (mInstaller == null) {
3614 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003615 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003616 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003617 sharedLibraryFile);
3618 }
3619 }
3620 if (!hasNativeLibraries)
3621 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3622
3623 if (!installedNativeLibraries)
3624 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3625
3626 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3627 }
3628
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003629 // Find the gdbserver executable program in a package at
3630 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3631 //
3632 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3633 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3634 //
3635 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3636 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3637 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3638 final String GDBSERVER = "gdbserver";
3639 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3640
3641 ZipFile zipFile = new ZipFile(scanFile);
3642 Enumeration<ZipEntry> entries =
3643 (Enumeration<ZipEntry>) zipFile.entries();
3644
3645 while (entries.hasMoreElements()) {
3646 ZipEntry entry = entries.nextElement();
3647 // skip directories
3648 if (entry.isDirectory()) {
3649 continue;
3650 }
3651 String entryName = entry.getName();
3652
3653 if (!entryName.equals(apkGdbServerPath)) {
3654 continue;
3655 }
3656
3657 String installGdbServerPath = installGdbServerDir.getPath() +
3658 "/" + GDBSERVER;
3659 File installGdbServerFile = new File(installGdbServerPath);
3660 if (! installGdbServerFile.exists() ||
3661 installGdbServerFile.length() != entry.getSize() ||
3662 installGdbServerFile.lastModified() != entry.getTime()) {
3663 if (Config.LOGD) {
3664 Log.d(TAG, "Caching gdbserver " + entry.getName());
3665 }
3666 if (mInstaller == null) {
3667 installGdbServerDir.mkdir();
3668 }
3669 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3670 installGdbServerFile);
3671 }
3672 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3673 }
3674 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3675 }
3676
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003677 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3678 // and copy them to /data/data/<appname>/lib.
3679 //
3680 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3681 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3682 // one if ro.product.cpu.abi2 is defined.
3683 //
3684 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3685 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003686 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003687 try {
3688 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3689
3690 // some architectures are capable of supporting several CPU ABIs
3691 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3692 // this is indicated by the definition of the ro.product.cpu.abi2
3693 // system property.
3694 //
3695 // only scan the package twice in case of ABI mismatch
3696 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003697 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003698 if (cpuAbi2 != null) {
3699 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003700 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003701
3702 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003703 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003704 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003706
3707 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3708 cpuAbi = cpuAbi2;
3709 }
3710 }
3711
3712 // for debuggable packages, also extract gdbserver from lib/<abi>
3713 // into /data/data/<appname>/lib too.
3714 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3715 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3716 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3717 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3718 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003721 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003722 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003723 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003725 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003726 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003727 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003728 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 }
3730
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003731 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003733 File binaryDir,
3734 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 InputStream inputStream = zipFile.getInputStream(entry);
3736 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003737 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003739 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 // now need to be left as world readable and owned by the system.
3741 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3742 ! tempFile.setLastModified(entry.getTime()) ||
3743 FileUtils.setPermissions(tempFilePath,
3744 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003745 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003747 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 // Failed to properly write file.
3749 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003750 throw new IOException("Couldn't create cached binary "
3751 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 }
3753 } finally {
3754 inputStream.close();
3755 }
3756 }
3757
3758 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3759 if (chatty && Config.LOGD) Log.d(
3760 TAG, "Removing package " + pkg.applicationInfo.packageName );
3761
3762 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 mPackages.remove(pkg.applicationInfo.packageName);
3766 if (pkg.mPath != null) {
3767 mAppDirs.remove(pkg.mPath);
3768 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 PackageSetting ps = (PackageSetting)pkg.mExtras;
3771 if (ps != null && ps.sharedUser != null) {
3772 // XXX don't do this until the data is removed.
3773 if (false) {
3774 ps.sharedUser.packages.remove(ps);
3775 if (ps.sharedUser.packages.size() == 0) {
3776 // Remove.
3777 }
3778 }
3779 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 int N = pkg.providers.size();
3782 StringBuilder r = null;
3783 int i;
3784 for (i=0; i<N; i++) {
3785 PackageParser.Provider p = pkg.providers.get(i);
3786 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3787 p.info.name));
3788 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 /* The is another ContentProvider with this authority when
3791 * this app was installed so this authority is null,
3792 * Ignore it as we don't have to unregister the provider.
3793 */
3794 continue;
3795 }
3796 String names[] = p.info.authority.split(";");
3797 for (int j = 0; j < names.length; j++) {
3798 if (mProviders.get(names[j]) == p) {
3799 mProviders.remove(names[j]);
3800 if (chatty && Config.LOGD) Log.d(
3801 TAG, "Unregistered content provider: " + names[j] +
3802 ", className = " + p.info.name +
3803 ", isSyncable = " + p.info.isSyncable);
3804 }
3805 }
3806 if (chatty) {
3807 if (r == null) {
3808 r = new StringBuilder(256);
3809 } else {
3810 r.append(' ');
3811 }
3812 r.append(p.info.name);
3813 }
3814 }
3815 if (r != null) {
3816 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3817 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819 N = pkg.services.size();
3820 r = null;
3821 for (i=0; i<N; i++) {
3822 PackageParser.Service s = pkg.services.get(i);
3823 mServices.removeService(s);
3824 if (chatty) {
3825 if (r == null) {
3826 r = new StringBuilder(256);
3827 } else {
3828 r.append(' ');
3829 }
3830 r.append(s.info.name);
3831 }
3832 }
3833 if (r != null) {
3834 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 N = pkg.receivers.size();
3838 r = null;
3839 for (i=0; i<N; i++) {
3840 PackageParser.Activity a = pkg.receivers.get(i);
3841 mReceivers.removeActivity(a, "receiver");
3842 if (chatty) {
3843 if (r == null) {
3844 r = new StringBuilder(256);
3845 } else {
3846 r.append(' ');
3847 }
3848 r.append(a.info.name);
3849 }
3850 }
3851 if (r != null) {
3852 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3853 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 N = pkg.activities.size();
3856 r = null;
3857 for (i=0; i<N; i++) {
3858 PackageParser.Activity a = pkg.activities.get(i);
3859 mActivities.removeActivity(a, "activity");
3860 if (chatty) {
3861 if (r == null) {
3862 r = new StringBuilder(256);
3863 } else {
3864 r.append(' ');
3865 }
3866 r.append(a.info.name);
3867 }
3868 }
3869 if (r != null) {
3870 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 N = pkg.permissions.size();
3874 r = null;
3875 for (i=0; i<N; i++) {
3876 PackageParser.Permission p = pkg.permissions.get(i);
3877 boolean tree = false;
3878 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3879 if (bp == null) {
3880 tree = true;
3881 bp = mSettings.mPermissionTrees.get(p.info.name);
3882 }
3883 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003884 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 if (chatty) {
3886 if (r == null) {
3887 r = new StringBuilder(256);
3888 } else {
3889 r.append(' ');
3890 }
3891 r.append(p.info.name);
3892 }
3893 }
3894 }
3895 if (r != null) {
3896 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3897 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 N = pkg.instrumentation.size();
3900 r = null;
3901 for (i=0; i<N; i++) {
3902 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003903 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 if (chatty) {
3905 if (r == null) {
3906 r = new StringBuilder(256);
3907 } else {
3908 r.append(' ');
3909 }
3910 r.append(a.info.name);
3911 }
3912 }
3913 if (r != null) {
3914 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3915 }
3916 }
3917 }
3918
3919 private static final boolean isPackageFilename(String name) {
3920 return name != null && name.endsWith(".apk");
3921 }
3922
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003923 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3924 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3925 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3926 return true;
3927 }
3928 }
3929 return false;
3930 }
3931
3932 private void updatePermissionsLP(String changingPkg,
3933 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 // Make sure there are no dangling permission trees.
3935 Iterator<BasePermission> it = mSettings.mPermissionTrees
3936 .values().iterator();
3937 while (it.hasNext()) {
3938 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003939 if (bp.packageSetting == null) {
3940 // We may not yet have parsed the package, so just see if
3941 // we still know about its settings.
3942 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3943 }
3944 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003945 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 + " from package " + bp.sourcePackage);
3947 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003948 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3949 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3950 Slog.i(TAG, "Removing old permission tree: " + bp.name
3951 + " from package " + bp.sourcePackage);
3952 grantPermissions = true;
3953 it.remove();
3954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 }
3956 }
3957
3958 // Make sure all dynamic permissions have been assigned to a package,
3959 // and make sure there are no dangling permissions.
3960 it = mSettings.mPermissions.values().iterator();
3961 while (it.hasNext()) {
3962 BasePermission bp = it.next();
3963 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3964 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3965 + bp.name + " pkg=" + bp.sourcePackage
3966 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003967 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 BasePermission tree = findPermissionTreeLP(bp.name);
3969 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003970 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971 bp.perm = new PackageParser.Permission(tree.perm.owner,
3972 new PermissionInfo(bp.pendingInfo));
3973 bp.perm.info.packageName = tree.perm.info.packageName;
3974 bp.perm.info.name = bp.name;
3975 bp.uid = tree.uid;
3976 }
3977 }
3978 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003979 if (bp.packageSetting == null) {
3980 // We may not yet have parsed the package, so just see if
3981 // we still know about its settings.
3982 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3983 }
3984 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003985 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 + " from package " + bp.sourcePackage);
3987 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003988 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3989 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3990 Slog.i(TAG, "Removing old permission: " + bp.name
3991 + " from package " + bp.sourcePackage);
3992 grantPermissions = true;
3993 it.remove();
3994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 }
3996 }
3997
3998 // Now update the permissions for all packages, in particular
3999 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004000 if (grantPermissions) {
4001 for (PackageParser.Package pkg : mPackages.values()) {
4002 if (pkg != pkgInfo) {
4003 grantPermissionsLP(pkg, false);
4004 }
4005 }
4006 }
4007
4008 if (pkgInfo != null) {
4009 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 }
4011 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
4014 final PackageSetting ps = (PackageSetting)pkg.mExtras;
4015 if (ps == null) {
4016 return;
4017 }
4018 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004019 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 if (replace) {
4022 ps.permissionsFixed = false;
4023 if (gp == ps) {
4024 gp.grantedPermissions.clear();
4025 gp.gids = mGlobalGids;
4026 }
4027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 if (gp.gids == null) {
4030 gp.gids = mGlobalGids;
4031 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 final int N = pkg.requestedPermissions.size();
4034 for (int i=0; i<N; i++) {
4035 String name = pkg.requestedPermissions.get(i);
4036 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037 if (false) {
4038 if (gp != ps) {
4039 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004040 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 }
4042 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004043 if (bp != null && bp.packageSetting != null) {
4044 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004046 boolean allowedSig = false;
4047 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4048 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004050 } else if (bp.packageSetting == null) {
4051 // This permission is invalid; skip it.
4052 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004053 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4054 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4055 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004057 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004059 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4061 // For updated system applications, the signatureOrSystem permission
4062 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004063 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4065 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4066 if(sysPs.grantedPermissions.contains(perm)) {
4067 allowed = true;
4068 } else {
4069 allowed = false;
4070 }
4071 } else {
4072 allowed = true;
4073 }
4074 }
4075 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004076 if (allowed) {
4077 allowedSig = true;
4078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079 } else {
4080 allowed = false;
4081 }
4082 if (false) {
4083 if (gp != ps) {
4084 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4085 }
4086 }
4087 if (allowed) {
4088 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4089 && ps.permissionsFixed) {
4090 // If this is an existing, non-system package, then
4091 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004092 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004094 // Except... if this is a permission that was added
4095 // to the platform (note: need to only do this when
4096 // updating the platform).
4097 final int NP = PackageParser.NEW_PERMISSIONS.length;
4098 for (int ip=0; ip<NP; ip++) {
4099 final PackageParser.NewPermissionInfo npi
4100 = PackageParser.NEW_PERMISSIONS[ip];
4101 if (npi.name.equals(perm)
4102 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4103 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004104 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004105 + pkg.packageName);
4106 break;
4107 }
4108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 }
4110 }
4111 if (allowed) {
4112 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004113 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 gp.grantedPermissions.add(perm);
4115 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004116 } else if (!ps.haveGids) {
4117 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 }
4119 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004120 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 + " to package " + pkg.packageName
4122 + " because it was previously installed without");
4123 }
4124 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004125 if (gp.grantedPermissions.remove(perm)) {
4126 changedPermission = true;
4127 gp.gids = removeInts(gp.gids, bp.gids);
4128 Slog.i(TAG, "Un-granting permission " + perm
4129 + " from package " + pkg.packageName
4130 + " (protectionLevel=" + bp.protectionLevel
4131 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4132 + ")");
4133 } else {
4134 Slog.w(TAG, "Not granting permission " + perm
4135 + " to package " + pkg.packageName
4136 + " (protectionLevel=" + bp.protectionLevel
4137 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4138 + ")");
4139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 }
4141 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004142 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 + " in package " + pkg.packageName);
4144 }
4145 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004146
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004147 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004148 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4149 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 // This is the first that we have heard about this package, so the
4151 // permissions we have now selected are fixed until explicitly
4152 // changed.
4153 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004155 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004158 private final class ActivityIntentResolver
4159 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004160 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004161 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004162 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163 }
4164
Mihai Preda074edef2009-05-18 17:13:31 +02004165 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004167 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4169 }
4170
Mihai Predaeae850c2009-05-13 10:13:48 +02004171 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4172 ArrayList<PackageParser.Activity> packageActivities) {
4173 if (packageActivities == null) {
4174 return null;
4175 }
4176 mFlags = flags;
4177 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4178 int N = packageActivities.size();
4179 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4180 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004181
4182 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004183 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004184 intentFilters = packageActivities.get(i).intents;
4185 if (intentFilters != null && intentFilters.size() > 0) {
4186 listCut.add(intentFilters);
4187 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004188 }
4189 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4190 }
4191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004193 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 if (SHOW_INFO || Config.LOGV) Log.v(
4195 TAG, " " + type + " " +
4196 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4197 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4198 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004199 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4201 if (SHOW_INFO || Config.LOGV) {
4202 Log.v(TAG, " IntentFilter:");
4203 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4204 }
4205 if (!intent.debugCheck()) {
4206 Log.w(TAG, "==> For Activity " + a.info.name);
4207 }
4208 addFilter(intent);
4209 }
4210 }
4211
4212 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004213 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 if (SHOW_INFO || Config.LOGV) Log.v(
4215 TAG, " " + type + " " +
4216 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4217 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4218 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004219 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004220 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4221 if (SHOW_INFO || Config.LOGV) {
4222 Log.v(TAG, " IntentFilter:");
4223 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4224 }
4225 removeFilter(intent);
4226 }
4227 }
4228
4229 @Override
4230 protected boolean allowFilterResult(
4231 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4232 ActivityInfo filterAi = filter.activity.info;
4233 for (int i=dest.size()-1; i>=0; i--) {
4234 ActivityInfo destAi = dest.get(i).activityInfo;
4235 if (destAi.name == filterAi.name
4236 && destAi.packageName == filterAi.packageName) {
4237 return false;
4238 }
4239 }
4240 return true;
4241 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004244 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4245 return info.activity.owner.packageName;
4246 }
4247
4248 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4250 int match) {
4251 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4252 return null;
4253 }
4254 final PackageParser.Activity activity = info.activity;
4255 if (mSafeMode && (activity.info.applicationInfo.flags
4256 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4257 return null;
4258 }
4259 final ResolveInfo res = new ResolveInfo();
4260 res.activityInfo = PackageParser.generateActivityInfo(activity,
4261 mFlags);
4262 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4263 res.filter = info;
4264 }
4265 res.priority = info.getPriority();
4266 res.preferredOrder = activity.owner.mPreferredOrder;
4267 //System.out.println("Result: " + res.activityInfo.className +
4268 // " = " + res.priority);
4269 res.match = match;
4270 res.isDefault = info.hasDefault;
4271 res.labelRes = info.labelRes;
4272 res.nonLocalizedLabel = info.nonLocalizedLabel;
4273 res.icon = info.icon;
4274 return res;
4275 }
4276
4277 @Override
4278 protected void sortResults(List<ResolveInfo> results) {
4279 Collections.sort(results, mResolvePrioritySorter);
4280 }
4281
4282 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004283 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004285 out.print(prefix); out.print(
4286 Integer.toHexString(System.identityHashCode(filter.activity)));
4287 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004288 out.print(filter.activity.getComponentShortName());
4289 out.print(" filter ");
4290 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 }
4292
4293// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4294// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4295// final List<ResolveInfo> retList = Lists.newArrayList();
4296// while (i.hasNext()) {
4297// final ResolveInfo resolveInfo = i.next();
4298// if (isEnabledLP(resolveInfo.activityInfo)) {
4299// retList.add(resolveInfo);
4300// }
4301// }
4302// return retList;
4303// }
4304
4305 // Keys are String (activity class name), values are Activity.
4306 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4307 = new HashMap<ComponentName, PackageParser.Activity>();
4308 private int mFlags;
4309 }
4310
4311 private final class ServiceIntentResolver
4312 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004313 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004314 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004315 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 }
4317
Mihai Preda074edef2009-05-18 17:13:31 +02004318 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004320 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4322 }
4323
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004324 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4325 ArrayList<PackageParser.Service> packageServices) {
4326 if (packageServices == null) {
4327 return null;
4328 }
4329 mFlags = flags;
4330 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4331 int N = packageServices.size();
4332 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4333 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4334
4335 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4336 for (int i = 0; i < N; ++i) {
4337 intentFilters = packageServices.get(i).intents;
4338 if (intentFilters != null && intentFilters.size() > 0) {
4339 listCut.add(intentFilters);
4340 }
4341 }
4342 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4343 }
4344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004346 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 if (SHOW_INFO || Config.LOGV) Log.v(
4348 TAG, " " + (s.info.nonLocalizedLabel != null
4349 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4350 if (SHOW_INFO || Config.LOGV) Log.v(
4351 TAG, " Class=" + s.info.name);
4352 int NI = s.intents.size();
4353 int j;
4354 for (j=0; j<NI; j++) {
4355 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4356 if (SHOW_INFO || Config.LOGV) {
4357 Log.v(TAG, " IntentFilter:");
4358 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4359 }
4360 if (!intent.debugCheck()) {
4361 Log.w(TAG, "==> For Service " + s.info.name);
4362 }
4363 addFilter(intent);
4364 }
4365 }
4366
4367 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004368 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 if (SHOW_INFO || Config.LOGV) Log.v(
4370 TAG, " " + (s.info.nonLocalizedLabel != null
4371 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4372 if (SHOW_INFO || Config.LOGV) Log.v(
4373 TAG, " Class=" + s.info.name);
4374 int NI = s.intents.size();
4375 int j;
4376 for (j=0; j<NI; j++) {
4377 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4378 if (SHOW_INFO || Config.LOGV) {
4379 Log.v(TAG, " IntentFilter:");
4380 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4381 }
4382 removeFilter(intent);
4383 }
4384 }
4385
4386 @Override
4387 protected boolean allowFilterResult(
4388 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4389 ServiceInfo filterSi = filter.service.info;
4390 for (int i=dest.size()-1; i>=0; i--) {
4391 ServiceInfo destAi = dest.get(i).serviceInfo;
4392 if (destAi.name == filterSi.name
4393 && destAi.packageName == filterSi.packageName) {
4394 return false;
4395 }
4396 }
4397 return true;
4398 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004401 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4402 return info.service.owner.packageName;
4403 }
4404
4405 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004406 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4407 int match) {
4408 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4409 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4410 return null;
4411 }
4412 final PackageParser.Service service = info.service;
4413 if (mSafeMode && (service.info.applicationInfo.flags
4414 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4415 return null;
4416 }
4417 final ResolveInfo res = new ResolveInfo();
4418 res.serviceInfo = PackageParser.generateServiceInfo(service,
4419 mFlags);
4420 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4421 res.filter = filter;
4422 }
4423 res.priority = info.getPriority();
4424 res.preferredOrder = service.owner.mPreferredOrder;
4425 //System.out.println("Result: " + res.activityInfo.className +
4426 // " = " + res.priority);
4427 res.match = match;
4428 res.isDefault = info.hasDefault;
4429 res.labelRes = info.labelRes;
4430 res.nonLocalizedLabel = info.nonLocalizedLabel;
4431 res.icon = info.icon;
4432 return res;
4433 }
4434
4435 @Override
4436 protected void sortResults(List<ResolveInfo> results) {
4437 Collections.sort(results, mResolvePrioritySorter);
4438 }
4439
4440 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004441 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004442 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004443 out.print(prefix); out.print(
4444 Integer.toHexString(System.identityHashCode(filter.service)));
4445 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004446 out.print(filter.service.getComponentShortName());
4447 out.print(" filter ");
4448 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004449 }
4450
4451// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4452// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4453// final List<ResolveInfo> retList = Lists.newArrayList();
4454// while (i.hasNext()) {
4455// final ResolveInfo resolveInfo = (ResolveInfo) i;
4456// if (isEnabledLP(resolveInfo.serviceInfo)) {
4457// retList.add(resolveInfo);
4458// }
4459// }
4460// return retList;
4461// }
4462
4463 // Keys are String (activity class name), values are Activity.
4464 private final HashMap<ComponentName, PackageParser.Service> mServices
4465 = new HashMap<ComponentName, PackageParser.Service>();
4466 private int mFlags;
4467 };
4468
4469 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4470 new Comparator<ResolveInfo>() {
4471 public int compare(ResolveInfo r1, ResolveInfo r2) {
4472 int v1 = r1.priority;
4473 int v2 = r2.priority;
4474 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4475 if (v1 != v2) {
4476 return (v1 > v2) ? -1 : 1;
4477 }
4478 v1 = r1.preferredOrder;
4479 v2 = r2.preferredOrder;
4480 if (v1 != v2) {
4481 return (v1 > v2) ? -1 : 1;
4482 }
4483 if (r1.isDefault != r2.isDefault) {
4484 return r1.isDefault ? -1 : 1;
4485 }
4486 v1 = r1.match;
4487 v2 = r2.match;
4488 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4489 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4490 }
4491 };
4492
4493 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4494 new Comparator<ProviderInfo>() {
4495 public int compare(ProviderInfo p1, ProviderInfo p2) {
4496 final int v1 = p1.initOrder;
4497 final int v2 = p2.initOrder;
4498 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4499 }
4500 };
4501
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004502 private static final void sendPackageBroadcast(String action, String pkg,
4503 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 IActivityManager am = ActivityManagerNative.getDefault();
4505 if (am != null) {
4506 try {
4507 final Intent intent = new Intent(action,
4508 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4509 if (extras != null) {
4510 intent.putExtras(extras);
4511 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004512 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004513 am.broadcastIntent(null, intent, null, finishedReceiver,
4514 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004515 } catch (RemoteException ex) {
4516 }
4517 }
4518 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004519
4520 public String nextPackageToClean(String lastPackage) {
4521 synchronized (mPackages) {
4522 if (!mMediaMounted) {
4523 // If the external storage is no longer mounted at this point,
4524 // the caller may not have been able to delete all of this
4525 // packages files and can not delete any more. Bail.
4526 return null;
4527 }
4528 if (lastPackage != null) {
4529 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4530 }
4531 return mSettings.mPackagesToBeCleaned.size() > 0
4532 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4533 }
4534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004536 void schedulePackageCleaning(String packageName) {
4537 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4538 }
4539
4540 void startCleaningPackages() {
4541 synchronized (mPackages) {
4542 if (!mMediaMounted) {
4543 return;
4544 }
4545 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4546 return;
4547 }
4548 }
4549 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4550 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4551 IActivityManager am = ActivityManagerNative.getDefault();
4552 if (am != null) {
4553 try {
4554 am.startService(null, intent, null);
4555 } catch (RemoteException e) {
4556 }
4557 }
4558 }
4559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004560 private final class AppDirObserver extends FileObserver {
4561 public AppDirObserver(String path, int mask, boolean isrom) {
4562 super(path, mask);
4563 mRootDir = path;
4564 mIsRom = isrom;
4565 }
4566
4567 public void onEvent(int event, String path) {
4568 String removedPackage = null;
4569 int removedUid = -1;
4570 String addedPackage = null;
4571 int addedUid = -1;
4572
4573 synchronized (mInstallLock) {
4574 String fullPathStr = null;
4575 File fullPath = null;
4576 if (path != null) {
4577 fullPath = new File(mRootDir, path);
4578 fullPathStr = fullPath.getPath();
4579 }
4580
4581 if (Config.LOGV) Log.v(
4582 TAG, "File " + fullPathStr + " changed: "
4583 + Integer.toHexString(event));
4584
4585 if (!isPackageFilename(path)) {
4586 if (Config.LOGV) Log.v(
4587 TAG, "Ignoring change of non-package file: " + fullPathStr);
4588 return;
4589 }
4590
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004591 // Ignore packages that are being installed or
4592 // have just been installed.
4593 if (ignoreCodePath(fullPathStr)) {
4594 return;
4595 }
4596 PackageParser.Package p = null;
4597 synchronized (mPackages) {
4598 p = mAppDirs.get(fullPathStr);
4599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004600 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004601 if (p != null) {
4602 removePackageLI(p, true);
4603 removedPackage = p.applicationInfo.packageName;
4604 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 }
4606 }
4607
4608 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004609 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004610 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004611 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4612 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613 PackageParser.PARSE_CHATTY |
4614 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004615 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 if (p != null) {
4617 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004618 updatePermissionsLP(p.packageName, p,
4619 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004620 }
4621 addedPackage = p.applicationInfo.packageName;
4622 addedUid = p.applicationInfo.uid;
4623 }
4624 }
4625 }
4626
4627 synchronized (mPackages) {
4628 mSettings.writeLP();
4629 }
4630 }
4631
4632 if (removedPackage != null) {
4633 Bundle extras = new Bundle(1);
4634 extras.putInt(Intent.EXTRA_UID, removedUid);
4635 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004636 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4637 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004638 }
4639 if (addedPackage != null) {
4640 Bundle extras = new Bundle(1);
4641 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004642 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4643 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 }
4645 }
4646
4647 private final String mRootDir;
4648 private final boolean mIsRom;
4649 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 /* Called when a downloaded package installation has been confirmed by the user */
4652 public void installPackage(
4653 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004654 installPackage(packageURI, observer, flags, null);
4655 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004656
Jacek Surazski65e13172009-04-28 15:26:38 +02004657 /* Called when a downloaded package installation has been confirmed by the user */
4658 public void installPackage(
4659 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4660 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004661 mContext.enforceCallingOrSelfPermission(
4662 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004663
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004664 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004665 msg.obj = new InstallParams(packageURI, observer, flags,
4666 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004667 mHandler.sendMessage(msg);
4668 }
4669
Christopher Tate1bb69062010-02-19 17:02:12 -08004670 public void finishPackageInstall(int token) {
4671 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4672 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4673 mHandler.sendMessage(msg);
4674 }
4675
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004676 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677 // Queue up an async operation since the package installation may take a little while.
4678 mHandler.post(new Runnable() {
4679 public void run() {
4680 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004681 // Result object to be returned
4682 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004683 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004684 res.uid = -1;
4685 res.pkg = null;
4686 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004687 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004688 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004689 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004690 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004691 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004692 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004693 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004694
4695 // A restore should be performed at this point if (a) the install
4696 // succeeded, (b) the operation is not an update, and (c) the new
4697 // package has a backupAgent defined.
4698 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004699 boolean doRestore = (!update
4700 && res.pkg != null
4701 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004702
4703 // Set up the post-install work request bookkeeping. This will be used
4704 // and cleaned up by the post-install event handling regardless of whether
4705 // there's a restore pass performed. Token values are >= 1.
4706 int token;
4707 if (mNextInstallToken < 0) mNextInstallToken = 1;
4708 token = mNextInstallToken++;
4709
4710 PostInstallData data = new PostInstallData(args, res);
4711 mRunningInstalls.put(token, data);
4712 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4713
4714 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4715 // Pass responsibility to the Backup Manager. It will perform a
4716 // restore if appropriate, then pass responsibility back to the
4717 // Package Manager to run the post-install observer callbacks
4718 // and broadcasts.
4719 IBackupManager bm = IBackupManager.Stub.asInterface(
4720 ServiceManager.getService(Context.BACKUP_SERVICE));
4721 if (bm != null) {
4722 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4723 + " to BM for possible restore");
4724 try {
4725 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4726 } catch (RemoteException e) {
4727 // can't happen; the backup manager is local
4728 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004729 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004730 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004731 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004732 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004733 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004734 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004736 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004737
4738 if (!doRestore) {
4739 // No restore possible, or the Backup Manager was mysteriously not
4740 // available -- just fire the post-install work request directly.
4741 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4742 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4743 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745 }
4746 });
4747 }
4748
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004749 abstract class HandlerParams {
4750 final static int MAX_RETRIES = 4;
4751 int retry = 0;
4752 final void startCopy() {
4753 try {
4754 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4755 retry++;
4756 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004757 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004758 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4759 handleServiceError();
4760 return;
4761 } else {
4762 handleStartCopy();
4763 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4764 mHandler.sendEmptyMessage(MCS_UNBIND);
4765 }
4766 } catch (RemoteException e) {
4767 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4768 mHandler.sendEmptyMessage(MCS_RECONNECT);
4769 }
4770 handleReturnCode();
4771 }
4772
4773 final void serviceError() {
4774 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4775 handleServiceError();
4776 handleReturnCode();
4777 }
4778 abstract void handleStartCopy() throws RemoteException;
4779 abstract void handleServiceError();
4780 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004781 }
4782
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004783 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004784 final IPackageInstallObserver observer;
4785 int flags;
4786 final Uri packageURI;
4787 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004788 private InstallArgs mArgs;
4789 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004790 InstallParams(Uri packageURI,
4791 IPackageInstallObserver observer, int flags,
4792 String installerPackageName) {
4793 this.packageURI = packageURI;
4794 this.flags = flags;
4795 this.observer = observer;
4796 this.installerPackageName = installerPackageName;
4797 }
4798
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004799 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4800 String packageName = pkgLite.packageName;
4801 int installLocation = pkgLite.installLocation;
4802 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4803 synchronized (mPackages) {
4804 PackageParser.Package pkg = mPackages.get(packageName);
4805 if (pkg != null) {
4806 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4807 // Check for updated system application.
4808 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4809 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004810 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004811 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4812 }
4813 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4814 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004815 if (onSd) {
4816 // Install flag overrides everything.
4817 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4818 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004819 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004820 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4821 // Application explicitly specified internal.
4822 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4823 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4824 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004825 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004826 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004827 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4828 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4829 }
4830 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004831 }
4832 }
4833 } else {
4834 // Invalid install. Return error code
4835 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4836 }
4837 }
4838 }
4839 // All the special cases have been taken care of.
4840 // Return result based on recommended install location.
4841 if (onSd) {
4842 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4843 }
4844 return pkgLite.recommendedInstallLocation;
4845 }
4846
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004847 /*
4848 * Invoke remote method to get package information and install
4849 * location values. Override install location based on default
4850 * policy if needed and then create install arguments based
4851 * on the install location.
4852 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004853 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004854 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004855 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4856 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004857 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4858 if (onInt && onSd) {
4859 // Check if both bits are set.
4860 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4861 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4862 } else if (fwdLocked && onSd) {
4863 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004864 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004865 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004866 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004867 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004868 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004869 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004870 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4871 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4872 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4873 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4874 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004875 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4876 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4877 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004878 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4879 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004880 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004881 // Override with defaults if needed.
4882 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004883 if (!onSd && !onInt) {
4884 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004885 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4886 // Set the flag to install on external media.
4887 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004888 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004889 } else {
4890 // Make sure the flag for installing on external
4891 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004892 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004893 flags &= ~PackageManager.INSTALL_EXTERNAL;
4894 }
4895 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004896 }
4897 }
4898 // Create the file args now.
4899 mArgs = createInstallArgs(this);
4900 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4901 // Create copy only if we are not in an erroneous state.
4902 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004903 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004904 }
4905 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004906 }
4907
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004908 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004909 void handleReturnCode() {
4910 processPendingInstall(mArgs, mRet);
4911 }
4912
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004913 @Override
4914 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004915 mArgs = createInstallArgs(this);
4916 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004917 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004918 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004919
4920 /*
4921 * Utility class used in movePackage api.
4922 * srcArgs and targetArgs are not set for invalid flags and make
4923 * sure to do null checks when invoking methods on them.
4924 * We probably want to return ErrorPrams for both failed installs
4925 * and moves.
4926 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004927 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004928 final IPackageMoveObserver observer;
4929 final int flags;
4930 final String packageName;
4931 final InstallArgs srcArgs;
4932 final InstallArgs targetArgs;
4933 int mRet;
4934 MoveParams(InstallArgs srcArgs,
4935 IPackageMoveObserver observer,
4936 int flags, String packageName) {
4937 this.srcArgs = srcArgs;
4938 this.observer = observer;
4939 this.flags = flags;
4940 this.packageName = packageName;
4941 if (srcArgs != null) {
4942 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4943 targetArgs = createInstallArgs(packageUri, flags, packageName);
4944 } else {
4945 targetArgs = null;
4946 }
4947 }
4948
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004949 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004950 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4951 // Check for storage space on target medium
4952 if (!targetArgs.checkFreeStorage(mContainerService)) {
4953 Log.w(TAG, "Insufficient storage to install");
4954 return;
4955 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004956 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004957 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004958 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004959 if (DEBUG_SD_INSTALL) {
4960 StringBuilder builder = new StringBuilder();
4961 if (srcArgs != null) {
4962 builder.append("src: ");
4963 builder.append(srcArgs.getCodePath());
4964 }
4965 if (targetArgs != null) {
4966 builder.append(" target : ");
4967 builder.append(targetArgs.getCodePath());
4968 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004969 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004970 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004971 }
4972
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004973 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004974 void handleReturnCode() {
4975 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004976 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4977 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4978 currentStatus = PackageManager.MOVE_SUCCEEDED;
4979 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4980 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4981 }
4982 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004983 }
4984
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004985 @Override
4986 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004987 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004988 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004989 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004990
4991 private InstallArgs createInstallArgs(InstallParams params) {
4992 if (installOnSd(params.flags)) {
4993 return new SdInstallArgs(params);
4994 } else {
4995 return new FileInstallArgs(params);
4996 }
4997 }
4998
4999 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
5000 if (installOnSd(flags)) {
5001 return new SdInstallArgs(fullCodePath, fullResourcePath);
5002 } else {
5003 return new FileInstallArgs(fullCodePath, fullResourcePath);
5004 }
5005 }
5006
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005007 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
5008 if (installOnSd(flags)) {
5009 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5010 return new SdInstallArgs(packageURI, cid);
5011 } else {
5012 return new FileInstallArgs(packageURI, pkgName);
5013 }
5014 }
5015
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005016 static abstract class InstallArgs {
5017 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005018 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005019 final int flags;
5020 final Uri packageURI;
5021 final String installerPackageName;
5022
5023 InstallArgs(Uri packageURI,
5024 IPackageInstallObserver observer, int flags,
5025 String installerPackageName) {
5026 this.packageURI = packageURI;
5027 this.flags = flags;
5028 this.observer = observer;
5029 this.installerPackageName = installerPackageName;
5030 }
5031
5032 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005033 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005034 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005035 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005036 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005037 abstract String getCodePath();
5038 abstract String getResourcePath();
5039 // Need installer lock especially for dex file removal.
5040 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005041 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005042 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005043 }
5044
5045 class FileInstallArgs extends InstallArgs {
5046 File installDir;
5047 String codeFileName;
5048 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005049 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005050
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005051 FileInstallArgs(InstallParams params) {
5052 super(params.packageURI, params.observer,
5053 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005054 }
5055
5056 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5057 super(null, null, 0, null);
5058 File codeFile = new File(fullCodePath);
5059 installDir = codeFile.getParentFile();
5060 codeFileName = fullCodePath;
5061 resourceFileName = fullResourcePath;
5062 }
5063
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005064 FileInstallArgs(Uri packageURI, String pkgName) {
5065 super(packageURI, null, 0, null);
5066 boolean fwdLocked = isFwdLocked(flags);
5067 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5068 String apkName = getNextCodePath(null, pkgName, ".apk");
5069 codeFileName = new File(installDir, apkName + ".apk").getPath();
5070 resourceFileName = getResourcePathFromCodePath();
5071 }
5072
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005073 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5074 return imcs.checkFreeStorage(false, packageURI);
5075 }
5076
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005077 String getCodePath() {
5078 return codeFileName;
5079 }
5080
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005081 void createCopyFile() {
5082 boolean fwdLocked = isFwdLocked(flags);
5083 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5084 codeFileName = createTempPackageFile(installDir).getPath();
5085 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005086 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005087 }
5088
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005089 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005090 if (temp) {
5091 // Generate temp file name
5092 createCopyFile();
5093 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005094 // Get a ParcelFileDescriptor to write to the output file
5095 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005096 if (!created) {
5097 try {
5098 codeFile.createNewFile();
5099 // Set permissions
5100 if (!setPermissions()) {
5101 // Failed setting permissions.
5102 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5103 }
5104 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005105 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005106 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5107 }
5108 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005109 ParcelFileDescriptor out = null;
5110 try {
5111 out = ParcelFileDescriptor.open(codeFile,
5112 ParcelFileDescriptor.MODE_READ_WRITE);
5113 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005114 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005115 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5116 }
5117 // Copy the resource now
5118 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5119 try {
5120 if (imcs.copyResource(packageURI, out)) {
5121 ret = PackageManager.INSTALL_SUCCEEDED;
5122 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005123 } finally {
5124 try { if (out != null) out.close(); } catch (IOException e) {}
5125 }
5126 return ret;
5127 }
5128
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005129 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005130 if (status != PackageManager.INSTALL_SUCCEEDED) {
5131 cleanUp();
5132 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005133 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005134 }
5135
5136 boolean doRename(int status, final String pkgName, String oldCodePath) {
5137 if (status != PackageManager.INSTALL_SUCCEEDED) {
5138 cleanUp();
5139 return false;
5140 } else {
5141 // Rename based on packageName
5142 File codeFile = new File(getCodePath());
5143 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5144 File desFile = new File(installDir, apkName + ".apk");
5145 if (!codeFile.renameTo(desFile)) {
5146 return false;
5147 }
5148 // Reset paths since the file has been renamed.
5149 codeFileName = desFile.getPath();
5150 resourceFileName = getResourcePathFromCodePath();
5151 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005152 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005153 // Failed setting permissions.
5154 return false;
5155 }
5156 return true;
5157 }
5158 }
5159
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005160 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005161 if (status != PackageManager.INSTALL_SUCCEEDED) {
5162 cleanUp();
5163 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005164 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005165 }
5166
5167 String getResourcePath() {
5168 return resourceFileName;
5169 }
5170
5171 String getResourcePathFromCodePath() {
5172 String codePath = getCodePath();
5173 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5174 String apkNameOnly = getApkName(codePath);
5175 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5176 } else {
5177 return codePath;
5178 }
5179 }
5180
5181 private boolean cleanUp() {
5182 boolean ret = true;
5183 String sourceDir = getCodePath();
5184 String publicSourceDir = getResourcePath();
5185 if (sourceDir != null) {
5186 File sourceFile = new File(sourceDir);
5187 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005188 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005189 ret = false;
5190 }
5191 // Delete application's code and resources
5192 sourceFile.delete();
5193 }
5194 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5195 final File publicSourceFile = new File(publicSourceDir);
5196 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005197 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005198 }
5199 if (publicSourceFile.exists()) {
5200 publicSourceFile.delete();
5201 }
5202 }
5203 return ret;
5204 }
5205
5206 void cleanUpResourcesLI() {
5207 String sourceDir = getCodePath();
5208 if (cleanUp() && mInstaller != null) {
5209 int retCode = mInstaller.rmdex(sourceDir);
5210 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005211 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005212 + " at location "
5213 + sourceDir + ", retcode=" + retCode);
5214 // we don't consider this to be a failure of the core package deletion
5215 }
5216 }
5217 }
5218
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005219 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005220 // TODO Do this in a more elegant way later on. for now just a hack
5221 if (!isFwdLocked(flags)) {
5222 final int filePermissions =
5223 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5224 |FileUtils.S_IROTH;
5225 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5226 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005227 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005228 getCodePath()
5229 + ". The return code was: " + retCode);
5230 // TODO Define new internal error
5231 return false;
5232 }
5233 return true;
5234 }
5235 return true;
5236 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005237
5238 boolean doPostDeleteLI(boolean delete) {
5239 cleanUpResourcesLI();
5240 return true;
5241 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005242 }
5243
5244 class SdInstallArgs extends InstallArgs {
5245 String cid;
5246 String cachePath;
5247 static final String RES_FILE_NAME = "pkg.apk";
5248
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005249 SdInstallArgs(InstallParams params) {
5250 super(params.packageURI, params.observer,
5251 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005252 }
5253
5254 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005255 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005256 // Extract cid from fullCodePath
5257 int eidx = fullCodePath.lastIndexOf("/");
5258 String subStr1 = fullCodePath.substring(0, eidx);
5259 int sidx = subStr1.lastIndexOf("/");
5260 cid = subStr1.substring(sidx+1, eidx);
5261 cachePath = subStr1;
5262 }
5263
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005264 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005265 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5266 this.cid = cid;
5267 }
5268
5269 SdInstallArgs(Uri packageURI, String cid) {
5270 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005271 this.cid = cid;
5272 }
5273
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005274 void createCopyFile() {
5275 cid = getTempContainerId();
5276 }
5277
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005278 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5279 return imcs.checkFreeStorage(true, packageURI);
5280 }
5281
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005282 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005283 if (temp) {
5284 createCopyFile();
5285 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005286 cachePath = imcs.copyResourceToContainer(
5287 packageURI, cid,
5288 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005289 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5290 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005291 }
5292
5293 @Override
5294 String getCodePath() {
5295 return cachePath + "/" + RES_FILE_NAME;
5296 }
5297
5298 @Override
5299 String getResourcePath() {
5300 return cachePath + "/" + RES_FILE_NAME;
5301 }
5302
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005303 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005304 if (status != PackageManager.INSTALL_SUCCEEDED) {
5305 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005306 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005307 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005308 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005309 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005310 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005311 if (cachePath == null) {
5312 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5313 }
5314 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005315 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005316 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005317 }
5318
5319 boolean doRename(int status, final String pkgName,
5320 String oldCodePath) {
5321 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005322 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005323 if (PackageHelper.isContainerMounted(cid)) {
5324 // Unmount the container
5325 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005326 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005327 return false;
5328 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005329 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005330 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005331 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5332 " which might be stale. Will try to clean up.");
5333 // Clean up the stale container and proceed to recreate.
5334 if (!PackageHelper.destroySdDir(newCacheId)) {
5335 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5336 return false;
5337 }
5338 // Successfully cleaned up stale container. Try to rename again.
5339 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5340 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5341 + " inspite of cleaning it up.");
5342 return false;
5343 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005344 }
5345 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005346 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005347 newCachePath = PackageHelper.mountSdDir(newCacheId,
5348 getEncryptKey(), Process.SYSTEM_UID);
5349 } else {
5350 newCachePath = PackageHelper.getSdDir(newCacheId);
5351 }
5352 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005353 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005354 return false;
5355 }
5356 Log.i(TAG, "Succesfully renamed " + cid +
5357 " at path: " + cachePath + " to " + newCacheId +
5358 " at new path: " + newCachePath);
5359 cid = newCacheId;
5360 cachePath = newCachePath;
5361 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005362 }
5363
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005364 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005365 if (status != PackageManager.INSTALL_SUCCEEDED) {
5366 cleanUp();
5367 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005368 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005369 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005370 PackageHelper.mountSdDir(cid,
5371 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005372 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005373 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005374 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005375 }
5376
5377 private void cleanUp() {
5378 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005379 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005380 }
5381
5382 void cleanUpResourcesLI() {
5383 String sourceFile = getCodePath();
5384 // Remove dex file
5385 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005386 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005387 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005388 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005389 + " at location "
5390 + sourceFile.toString() + ", retcode=" + retCode);
5391 // we don't consider this to be a failure of the core package deletion
5392 }
5393 }
5394 cleanUp();
5395 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005396
5397 boolean matchContainer(String app) {
5398 if (cid.startsWith(app)) {
5399 return true;
5400 }
5401 return false;
5402 }
5403
5404 String getPackageName() {
5405 int idx = cid.lastIndexOf("-");
5406 if (idx == -1) {
5407 return cid;
5408 }
5409 return cid.substring(0, idx);
5410 }
5411
5412 boolean doPostDeleteLI(boolean delete) {
5413 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005414 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005415 if (mounted) {
5416 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005417 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005418 }
5419 if (ret && delete) {
5420 cleanUpResourcesLI();
5421 }
5422 return ret;
5423 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005424 };
5425
5426 // Utility method used to create code paths based on package name and available index.
5427 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5428 String idxStr = "";
5429 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005430 // Fall back to default value of idx=1 if prefix is not
5431 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005432 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005433 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005434 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005435 if (subStr.endsWith(suffix)) {
5436 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005437 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005438 // If oldCodePath already contains prefix find out the
5439 // ending index to either increment or decrement.
5440 int sidx = subStr.lastIndexOf(prefix);
5441 if (sidx != -1) {
5442 subStr = subStr.substring(sidx + prefix.length());
5443 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005444 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5445 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005446 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005447 try {
5448 idx = Integer.parseInt(subStr);
5449 if (idx <= 1) {
5450 idx++;
5451 } else {
5452 idx--;
5453 }
5454 } catch(NumberFormatException e) {
5455 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005456 }
5457 }
5458 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005459 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005460 return prefix + idxStr;
5461 }
5462
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005463 // Utility method used to ignore ADD/REMOVE events
5464 // by directory observer.
5465 private static boolean ignoreCodePath(String fullPathStr) {
5466 String apkName = getApkName(fullPathStr);
5467 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5468 if (idx != -1 && ((idx+1) < apkName.length())) {
5469 // Make sure the package ends with a numeral
5470 String version = apkName.substring(idx+1);
5471 try {
5472 Integer.parseInt(version);
5473 return true;
5474 } catch (NumberFormatException e) {}
5475 }
5476 return false;
5477 }
5478
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005479 // Utility method that returns the relative package path with respect
5480 // to the installation directory. Like say for /data/data/com.test-1.apk
5481 // string com.test-1 is returned.
5482 static String getApkName(String codePath) {
5483 if (codePath == null) {
5484 return null;
5485 }
5486 int sidx = codePath.lastIndexOf("/");
5487 int eidx = codePath.lastIndexOf(".");
5488 if (eidx == -1) {
5489 eidx = codePath.length();
5490 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005491 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005492 return null;
5493 }
5494 return codePath.substring(sidx+1, eidx);
5495 }
5496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005497 class PackageInstalledInfo {
5498 String name;
5499 int uid;
5500 PackageParser.Package pkg;
5501 int returnCode;
5502 PackageRemovedInfo removedInfo;
5503 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005505 /*
5506 * Install a non-existing package.
5507 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005508 private void installNewPackageLI(PackageParser.Package pkg,
5509 int parseFlags,
5510 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005511 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005513 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005514
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005515 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005516 res.name = pkgName;
5517 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005518 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5519 // A package with the same name is already installed, though
5520 // it has been renamed to an older name. The package we
5521 // are trying to install should be installed as an update to
5522 // the existing one, but that has not been requested, so bail.
5523 Slog.w(TAG, "Attempt to re-install " + pkgName
5524 + " without first uninstalling package running as "
5525 + mSettings.mRenamedPackages.get(pkgName));
5526 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5527 return;
5528 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005529 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005531 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 + " without first uninstalling.");
5533 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5534 return;
5535 }
5536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005537 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005538 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005540 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5542 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5543 }
5544 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005545 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005546 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005547 res);
5548 // delete the partially installed application. the data directory will have to be
5549 // restored if it was already existing
5550 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5551 // remove package from internal structures. Note that we want deletePackageX to
5552 // delete the package data and cache directories that it created in
5553 // scanPackageLocked, unless those directories existed before we even tried to
5554 // install.
5555 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005556 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5558 res.removedInfo);
5559 }
5560 }
5561 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005562
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005563 private void replacePackageLI(PackageParser.Package pkg,
5564 int parseFlags,
5565 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005566 String installerPackageName, PackageInstalledInfo res) {
5567
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005568 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005569 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 // First find the old package info and check signatures
5571 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005572 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005573 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005574 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5576 return;
5577 }
5578 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005579 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005580 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005581 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005583 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005584 }
5585 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005587 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005588 PackageParser.Package pkg,
5589 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005590 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005591 PackageParser.Package newPackage = null;
5592 String pkgName = deletedPackage.packageName;
5593 boolean deletedPkg = true;
5594 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005595
Jacek Surazski65e13172009-04-28 15:26:38 +02005596 String oldInstallerPackageName = null;
5597 synchronized (mPackages) {
5598 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5599 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005602 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 res.removedInfo)) {
5604 // If the existing package was'nt successfully deleted
5605 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5606 deletedPkg = false;
5607 } else {
5608 // Successfully deleted the old package. Now proceed with re-installation
5609 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005610 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005612 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5614 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005615 }
5616 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005617 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005618 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 res);
5620 updatedSettings = true;
5621 }
5622 }
5623
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005624 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005625 // remove package from internal structures. Note that we want deletePackageX to
5626 // delete the package data and cache directories that it created in
5627 // scanPackageLocked, unless those directories existed before we even tried to
5628 // install.
5629 if(updatedSettings) {
5630 deletePackageLI(
5631 pkgName, true,
5632 PackageManager.DONT_DELETE_DATA,
5633 res.removedInfo);
5634 }
5635 // Since we failed to install the new package we need to restore the old
5636 // package that we deleted.
5637 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005638 File restoreFile = new File(deletedPackage.mPath);
5639 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005640 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005641 return;
5642 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005643 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005644 boolean oldOnSd = isExternal(deletedPackage);
5645 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5646 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5647 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5648 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5649 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5650 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5651 return;
5652 }
5653 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005654 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005655 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5656 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005657 mSettings.writeLP();
5658 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005659 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 }
5661 }
5662 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005664 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005665 PackageParser.Package pkg,
5666 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005667 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 PackageParser.Package newPackage = null;
5669 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005670 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 PackageParser.PARSE_IS_SYSTEM;
5672 String packageName = deletedPackage.packageName;
5673 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5674 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005675 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005676 return;
5677 }
5678 PackageParser.Package oldPkg;
5679 PackageSetting oldPkgSetting;
5680 synchronized (mPackages) {
5681 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005682 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005683 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5684 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005685 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005686 return;
5687 }
5688 }
5689 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5690 res.removedInfo.removedPackage = packageName;
5691 // Remove existing system package
5692 removePackageLI(oldPkg, true);
5693 synchronized (mPackages) {
5694 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5695 }
5696
5697 // Successfully disabled the old package. Now proceed with re-installation
5698 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5699 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005700 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005702 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5704 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5705 }
5706 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005707 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 updatedSettings = true;
5709 }
5710
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005711 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005712 // Re installation failed. Restore old information
5713 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005714 if (newPackage != null) {
5715 removePackageLI(newPackage, true);
5716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005718 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005720 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 // Restore the old system information in Settings
5722 synchronized(mPackages) {
5723 if(updatedSettings) {
5724 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005725 mSettings.setInstallerPackageName(packageName,
5726 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 }
5728 mSettings.writeLP();
5729 }
5730 }
5731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005732
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005733 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005734 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005735 int retCode;
5736 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5737 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5738 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005739 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005740 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5741 }
5742 }
5743 return PackageManager.INSTALL_SUCCEEDED;
5744 }
5745
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005746 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005747 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005748 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 synchronized (mPackages) {
5750 //write settings. the installStatus will be incomplete at this stage.
5751 //note that the new package setting would have already been
5752 //added to mPackages. It hasn't been persisted yet.
5753 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5754 mSettings.writeLP();
5755 }
5756
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005757 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005758 != PackageManager.INSTALL_SUCCEEDED) {
5759 // Discontinue if moving dex files failed.
5760 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005762 if((res.returnCode = setPermissionsLI(newPackage))
5763 != PackageManager.INSTALL_SUCCEEDED) {
5764 if (mInstaller != null) {
5765 mInstaller.rmdex(newPackage.mScanPath);
5766 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005767 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005769 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005771 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005772 updatePermissionsLP(newPackage.packageName, newPackage,
5773 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005774 res.name = pkgName;
5775 res.uid = newPackage.applicationInfo.uid;
5776 res.pkg = newPackage;
5777 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005778 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5780 //to update install status
5781 mSettings.writeLP();
5782 }
5783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005784
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005785 private void installPackageLI(InstallArgs args,
5786 boolean newInstall, PackageInstalledInfo res) {
5787 int pFlags = args.flags;
5788 String installerPackageName = args.installerPackageName;
5789 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005790 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005791 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005792 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005793 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005794 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005795 // Result object to be returned
5796 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5797
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005798 // Retrieve PackageSettings and parse package
5799 int parseFlags = PackageParser.PARSE_CHATTY |
5800 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5801 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5802 parseFlags |= mDefParseFlags;
5803 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5804 pp.setSeparateProcesses(mSeparateProcesses);
5805 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5806 null, mMetrics, parseFlags);
5807 if (pkg == null) {
5808 res.returnCode = pp.getParseError();
5809 return;
5810 }
5811 String pkgName = res.name = pkg.packageName;
5812 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5813 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5814 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5815 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005817 }
5818 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5819 res.returnCode = pp.getParseError();
5820 return;
5821 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005822 // Get rid of all references to package scan path via parser.
5823 pp = null;
5824 String oldCodePath = null;
5825 boolean systemApp = false;
5826 synchronized (mPackages) {
5827 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005828 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5829 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005830 if (pkg.mOriginalPackages != null
5831 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005832 && mPackages.containsKey(oldName)) {
5833 // This package is derived from an original package,
5834 // and this device has been updating from that original
5835 // name. We must continue using the original name, so
5836 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005837 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005838 pkgName = pkg.packageName;
5839 replace = true;
5840 } else if (mPackages.containsKey(pkgName)) {
5841 // This package, under its official name, already exists
5842 // on the device; we should replace it.
5843 replace = true;
5844 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005845 }
5846 PackageSetting ps = mSettings.mPackages.get(pkgName);
5847 if (ps != null) {
5848 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5849 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5850 systemApp = (ps.pkg.applicationInfo.flags &
5851 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005852 }
5853 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005855
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005856 if (systemApp && onSd) {
5857 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005858 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005859 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5860 return;
5861 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005862
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005863 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5864 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5865 return;
5866 }
5867 // Set application objects path explicitly after the rename
5868 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005869 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005870 replacePackageLI(pkg, parseFlags, scanMode,
5871 installerPackageName, res);
5872 } else {
5873 installNewPackageLI(pkg, parseFlags, scanMode,
5874 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 }
5876 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005877
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005878 private int setPermissionsLI(PackageParser.Package newPackage) {
5879 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005880 int retCode = 0;
5881 // TODO Gross hack but fix later. Ideally move this to be a post installation
5882 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005883 if ((newPackage.applicationInfo.flags
5884 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5885 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005886 try {
5887 extractPublicFiles(newPackage, destResourceFile);
5888 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005889 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 -08005890 " forward-locked app.");
5891 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5892 } finally {
5893 //TODO clean up the extracted public files
5894 }
5895 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005896 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 newPackage.applicationInfo.uid);
5898 } else {
5899 final int filePermissions =
5900 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005901 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005902 newPackage.applicationInfo.uid);
5903 }
5904 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005905 // The permissions on the resource file was set when it was copied for
5906 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005909 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005910 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005911 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005912 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005913 // TODO Define new internal error
5914 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005915 }
5916 return PackageManager.INSTALL_SUCCEEDED;
5917 }
5918
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005919 private boolean isForwardLocked(PackageParser.Package pkg) {
5920 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 }
5922
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005923 private boolean isExternal(PackageParser.Package pkg) {
5924 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
5925 }
5926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005927 private void extractPublicFiles(PackageParser.Package newPackage,
5928 File publicZipFile) throws IOException {
5929 final ZipOutputStream publicZipOutStream =
5930 new ZipOutputStream(new FileOutputStream(publicZipFile));
5931 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5932
5933 // Copy manifest, resources.arsc and res directory to public zip
5934
5935 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5936 while (privateZipEntries.hasMoreElements()) {
5937 final ZipEntry zipEntry = privateZipEntries.nextElement();
5938 final String zipEntryName = zipEntry.getName();
5939 if ("AndroidManifest.xml".equals(zipEntryName)
5940 || "resources.arsc".equals(zipEntryName)
5941 || zipEntryName.startsWith("res/")) {
5942 try {
5943 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5944 } catch (IOException e) {
5945 try {
5946 publicZipOutStream.close();
5947 throw e;
5948 } finally {
5949 publicZipFile.delete();
5950 }
5951 }
5952 }
5953 }
5954
5955 publicZipOutStream.close();
5956 FileUtils.setPermissions(
5957 publicZipFile.getAbsolutePath(),
5958 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5959 -1, -1);
5960 }
5961
5962 private static void copyZipEntry(ZipEntry zipEntry,
5963 ZipFile inZipFile,
5964 ZipOutputStream outZipStream) throws IOException {
5965 byte[] buffer = new byte[4096];
5966 int num;
5967
5968 ZipEntry newEntry;
5969 if (zipEntry.getMethod() == ZipEntry.STORED) {
5970 // Preserve the STORED method of the input entry.
5971 newEntry = new ZipEntry(zipEntry);
5972 } else {
5973 // Create a new entry so that the compressed len is recomputed.
5974 newEntry = new ZipEntry(zipEntry.getName());
5975 }
5976 outZipStream.putNextEntry(newEntry);
5977
5978 InputStream data = inZipFile.getInputStream(zipEntry);
5979 while ((num = data.read(buffer)) > 0) {
5980 outZipStream.write(buffer, 0, num);
5981 }
5982 outZipStream.flush();
5983 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 private void deleteTempPackageFiles() {
5986 FilenameFilter filter = new FilenameFilter() {
5987 public boolean accept(File dir, String name) {
5988 return name.startsWith("vmdl") && name.endsWith(".tmp");
5989 }
5990 };
5991 String tmpFilesList[] = mAppInstallDir.list(filter);
5992 if(tmpFilesList == null) {
5993 return;
5994 }
5995 for(int i = 0; i < tmpFilesList.length; i++) {
5996 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5997 tmpFile.delete();
5998 }
5999 }
6000
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006001 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006002 File tmpPackageFile;
6003 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006004 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006005 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006006 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 return null;
6008 }
6009 try {
6010 FileUtils.setPermissions(
6011 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6012 -1, -1);
6013 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006014 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 return null;
6016 }
6017 return tmpPackageFile;
6018 }
6019
6020 public void deletePackage(final String packageName,
6021 final IPackageDeleteObserver observer,
6022 final int flags) {
6023 mContext.enforceCallingOrSelfPermission(
6024 android.Manifest.permission.DELETE_PACKAGES, null);
6025 // Queue up an async operation since the package deletion may take a little while.
6026 mHandler.post(new Runnable() {
6027 public void run() {
6028 mHandler.removeCallbacks(this);
6029 final boolean succeded = deletePackageX(packageName, true, true, flags);
6030 if (observer != null) {
6031 try {
6032 observer.packageDeleted(succeded);
6033 } catch (RemoteException e) {
6034 Log.i(TAG, "Observer no longer exists.");
6035 } //end catch
6036 } //end if
6037 } //end run
6038 });
6039 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 /**
6042 * This method is an internal method that could be get invoked either
6043 * to delete an installed package or to clean up a failed installation.
6044 * After deleting an installed package, a broadcast is sent to notify any
6045 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006046 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006047 * installation wouldn't have sent the initial broadcast either
6048 * The key steps in deleting a package are
6049 * deleting the package information in internal structures like mPackages,
6050 * deleting the packages base directories through installd
6051 * updating mSettings to reflect current status
6052 * persisting settings for later use
6053 * sending a broadcast if necessary
6054 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6056 boolean deleteCodeAndResources, int flags) {
6057 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006058 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006060 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6061 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6062 try {
6063 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006064 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006065 return false;
6066 }
6067 } catch (RemoteException e) {
6068 }
6069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070 synchronized (mInstallLock) {
6071 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
6072 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006074 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006075 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
6076 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
6077
6078 // If the removed package was a system update, the old system packaged
6079 // was re-enabled; we need to broadcast this information
6080 if (systemUpdate) {
6081 Bundle extras = new Bundle(1);
6082 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6083 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6084
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006085 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6086 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08006089 // Force a gc here.
6090 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006091 // Delete the resources here after sending the broadcast to let
6092 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006093 if (info.args != null) {
6094 synchronized (mInstallLock) {
6095 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006096 }
6097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006098 return res;
6099 }
6100
6101 static class PackageRemovedInfo {
6102 String removedPackage;
6103 int uid = -1;
6104 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006105 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006106 // Clean up resources deleted packages.
6107 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 void sendBroadcast(boolean fullRemove, boolean replacing) {
6110 Bundle extras = new Bundle(1);
6111 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6112 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6113 if (replacing) {
6114 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6115 }
6116 if (removedPackage != null) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006117 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006118 }
6119 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006120 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 }
6122 }
6123 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 /*
6126 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6127 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006128 * 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 -08006129 * delete a partially installed application.
6130 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006131 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132 int flags) {
6133 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006134 if (outInfo != null) {
6135 outInfo.removedPackage = packageName;
6136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 removePackageLI(p, true);
6138 // Retrieve object to delete permissions for shared user later on
6139 PackageSetting deletedPs;
6140 synchronized (mPackages) {
6141 deletedPs = mSettings.mPackages.get(packageName);
6142 }
6143 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6144 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006145 int retCode = mInstaller.remove(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006147 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 + packageName + ", retcode=" + retCode);
6149 // we don't consider this to be a failure of the core package deletion
6150 }
6151 } else {
6152 //for emulator
6153 PackageParser.Package pkg = mPackages.get(packageName);
6154 File dataDir = new File(pkg.applicationInfo.dataDir);
6155 dataDir.delete();
6156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 }
6158 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006159 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006160 schedulePackageCleaning(packageName);
6161
6162 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6163 if (outInfo != null) {
6164 outInfo.removedUid = mSettings.removePackageLP(packageName);
6165 }
6166 if (deletedPs != null) {
6167 updatePermissionsLP(deletedPs.name, null, false, false);
6168 if (deletedPs.sharedUser != null) {
6169 // remove permissions associated with package
6170 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6171 }
6172 }
6173 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006174 // remove from preferred activities.
6175 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6176 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6177 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6178 removed.add(pa);
6179 }
6180 }
6181 for (PreferredActivity pa : removed) {
6182 mSettings.mPreferredActivities.removeFilter(pa);
6183 }
6184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006186 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 }
6188 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006190 /*
6191 * Tries to delete system package.
6192 */
6193 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006194 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006195 ApplicationInfo applicationInfo = p.applicationInfo;
6196 //applicable for non-partially installed applications only
6197 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006198 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 return false;
6200 }
6201 PackageSetting ps = null;
6202 // Confirm if the system package has been updated
6203 // An updated system app can be deleted. This will also have to restore
6204 // the system pkg from system partition
6205 synchronized (mPackages) {
6206 ps = mSettings.getDisabledSystemPkg(p.packageName);
6207 }
6208 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006209 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 return false;
6211 } else {
6212 Log.i(TAG, "Deleting system pkg from data partition");
6213 }
6214 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006215 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006216 boolean deleteCodeAndResources = false;
6217 if (ps.versionCode < p.mVersionCode) {
6218 // Delete code and resources for downgrades
6219 deleteCodeAndResources = true;
6220 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6221 flags &= ~PackageManager.DONT_DELETE_DATA;
6222 }
6223 } else {
6224 // Preserve data by setting flag
6225 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6226 flags |= PackageManager.DONT_DELETE_DATA;
6227 }
6228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6230 if (!ret) {
6231 return false;
6232 }
6233 synchronized (mPackages) {
6234 // Reinstate the old system package
6235 mSettings.enableSystemPackageLP(p.packageName);
6236 }
6237 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006238 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006240 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006243 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 return false;
6245 }
6246 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006247 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 mSettings.writeLP();
6249 }
6250 return true;
6251 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6254 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6255 ApplicationInfo applicationInfo = p.applicationInfo;
6256 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006257 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 return false;
6259 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006260 if (outInfo != null) {
6261 outInfo.uid = applicationInfo.uid;
6262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263
6264 // Delete package data from internal structures and also remove data if flag is set
6265 removePackageDataLI(p, outInfo, flags);
6266
6267 // Delete application code and resources
6268 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006269 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006270 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006271 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006272 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6273 PackageManager.INSTALL_FORWARD_LOCK : 0;
6274 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006275 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 }
6277 return true;
6278 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 /*
6281 * This method handles package deletion in general
6282 */
6283 private boolean deletePackageLI(String packageName,
6284 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6285 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006286 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006287 return false;
6288 }
6289 PackageParser.Package p;
6290 boolean dataOnly = false;
6291 synchronized (mPackages) {
6292 p = mPackages.get(packageName);
6293 if (p == null) {
6294 //this retrieves partially installed apps
6295 dataOnly = true;
6296 PackageSetting ps = mSettings.mPackages.get(packageName);
6297 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006298 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006299 return false;
6300 }
6301 p = ps.pkg;
6302 }
6303 }
6304 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006305 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 return false;
6307 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 if (dataOnly) {
6310 // Delete application data first
6311 removePackageDataLI(p, outInfo, flags);
6312 return true;
6313 }
6314 // At this point the package should have ApplicationInfo associated with it
6315 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006316 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 return false;
6318 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006319 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6321 Log.i(TAG, "Removing system package:"+p.packageName);
6322 // When an updated system application is deleted we delete the existing resources as well and
6323 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006324 ret = deleteSystemPackageLI(p, flags, outInfo);
6325 } else {
6326 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006327 // Kill application pre-emptively especially for apps on sd.
6328 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006329 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006331 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 public void clearApplicationUserData(final String packageName,
6335 final IPackageDataObserver observer) {
6336 mContext.enforceCallingOrSelfPermission(
6337 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6338 // Queue up an async operation since the package deletion may take a little while.
6339 mHandler.post(new Runnable() {
6340 public void run() {
6341 mHandler.removeCallbacks(this);
6342 final boolean succeeded;
6343 synchronized (mInstallLock) {
6344 succeeded = clearApplicationUserDataLI(packageName);
6345 }
6346 if (succeeded) {
6347 // invoke DeviceStorageMonitor's update method to clear any notifications
6348 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6349 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6350 if (dsm != null) {
6351 dsm.updateMemory();
6352 }
6353 }
6354 if(observer != null) {
6355 try {
6356 observer.onRemoveCompleted(packageName, succeeded);
6357 } catch (RemoteException e) {
6358 Log.i(TAG, "Observer no longer exists.");
6359 }
6360 } //end if observer
6361 } //end run
6362 });
6363 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 private boolean clearApplicationUserDataLI(String packageName) {
6366 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006367 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368 return false;
6369 }
6370 PackageParser.Package p;
6371 boolean dataOnly = false;
6372 synchronized (mPackages) {
6373 p = mPackages.get(packageName);
6374 if(p == null) {
6375 dataOnly = true;
6376 PackageSetting ps = mSettings.mPackages.get(packageName);
6377 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006378 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006379 return false;
6380 }
6381 p = ps.pkg;
6382 }
6383 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 if(!dataOnly) {
6386 //need to check this only for fully installed applications
6387 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006388 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 return false;
6390 }
6391 final ApplicationInfo applicationInfo = p.applicationInfo;
6392 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006393 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 return false;
6395 }
6396 }
6397 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006398 int retCode = mInstaller.clearUserData(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006399 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006400 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 + packageName);
6402 return false;
6403 }
6404 }
6405 return true;
6406 }
6407
6408 public void deleteApplicationCacheFiles(final String packageName,
6409 final IPackageDataObserver observer) {
6410 mContext.enforceCallingOrSelfPermission(
6411 android.Manifest.permission.DELETE_CACHE_FILES, null);
6412 // Queue up an async operation since the package deletion may take a little while.
6413 mHandler.post(new Runnable() {
6414 public void run() {
6415 mHandler.removeCallbacks(this);
6416 final boolean succeded;
6417 synchronized (mInstallLock) {
6418 succeded = deleteApplicationCacheFilesLI(packageName);
6419 }
6420 if(observer != null) {
6421 try {
6422 observer.onRemoveCompleted(packageName, succeded);
6423 } catch (RemoteException e) {
6424 Log.i(TAG, "Observer no longer exists.");
6425 }
6426 } //end if observer
6427 } //end run
6428 });
6429 }
6430
6431 private boolean deleteApplicationCacheFilesLI(String packageName) {
6432 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006433 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 return false;
6435 }
6436 PackageParser.Package p;
6437 synchronized (mPackages) {
6438 p = mPackages.get(packageName);
6439 }
6440 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006441 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 return false;
6443 }
6444 final ApplicationInfo applicationInfo = p.applicationInfo;
6445 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006446 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 return false;
6448 }
6449 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006450 int retCode = mInstaller.deleteCacheFiles(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006452 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 + packageName);
6454 return false;
6455 }
6456 }
6457 return true;
6458 }
6459
6460 public void getPackageSizeInfo(final String packageName,
6461 final IPackageStatsObserver observer) {
6462 mContext.enforceCallingOrSelfPermission(
6463 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6464 // Queue up an async operation since the package deletion may take a little while.
6465 mHandler.post(new Runnable() {
6466 public void run() {
6467 mHandler.removeCallbacks(this);
6468 PackageStats lStats = new PackageStats(packageName);
6469 final boolean succeded;
6470 synchronized (mInstallLock) {
6471 succeded = getPackageSizeInfoLI(packageName, lStats);
6472 }
6473 if(observer != null) {
6474 try {
6475 observer.onGetStatsCompleted(lStats, succeded);
6476 } catch (RemoteException e) {
6477 Log.i(TAG, "Observer no longer exists.");
6478 }
6479 } //end if observer
6480 } //end run
6481 });
6482 }
6483
6484 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6485 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006486 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 return false;
6488 }
6489 PackageParser.Package p;
6490 boolean dataOnly = false;
6491 synchronized (mPackages) {
6492 p = mPackages.get(packageName);
6493 if(p == null) {
6494 dataOnly = true;
6495 PackageSetting ps = mSettings.mPackages.get(packageName);
6496 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006497 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 return false;
6499 }
6500 p = ps.pkg;
6501 }
6502 }
6503 String publicSrcDir = null;
6504 if(!dataOnly) {
6505 final ApplicationInfo applicationInfo = p.applicationInfo;
6506 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006507 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 return false;
6509 }
6510 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6511 }
6512 if (mInstaller != null) {
6513 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006514 publicSrcDir, pStats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 if (res < 0) {
6516 return false;
6517 } else {
6518 return true;
6519 }
6520 }
6521 return true;
6522 }
6523
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 public void addPackageToPreferred(String packageName) {
6526 mContext.enforceCallingOrSelfPermission(
6527 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006528 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 }
6530
6531 public void removePackageFromPreferred(String packageName) {
6532 mContext.enforceCallingOrSelfPermission(
6533 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006534 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 }
6536
6537 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006538 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 }
6540
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006541 int getUidTargetSdkVersionLockedLP(int uid) {
6542 Object obj = mSettings.getUserIdLP(uid);
6543 if (obj instanceof SharedUserSetting) {
6544 SharedUserSetting sus = (SharedUserSetting)obj;
6545 final int N = sus.packages.size();
6546 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6547 Iterator<PackageSetting> it = sus.packages.iterator();
6548 int i=0;
6549 while (it.hasNext()) {
6550 PackageSetting ps = it.next();
6551 if (ps.pkg != null) {
6552 int v = ps.pkg.applicationInfo.targetSdkVersion;
6553 if (v < vers) vers = v;
6554 }
6555 }
6556 return vers;
6557 } else if (obj instanceof PackageSetting) {
6558 PackageSetting ps = (PackageSetting)obj;
6559 if (ps.pkg != null) {
6560 return ps.pkg.applicationInfo.targetSdkVersion;
6561 }
6562 }
6563 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6564 }
6565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 public void addPreferredActivity(IntentFilter filter, int match,
6567 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006569 if (mContext.checkCallingOrSelfPermission(
6570 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6571 != PackageManager.PERMISSION_GRANTED) {
6572 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6573 < Build.VERSION_CODES.FROYO) {
6574 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6575 + Binder.getCallingUid());
6576 return;
6577 }
6578 mContext.enforceCallingOrSelfPermission(
6579 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6580 }
6581
6582 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6584 mSettings.mPreferredActivities.addFilter(
6585 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006586 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006587 }
6588 }
6589
Satish Sampath8dbe6122009-06-02 23:35:54 +01006590 public void replacePreferredActivity(IntentFilter filter, int match,
6591 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006592 if (filter.countActions() != 1) {
6593 throw new IllegalArgumentException(
6594 "replacePreferredActivity expects filter to have only 1 action.");
6595 }
6596 if (filter.countCategories() != 1) {
6597 throw new IllegalArgumentException(
6598 "replacePreferredActivity expects filter to have only 1 category.");
6599 }
6600 if (filter.countDataAuthorities() != 0
6601 || filter.countDataPaths() != 0
6602 || filter.countDataSchemes() != 0
6603 || filter.countDataTypes() != 0) {
6604 throw new IllegalArgumentException(
6605 "replacePreferredActivity expects filter to have no data authorities, " +
6606 "paths, schemes or types.");
6607 }
6608 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006609 if (mContext.checkCallingOrSelfPermission(
6610 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6611 != PackageManager.PERMISSION_GRANTED) {
6612 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6613 < Build.VERSION_CODES.FROYO) {
6614 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6615 + Binder.getCallingUid());
6616 return;
6617 }
6618 mContext.enforceCallingOrSelfPermission(
6619 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6620 }
6621
Satish Sampath8dbe6122009-06-02 23:35:54 +01006622 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6623 String action = filter.getAction(0);
6624 String category = filter.getCategory(0);
6625 while (it.hasNext()) {
6626 PreferredActivity pa = it.next();
6627 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6628 it.remove();
6629 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6630 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6631 }
6632 }
6633 addPreferredActivity(filter, match, set, activity);
6634 }
6635 }
6636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006638 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006639 int uid = Binder.getCallingUid();
6640 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006641 if (pkg == null || pkg.applicationInfo.uid != uid) {
6642 if (mContext.checkCallingOrSelfPermission(
6643 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6644 != PackageManager.PERMISSION_GRANTED) {
6645 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6646 < Build.VERSION_CODES.FROYO) {
6647 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6648 + Binder.getCallingUid());
6649 return;
6650 }
6651 mContext.enforceCallingOrSelfPermission(
6652 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6653 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006654 }
6655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006656 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006657 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 }
6659 }
6660 }
6661
6662 boolean clearPackagePreferredActivitiesLP(String packageName) {
6663 boolean changed = false;
6664 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6665 while (it.hasNext()) {
6666 PreferredActivity pa = it.next();
6667 if (pa.mActivity.getPackageName().equals(packageName)) {
6668 it.remove();
6669 changed = true;
6670 }
6671 }
6672 return changed;
6673 }
6674
6675 public int getPreferredActivities(List<IntentFilter> outFilters,
6676 List<ComponentName> outActivities, String packageName) {
6677
6678 int num = 0;
6679 synchronized (mPackages) {
6680 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6681 while (it.hasNext()) {
6682 PreferredActivity pa = it.next();
6683 if (packageName == null
6684 || pa.mActivity.getPackageName().equals(packageName)) {
6685 if (outFilters != null) {
6686 outFilters.add(new IntentFilter(pa));
6687 }
6688 if (outActivities != null) {
6689 outActivities.add(pa.mActivity);
6690 }
6691 }
6692 }
6693 }
6694
6695 return num;
6696 }
6697
6698 public void setApplicationEnabledSetting(String appPackageName,
6699 int newState, int flags) {
6700 setEnabledSetting(appPackageName, null, newState, flags);
6701 }
6702
6703 public void setComponentEnabledSetting(ComponentName componentName,
6704 int newState, int flags) {
6705 setEnabledSetting(componentName.getPackageName(),
6706 componentName.getClassName(), newState, flags);
6707 }
6708
6709 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006710 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6712 || newState == COMPONENT_ENABLED_STATE_ENABLED
6713 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6714 throw new IllegalArgumentException("Invalid new component state: "
6715 + newState);
6716 }
6717 PackageSetting pkgSetting;
6718 final int uid = Binder.getCallingUid();
6719 final int permission = mContext.checkCallingPermission(
6720 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6721 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006722 boolean sendNow = false;
6723 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006724 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006725 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006726 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006727 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006728 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006730 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006732 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 }
6734 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006735 "Unknown component: " + packageName
6736 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 }
6738 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6739 throw new SecurityException(
6740 "Permission Denial: attempt to change component state from pid="
6741 + Binder.getCallingPid()
6742 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6743 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006744 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006746 if (pkgSetting.enabled == newState) {
6747 // Nothing to do
6748 return;
6749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 pkgSetting.enabled = newState;
6751 } else {
6752 // We're dealing with a component level state change
6753 switch (newState) {
6754 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006755 if (!pkgSetting.enableComponentLP(className)) {
6756 return;
6757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758 break;
6759 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006760 if (!pkgSetting.disableComponentLP(className)) {
6761 return;
6762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006763 break;
6764 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006765 if (!pkgSetting.restoreComponentLP(className)) {
6766 return;
6767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 break;
6769 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006770 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006771 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 }
6773 }
6774 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006775 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006776 components = mPendingBroadcasts.get(packageName);
6777 boolean newPackage = components == null;
6778 if (newPackage) {
6779 components = new ArrayList<String>();
6780 }
6781 if (!components.contains(componentName)) {
6782 components.add(componentName);
6783 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006784 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6785 sendNow = true;
6786 // Purge entry from pending broadcast list if another one exists already
6787 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006788 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006789 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006790 if (newPackage) {
6791 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006792 }
6793 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6794 // Schedule a message
6795 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6796 }
6797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006798 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006800 long callingId = Binder.clearCallingIdentity();
6801 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006802 if (sendNow) {
6803 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006804 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006806 } finally {
6807 Binder.restoreCallingIdentity(callingId);
6808 }
6809 }
6810
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006811 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006812 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6813 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6814 + " components=" + componentNames);
6815 Bundle extras = new Bundle(4);
6816 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6817 String nameList[] = new String[componentNames.size()];
6818 componentNames.toArray(nameList);
6819 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006820 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6821 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006822 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006823 }
6824
Jacek Surazski65e13172009-04-28 15:26:38 +02006825 public String getInstallerPackageName(String packageName) {
6826 synchronized (mPackages) {
6827 PackageSetting pkg = mSettings.mPackages.get(packageName);
6828 if (pkg == null) {
6829 throw new IllegalArgumentException("Unknown package: " + packageName);
6830 }
6831 return pkg.installerPackageName;
6832 }
6833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006835 public int getApplicationEnabledSetting(String appPackageName) {
6836 synchronized (mPackages) {
6837 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6838 if (pkg == null) {
6839 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6840 }
6841 return pkg.enabled;
6842 }
6843 }
6844
6845 public int getComponentEnabledSetting(ComponentName componentName) {
6846 synchronized (mPackages) {
6847 final String packageNameStr = componentName.getPackageName();
6848 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6849 if (pkg == null) {
6850 throw new IllegalArgumentException("Unknown component: " + componentName);
6851 }
6852 final String classNameStr = componentName.getClassName();
6853 return pkg.currentEnabledStateLP(classNameStr);
6854 }
6855 }
6856
6857 public void enterSafeMode() {
6858 if (!mSystemReady) {
6859 mSafeMode = true;
6860 }
6861 }
6862
6863 public void systemReady() {
6864 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006865
6866 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006867 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006868 mContext.getContentResolver(),
6869 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006870 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006871 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006872 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 }
6875
6876 public boolean isSafeMode() {
6877 return mSafeMode;
6878 }
6879
6880 public boolean hasSystemUidErrors() {
6881 return mHasSystemUidErrors;
6882 }
6883
6884 static String arrayToString(int[] array) {
6885 StringBuffer buf = new StringBuffer(128);
6886 buf.append('[');
6887 if (array != null) {
6888 for (int i=0; i<array.length; i++) {
6889 if (i > 0) buf.append(", ");
6890 buf.append(array[i]);
6891 }
6892 }
6893 buf.append(']');
6894 return buf.toString();
6895 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006897 @Override
6898 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6899 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6900 != PackageManager.PERMISSION_GRANTED) {
6901 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6902 + Binder.getCallingPid()
6903 + ", uid=" + Binder.getCallingUid()
6904 + " without permission "
6905 + android.Manifest.permission.DUMP);
6906 return;
6907 }
6908
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006909 String packageName = null;
6910
6911 int opti = 0;
6912 while (opti < args.length) {
6913 String opt = args[opti];
6914 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6915 break;
6916 }
6917 opti++;
6918 if ("-a".equals(opt)) {
6919 // Right now we only know how to print all.
6920 } else if ("-h".equals(opt)) {
6921 pw.println("Package manager dump options:");
6922 pw.println(" [-h] [cmd] ...");
6923 pw.println(" cmd may be one of:");
6924 pw.println(" [package.name]: info about given package");
6925 return;
6926 } else {
6927 pw.println("Unknown argument: " + opt + "; use -h for help");
6928 }
6929 }
6930
6931 // Is the caller requesting to dump a particular piece of data?
6932 if (opti < args.length) {
6933 String cmd = args[opti];
6934 opti++;
6935 // Is this a package name?
6936 if ("android".equals(cmd) || cmd.contains(".")) {
6937 packageName = cmd;
6938 }
6939 }
6940
6941 boolean printedTitle = false;
6942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006943 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006944 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6945 printedTitle = true;
6946 }
6947 if (mReceivers.dump(pw, printedTitle
6948 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6949 " ", packageName)) {
6950 printedTitle = true;
6951 }
6952 if (mServices.dump(pw, printedTitle
6953 ? "\nService Resolver Table:" : "Service Resolver Table:",
6954 " ", packageName)) {
6955 printedTitle = true;
6956 }
6957 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6958 ? "\nPreferred Activities:" : "Preferred Activities:",
6959 " ", packageName)) {
6960 printedTitle = true;
6961 }
6962 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006963 {
6964 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006965 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6966 continue;
6967 }
6968 if (!printedSomething) {
6969 if (printedTitle) pw.println(" ");
6970 pw.println("Permissions:");
6971 printedSomething = true;
6972 printedTitle = true;
6973 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006974 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6975 pw.print(Integer.toHexString(System.identityHashCode(p)));
6976 pw.println("):");
6977 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6978 pw.print(" uid="); pw.print(p.uid);
6979 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006980 pw.print(" type="); pw.print(p.type);
6981 pw.print(" prot="); pw.println(p.protectionLevel);
6982 if (p.packageSetting != null) {
6983 pw.print(" packageSetting="); pw.println(p.packageSetting);
6984 }
6985 if (p.perm != null) {
6986 pw.print(" perm="); pw.println(p.perm);
6987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006988 }
6989 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006990 printedSomething = false;
6991 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006992 {
6993 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006994 if (packageName != null && !packageName.equals(ps.realName)
6995 && !packageName.equals(ps.name)) {
6996 continue;
6997 }
6998 if (!printedSomething) {
6999 if (printedTitle) pw.println(" ");
7000 pw.println("Packages:");
7001 printedSomething = true;
7002 printedTitle = true;
7003 }
7004 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007005 pw.print(" Package [");
7006 pw.print(ps.realName != null ? ps.realName : ps.name);
7007 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007008 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7009 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007010 if (ps.realName != null) {
7011 pw.print(" compat name="); pw.println(ps.name);
7012 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007013 pw.print(" userId="); pw.print(ps.userId);
7014 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7015 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7016 pw.print(" pkg="); pw.println(ps.pkg);
7017 pw.print(" codePath="); pw.println(ps.codePathString);
7018 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007019 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007020 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007021 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007022 pw.print(" supportsScreens=[");
7023 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007024 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007025 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007026 if (!first) pw.print(", ");
7027 first = false;
7028 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007029 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007030 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007031 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007032 if (!first) pw.print(", ");
7033 first = false;
7034 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007035 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007036 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007037 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007038 if (!first) pw.print(", ");
7039 first = false;
7040 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007041 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007042 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007043 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007044 if (!first) pw.print(", ");
7045 first = false;
7046 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007047 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007048 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007049 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7050 if (!first) pw.print(", ");
7051 first = false;
7052 pw.print("anyDensity");
7053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007054 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007055 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007056 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7057 pw.print(" signatures="); pw.println(ps.signatures);
7058 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007059 pw.print(" haveGids="); pw.println(ps.haveGids);
7060 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007061 pw.print(" installStatus="); pw.print(ps.installStatus);
7062 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007063 if (ps.disabledComponents.size() > 0) {
7064 pw.println(" disabledComponents:");
7065 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007066 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007067 }
7068 }
7069 if (ps.enabledComponents.size() > 0) {
7070 pw.println(" enabledComponents:");
7071 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007072 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007073 }
7074 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007075 if (ps.grantedPermissions.size() > 0) {
7076 pw.println(" grantedPermissions:");
7077 for (String s : ps.grantedPermissions) {
7078 pw.print(" "); pw.println(s);
7079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 }
7082 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007083 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007084 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007085 for (HashMap.Entry<String, String> e
7086 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007087 if (packageName != null && !packageName.equals(e.getKey())
7088 && !packageName.equals(e.getValue())) {
7089 continue;
7090 }
7091 if (!printedSomething) {
7092 if (printedTitle) pw.println(" ");
7093 pw.println("Renamed packages:");
7094 printedSomething = true;
7095 printedTitle = true;
7096 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007097 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7098 pw.println(e.getValue());
7099 }
7100 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007101 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007102 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007103 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007104 if (packageName != null && !packageName.equals(ps.realName)
7105 && !packageName.equals(ps.name)) {
7106 continue;
7107 }
7108 if (!printedSomething) {
7109 if (printedTitle) pw.println(" ");
7110 pw.println("Hidden system packages:");
7111 printedSomething = true;
7112 printedTitle = true;
7113 }
7114 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007115 pw.print(ps.realName != null ? ps.realName : ps.name);
7116 pw.print("] (");
7117 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7118 pw.println("):");
7119 if (ps.realName != null) {
7120 pw.print(" compat name="); pw.println(ps.name);
7121 }
7122 pw.print(" userId="); pw.println(ps.userId);
7123 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7124 pw.print(" codePath="); pw.println(ps.codePathString);
7125 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7126 }
7127 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007128 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007129 {
7130 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007131 if (packageName != null && su != packageSharedUser) {
7132 continue;
7133 }
7134 if (!printedSomething) {
7135 if (printedTitle) pw.println(" ");
7136 pw.println("Shared users:");
7137 printedSomething = true;
7138 printedTitle = true;
7139 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007140 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7141 pw.print(Integer.toHexString(System.identityHashCode(su)));
7142 pw.println("):");
7143 pw.print(" userId="); pw.print(su.userId);
7144 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007145 pw.println(" grantedPermissions:");
7146 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007147 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007149 }
7150 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007151
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007152 if (packageName == null) {
7153 if (printedTitle) pw.println(" ");
7154 printedTitle = true;
7155 pw.println("Settings parse messages:");
7156 pw.println(mSettings.mReadMessages.toString());
7157
7158 pw.println(" ");
7159 pw.println("Package warning messages:");
7160 File fname = getSettingsProblemFile();
7161 FileInputStream in;
7162 try {
7163 in = new FileInputStream(fname);
7164 int avail = in.available();
7165 byte[] data = new byte[avail];
7166 in.read(data);
7167 pw.println(new String(data));
7168 } catch (FileNotFoundException e) {
7169 } catch (IOException e) {
7170 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007172 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007173
7174 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007175 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007176 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007177 if (packageName != null && !packageName.equals(p.info.packageName)) {
7178 continue;
7179 }
7180 if (!printedSomething) {
7181 if (printedTitle) pw.println(" ");
7182 pw.println("Registered ContentProviders:");
7183 printedSomething = true;
7184 printedTitle = true;
7185 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007186 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007187 pw.println(p.toString());
7188 }
7189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 }
7191
7192 static final class BasePermission {
7193 final static int TYPE_NORMAL = 0;
7194 final static int TYPE_BUILTIN = 1;
7195 final static int TYPE_DYNAMIC = 2;
7196
7197 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007198 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007199 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007200 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007201 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007202 PackageParser.Permission perm;
7203 PermissionInfo pendingInfo;
7204 int uid;
7205 int[] gids;
7206
7207 BasePermission(String _name, String _sourcePackage, int _type) {
7208 name = _name;
7209 sourcePackage = _sourcePackage;
7210 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007211 // Default to most conservative protection level.
7212 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7213 }
7214
7215 public String toString() {
7216 return "BasePermission{"
7217 + Integer.toHexString(System.identityHashCode(this))
7218 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 }
7220 }
7221
7222 static class PackageSignatures {
7223 private Signature[] mSignatures;
7224
7225 PackageSignatures(Signature[] sigs) {
7226 assignSignatures(sigs);
7227 }
7228
7229 PackageSignatures() {
7230 }
7231
7232 void writeXml(XmlSerializer serializer, String tagName,
7233 ArrayList<Signature> pastSignatures) throws IOException {
7234 if (mSignatures == null) {
7235 return;
7236 }
7237 serializer.startTag(null, tagName);
7238 serializer.attribute(null, "count",
7239 Integer.toString(mSignatures.length));
7240 for (int i=0; i<mSignatures.length; i++) {
7241 serializer.startTag(null, "cert");
7242 final Signature sig = mSignatures[i];
7243 final int sigHash = sig.hashCode();
7244 final int numPast = pastSignatures.size();
7245 int j;
7246 for (j=0; j<numPast; j++) {
7247 Signature pastSig = pastSignatures.get(j);
7248 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7249 serializer.attribute(null, "index", Integer.toString(j));
7250 break;
7251 }
7252 }
7253 if (j >= numPast) {
7254 pastSignatures.add(sig);
7255 serializer.attribute(null, "index", Integer.toString(numPast));
7256 serializer.attribute(null, "key", sig.toCharsString());
7257 }
7258 serializer.endTag(null, "cert");
7259 }
7260 serializer.endTag(null, tagName);
7261 }
7262
7263 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7264 throws IOException, XmlPullParserException {
7265 String countStr = parser.getAttributeValue(null, "count");
7266 if (countStr == null) {
7267 reportSettingsProblem(Log.WARN,
7268 "Error in package manager settings: <signatures> has"
7269 + " no count at " + parser.getPositionDescription());
7270 XmlUtils.skipCurrentTag(parser);
7271 }
7272 final int count = Integer.parseInt(countStr);
7273 mSignatures = new Signature[count];
7274 int pos = 0;
7275
7276 int outerDepth = parser.getDepth();
7277 int type;
7278 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7279 && (type != XmlPullParser.END_TAG
7280 || parser.getDepth() > outerDepth)) {
7281 if (type == XmlPullParser.END_TAG
7282 || type == XmlPullParser.TEXT) {
7283 continue;
7284 }
7285
7286 String tagName = parser.getName();
7287 if (tagName.equals("cert")) {
7288 if (pos < count) {
7289 String index = parser.getAttributeValue(null, "index");
7290 if (index != null) {
7291 try {
7292 int idx = Integer.parseInt(index);
7293 String key = parser.getAttributeValue(null, "key");
7294 if (key == null) {
7295 if (idx >= 0 && idx < pastSignatures.size()) {
7296 Signature sig = pastSignatures.get(idx);
7297 if (sig != null) {
7298 mSignatures[pos] = pastSignatures.get(idx);
7299 pos++;
7300 } else {
7301 reportSettingsProblem(Log.WARN,
7302 "Error in package manager settings: <cert> "
7303 + "index " + index + " is not defined at "
7304 + parser.getPositionDescription());
7305 }
7306 } else {
7307 reportSettingsProblem(Log.WARN,
7308 "Error in package manager settings: <cert> "
7309 + "index " + index + " is out of bounds at "
7310 + parser.getPositionDescription());
7311 }
7312 } else {
7313 while (pastSignatures.size() <= idx) {
7314 pastSignatures.add(null);
7315 }
7316 Signature sig = new Signature(key);
7317 pastSignatures.set(idx, sig);
7318 mSignatures[pos] = sig;
7319 pos++;
7320 }
7321 } catch (NumberFormatException e) {
7322 reportSettingsProblem(Log.WARN,
7323 "Error in package manager settings: <cert> "
7324 + "index " + index + " is not a number at "
7325 + parser.getPositionDescription());
7326 }
7327 } else {
7328 reportSettingsProblem(Log.WARN,
7329 "Error in package manager settings: <cert> has"
7330 + " no index at " + parser.getPositionDescription());
7331 }
7332 } else {
7333 reportSettingsProblem(Log.WARN,
7334 "Error in package manager settings: too "
7335 + "many <cert> tags, expected " + count
7336 + " at " + parser.getPositionDescription());
7337 }
7338 } else {
7339 reportSettingsProblem(Log.WARN,
7340 "Unknown element under <cert>: "
7341 + parser.getName());
7342 }
7343 XmlUtils.skipCurrentTag(parser);
7344 }
7345
7346 if (pos < count) {
7347 // Should never happen -- there is an error in the written
7348 // settings -- but if it does we don't want to generate
7349 // a bad array.
7350 Signature[] newSigs = new Signature[pos];
7351 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7352 mSignatures = newSigs;
7353 }
7354 }
7355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007356 private void assignSignatures(Signature[] sigs) {
7357 if (sigs == null) {
7358 mSignatures = null;
7359 return;
7360 }
7361 mSignatures = new Signature[sigs.length];
7362 for (int i=0; i<sigs.length; i++) {
7363 mSignatures[i] = sigs[i];
7364 }
7365 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007367 @Override
7368 public String toString() {
7369 StringBuffer buf = new StringBuffer(128);
7370 buf.append("PackageSignatures{");
7371 buf.append(Integer.toHexString(System.identityHashCode(this)));
7372 buf.append(" [");
7373 if (mSignatures != null) {
7374 for (int i=0; i<mSignatures.length; i++) {
7375 if (i > 0) buf.append(", ");
7376 buf.append(Integer.toHexString(
7377 System.identityHashCode(mSignatures[i])));
7378 }
7379 }
7380 buf.append("]}");
7381 return buf.toString();
7382 }
7383 }
7384
7385 static class PreferredActivity extends IntentFilter {
7386 final int mMatch;
7387 final String[] mSetPackages;
7388 final String[] mSetClasses;
7389 final String[] mSetComponents;
7390 final ComponentName mActivity;
7391 final String mShortActivity;
7392 String mParseError;
7393
7394 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7395 ComponentName activity) {
7396 super(filter);
7397 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7398 mActivity = activity;
7399 mShortActivity = activity.flattenToShortString();
7400 mParseError = null;
7401 if (set != null) {
7402 final int N = set.length;
7403 String[] myPackages = new String[N];
7404 String[] myClasses = new String[N];
7405 String[] myComponents = new String[N];
7406 for (int i=0; i<N; i++) {
7407 ComponentName cn = set[i];
7408 if (cn == null) {
7409 mSetPackages = null;
7410 mSetClasses = null;
7411 mSetComponents = null;
7412 return;
7413 }
7414 myPackages[i] = cn.getPackageName().intern();
7415 myClasses[i] = cn.getClassName().intern();
7416 myComponents[i] = cn.flattenToShortString().intern();
7417 }
7418 mSetPackages = myPackages;
7419 mSetClasses = myClasses;
7420 mSetComponents = myComponents;
7421 } else {
7422 mSetPackages = null;
7423 mSetClasses = null;
7424 mSetComponents = null;
7425 }
7426 }
7427
7428 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7429 IOException {
7430 mShortActivity = parser.getAttributeValue(null, "name");
7431 mActivity = ComponentName.unflattenFromString(mShortActivity);
7432 if (mActivity == null) {
7433 mParseError = "Bad activity name " + mShortActivity;
7434 }
7435 String matchStr = parser.getAttributeValue(null, "match");
7436 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7437 String setCountStr = parser.getAttributeValue(null, "set");
7438 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7439
7440 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7441 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7442 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7443
7444 int setPos = 0;
7445
7446 int outerDepth = parser.getDepth();
7447 int type;
7448 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7449 && (type != XmlPullParser.END_TAG
7450 || parser.getDepth() > outerDepth)) {
7451 if (type == XmlPullParser.END_TAG
7452 || type == XmlPullParser.TEXT) {
7453 continue;
7454 }
7455
7456 String tagName = parser.getName();
7457 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7458 // + parser.getDepth() + " tag=" + tagName);
7459 if (tagName.equals("set")) {
7460 String name = parser.getAttributeValue(null, "name");
7461 if (name == null) {
7462 if (mParseError == null) {
7463 mParseError = "No name in set tag in preferred activity "
7464 + mShortActivity;
7465 }
7466 } else if (setPos >= setCount) {
7467 if (mParseError == null) {
7468 mParseError = "Too many set tags in preferred activity "
7469 + mShortActivity;
7470 }
7471 } else {
7472 ComponentName cn = ComponentName.unflattenFromString(name);
7473 if (cn == null) {
7474 if (mParseError == null) {
7475 mParseError = "Bad set name " + name + " in preferred activity "
7476 + mShortActivity;
7477 }
7478 } else {
7479 myPackages[setPos] = cn.getPackageName();
7480 myClasses[setPos] = cn.getClassName();
7481 myComponents[setPos] = name;
7482 setPos++;
7483 }
7484 }
7485 XmlUtils.skipCurrentTag(parser);
7486 } else if (tagName.equals("filter")) {
7487 //Log.i(TAG, "Starting to parse filter...");
7488 readFromXml(parser);
7489 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7490 // + parser.getDepth() + " tag=" + parser.getName());
7491 } else {
7492 reportSettingsProblem(Log.WARN,
7493 "Unknown element under <preferred-activities>: "
7494 + parser.getName());
7495 XmlUtils.skipCurrentTag(parser);
7496 }
7497 }
7498
7499 if (setPos != setCount) {
7500 if (mParseError == null) {
7501 mParseError = "Not enough set tags (expected " + setCount
7502 + " but found " + setPos + ") in " + mShortActivity;
7503 }
7504 }
7505
7506 mSetPackages = myPackages;
7507 mSetClasses = myClasses;
7508 mSetComponents = myComponents;
7509 }
7510
7511 public void writeToXml(XmlSerializer serializer) throws IOException {
7512 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7513 serializer.attribute(null, "name", mShortActivity);
7514 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7515 serializer.attribute(null, "set", Integer.toString(NS));
7516 for (int s=0; s<NS; s++) {
7517 serializer.startTag(null, "set");
7518 serializer.attribute(null, "name", mSetComponents[s]);
7519 serializer.endTag(null, "set");
7520 }
7521 serializer.startTag(null, "filter");
7522 super.writeToXml(serializer);
7523 serializer.endTag(null, "filter");
7524 }
7525
7526 boolean sameSet(List<ResolveInfo> query, int priority) {
7527 if (mSetPackages == null) return false;
7528 final int NQ = query.size();
7529 final int NS = mSetPackages.length;
7530 int numMatch = 0;
7531 for (int i=0; i<NQ; i++) {
7532 ResolveInfo ri = query.get(i);
7533 if (ri.priority != priority) continue;
7534 ActivityInfo ai = ri.activityInfo;
7535 boolean good = false;
7536 for (int j=0; j<NS; j++) {
7537 if (mSetPackages[j].equals(ai.packageName)
7538 && mSetClasses[j].equals(ai.name)) {
7539 numMatch++;
7540 good = true;
7541 break;
7542 }
7543 }
7544 if (!good) return false;
7545 }
7546 return numMatch == NS;
7547 }
7548 }
7549
7550 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007551 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007553 HashSet<String> grantedPermissions = new HashSet<String>();
7554 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007556 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007557 setFlags(pkgFlags);
7558 }
7559
7560 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007561 this.pkgFlags = pkgFlags & (
7562 ApplicationInfo.FLAG_SYSTEM |
7563 ApplicationInfo.FLAG_FORWARD_LOCK |
7564 ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007565 }
7566 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007568 /**
7569 * Settings base class for pending and resolved classes.
7570 */
7571 static class PackageSettingBase extends GrantedPermissions {
7572 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007573 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007574 File codePath;
7575 String codePathString;
7576 File resourcePath;
7577 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007578 private long timeStamp;
7579 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007580 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007581
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007582 boolean uidError;
7583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584 PackageSignatures signatures = new PackageSignatures();
7585
7586 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007587 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007589 /* Explicitly disabled components */
7590 HashSet<String> disabledComponents = new HashSet<String>(0);
7591 /* Explicitly enabled components */
7592 HashSet<String> enabledComponents = new HashSet<String>(0);
7593 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7594 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007595
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007596 PackageSettingBase origPackage;
7597
Jacek Surazski65e13172009-04-28 15:26:38 +02007598 /* package name of the app that installed this package */
7599 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007600
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007601 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007602 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007603 super(pkgFlags);
7604 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007605 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007606 init(codePath, resourcePath, pVersionCode);
7607 }
7608
7609 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007610 this.codePath = codePath;
7611 this.codePathString = codePath.toString();
7612 this.resourcePath = resourcePath;
7613 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007614 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007615 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007616
Jacek Surazski65e13172009-04-28 15:26:38 +02007617 public void setInstallerPackageName(String packageName) {
7618 installerPackageName = packageName;
7619 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007620
Jacek Surazski65e13172009-04-28 15:26:38 +02007621 String getInstallerPackageName() {
7622 return installerPackageName;
7623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007625 public void setInstallStatus(int newStatus) {
7626 installStatus = newStatus;
7627 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007629 public int getInstallStatus() {
7630 return installStatus;
7631 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007633 public void setTimeStamp(long newStamp) {
7634 if (newStamp != timeStamp) {
7635 timeStamp = newStamp;
7636 timeStampString = Long.toString(newStamp);
7637 }
7638 }
7639
7640 public void setTimeStamp(long newStamp, String newStampStr) {
7641 timeStamp = newStamp;
7642 timeStampString = newStampStr;
7643 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645 public long getTimeStamp() {
7646 return timeStamp;
7647 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649 public String getTimeStampStr() {
7650 return timeStampString;
7651 }
7652
7653 public void copyFrom(PackageSettingBase base) {
7654 grantedPermissions = base.grantedPermissions;
7655 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007657 timeStamp = base.timeStamp;
7658 timeStampString = base.timeStampString;
7659 signatures = base.signatures;
7660 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007661 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 disabledComponents = base.disabledComponents;
7663 enabledComponents = base.enabledComponents;
7664 enabled = base.enabled;
7665 installStatus = base.installStatus;
7666 }
7667
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007668 boolean enableComponentLP(String componentClassName) {
7669 boolean changed = disabledComponents.remove(componentClassName);
7670 changed |= enabledComponents.add(componentClassName);
7671 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007672 }
7673
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007674 boolean disableComponentLP(String componentClassName) {
7675 boolean changed = enabledComponents.remove(componentClassName);
7676 changed |= disabledComponents.add(componentClassName);
7677 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 }
7679
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007680 boolean restoreComponentLP(String componentClassName) {
7681 boolean changed = enabledComponents.remove(componentClassName);
7682 changed |= disabledComponents.remove(componentClassName);
7683 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007684 }
7685
7686 int currentEnabledStateLP(String componentName) {
7687 if (enabledComponents.contains(componentName)) {
7688 return COMPONENT_ENABLED_STATE_ENABLED;
7689 } else if (disabledComponents.contains(componentName)) {
7690 return COMPONENT_ENABLED_STATE_DISABLED;
7691 } else {
7692 return COMPONENT_ENABLED_STATE_DEFAULT;
7693 }
7694 }
7695 }
7696
7697 /**
7698 * Settings data for a particular package we know about.
7699 */
7700 static final class PackageSetting extends PackageSettingBase {
7701 int userId;
7702 PackageParser.Package pkg;
7703 SharedUserSetting sharedUser;
7704
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007705 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007706 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007707 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710 @Override
7711 public String toString() {
7712 return "PackageSetting{"
7713 + Integer.toHexString(System.identityHashCode(this))
7714 + " " + name + "/" + userId + "}";
7715 }
7716 }
7717
7718 /**
7719 * Settings data for a particular shared user ID we know about.
7720 */
7721 static final class SharedUserSetting extends GrantedPermissions {
7722 final String name;
7723 int userId;
7724 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7725 final PackageSignatures signatures = new PackageSignatures();
7726
7727 SharedUserSetting(String _name, int _pkgFlags) {
7728 super(_pkgFlags);
7729 name = _name;
7730 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007732 @Override
7733 public String toString() {
7734 return "SharedUserSetting{"
7735 + Integer.toHexString(System.identityHashCode(this))
7736 + " " + name + "/" + userId + "}";
7737 }
7738 }
7739
7740 /**
7741 * Holds information about dynamic settings.
7742 */
7743 private static final class Settings {
7744 private final File mSettingsFilename;
7745 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007746 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747 private final HashMap<String, PackageSetting> mPackages =
7748 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007749 // List of replaced system applications
7750 final HashMap<String, PackageSetting> mDisabledSysPackages =
7751 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007752
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007753 // These are the last platform API version we were using for
7754 // the apps installed on internal and external storage. It is
7755 // used to grant newer permissions one time during a system upgrade.
7756 int mInternalSdkPlatform;
7757 int mExternalSdkPlatform;
7758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007759 // The user's preferred activities associated with particular intent
7760 // filters.
7761 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7762 new IntentResolver<PreferredActivity, PreferredActivity>() {
7763 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007764 protected String packageForFilter(PreferredActivity filter) {
7765 return filter.mActivity.getPackageName();
7766 }
7767 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007768 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007769 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007770 out.print(prefix); out.print(
7771 Integer.toHexString(System.identityHashCode(filter)));
7772 out.print(' ');
7773 out.print(filter.mActivity.flattenToShortString());
7774 out.print(" match=0x");
7775 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007777 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007778 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007779 out.print(prefix); out.print(" ");
7780 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007781 }
7782 }
7783 }
7784 };
7785 private final HashMap<String, SharedUserSetting> mSharedUsers =
7786 new HashMap<String, SharedUserSetting>();
7787 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7788 private final SparseArray<Object> mOtherUserIds =
7789 new SparseArray<Object>();
7790
7791 // For reading/writing settings file.
7792 private final ArrayList<Signature> mPastSignatures =
7793 new ArrayList<Signature>();
7794
7795 // Mapping from permission names to info about them.
7796 final HashMap<String, BasePermission> mPermissions =
7797 new HashMap<String, BasePermission>();
7798
7799 // Mapping from permission tree names to info about them.
7800 final HashMap<String, BasePermission> mPermissionTrees =
7801 new HashMap<String, BasePermission>();
7802
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007803 // Packages that have been uninstalled and still need their external
7804 // storage data deleted.
7805 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7806
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007807 // Packages that have been renamed since they were first installed.
7808 // Keys are the new names of the packages, values are the original
7809 // names. The packages appear everwhere else under their original
7810 // names.
7811 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007813 private final StringBuilder mReadMessages = new StringBuilder();
7814
7815 private static final class PendingPackage extends PackageSettingBase {
7816 final int sharedId;
7817
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007818 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007819 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007820 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007821 this.sharedId = sharedId;
7822 }
7823 }
7824 private final ArrayList<PendingPackage> mPendingPackages
7825 = new ArrayList<PendingPackage>();
7826
7827 Settings() {
7828 File dataDir = Environment.getDataDirectory();
7829 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007830 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007831 systemDir.mkdirs();
7832 FileUtils.setPermissions(systemDir.toString(),
7833 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7834 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7835 -1, -1);
7836 mSettingsFilename = new File(systemDir, "packages.xml");
7837 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007838 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007839 }
7840
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007841 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007842 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 int pkgFlags, boolean create, boolean add) {
7844 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007845 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007846 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 return p;
7848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007849
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007850 PackageSetting peekPackageLP(String name) {
7851 return mPackages.get(name);
7852 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007853 PackageSetting p = mPackages.get(name);
7854 if (p != null && p.codePath.getPath().equals(codePath)) {
7855 return p;
7856 }
7857 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007858 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007859 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 void setInstallStatus(String pkgName, int status) {
7862 PackageSetting p = mPackages.get(pkgName);
7863 if(p != null) {
7864 if(p.getInstallStatus() != status) {
7865 p.setInstallStatus(status);
7866 }
7867 }
7868 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007869
Jacek Surazski65e13172009-04-28 15:26:38 +02007870 void setInstallerPackageName(String pkgName,
7871 String installerPkgName) {
7872 PackageSetting p = mPackages.get(pkgName);
7873 if(p != null) {
7874 p.setInstallerPackageName(installerPkgName);
7875 }
7876 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007877
Jacek Surazski65e13172009-04-28 15:26:38 +02007878 String getInstallerPackageName(String pkgName) {
7879 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007880 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007881 }
7882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 int getInstallStatus(String pkgName) {
7884 PackageSetting p = mPackages.get(pkgName);
7885 if(p != null) {
7886 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007888 return -1;
7889 }
7890
7891 SharedUserSetting getSharedUserLP(String name,
7892 int pkgFlags, boolean create) {
7893 SharedUserSetting s = mSharedUsers.get(name);
7894 if (s == null) {
7895 if (!create) {
7896 return null;
7897 }
7898 s = new SharedUserSetting(name, pkgFlags);
7899 if (MULTIPLE_APPLICATION_UIDS) {
7900 s.userId = newUserIdLP(s);
7901 } else {
7902 s.userId = FIRST_APPLICATION_UID;
7903 }
7904 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7905 // < 0 means we couldn't assign a userid; fall out and return
7906 // s, which is currently null
7907 if (s.userId >= 0) {
7908 mSharedUsers.put(name, s);
7909 }
7910 }
7911
7912 return s;
7913 }
7914
7915 int disableSystemPackageLP(String name) {
7916 PackageSetting p = mPackages.get(name);
7917 if(p == null) {
7918 Log.w(TAG, "Package:"+name+" is not an installed package");
7919 return -1;
7920 }
7921 PackageSetting dp = mDisabledSysPackages.get(name);
7922 // always make sure the system package code and resource paths dont change
7923 if(dp == null) {
7924 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7925 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7926 }
7927 mDisabledSysPackages.put(name, p);
7928 }
7929 return removePackageLP(name);
7930 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007932 PackageSetting enableSystemPackageLP(String name) {
7933 PackageSetting p = mDisabledSysPackages.get(name);
7934 if(p == null) {
7935 Log.w(TAG, "Package:"+name+" is not disabled");
7936 return null;
7937 }
7938 // Reset flag in ApplicationInfo object
7939 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7940 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7941 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007942 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007943 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007944 mDisabledSysPackages.remove(name);
7945 return ret;
7946 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007947
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007948 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007949 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007950 PackageSetting p = mPackages.get(name);
7951 if (p != null) {
7952 if (p.userId == uid) {
7953 return p;
7954 }
7955 reportSettingsProblem(Log.ERROR,
7956 "Adding duplicate package, keeping first: " + name);
7957 return null;
7958 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007959 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 p.userId = uid;
7961 if (addUserIdLP(uid, p, name)) {
7962 mPackages.put(name, p);
7963 return p;
7964 }
7965 return null;
7966 }
7967
7968 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7969 SharedUserSetting s = mSharedUsers.get(name);
7970 if (s != null) {
7971 if (s.userId == uid) {
7972 return s;
7973 }
7974 reportSettingsProblem(Log.ERROR,
7975 "Adding duplicate shared user, keeping first: " + name);
7976 return null;
7977 }
7978 s = new SharedUserSetting(name, pkgFlags);
7979 s.userId = uid;
7980 if (addUserIdLP(uid, s, name)) {
7981 mSharedUsers.put(name, s);
7982 return s;
7983 }
7984 return null;
7985 }
7986
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007987 // Transfer ownership of permissions from one package to another.
7988 private void transferPermissions(String origPkg, String newPkg) {
7989 // Transfer ownership of permissions to the new package.
7990 for (int i=0; i<2; i++) {
7991 HashMap<String, BasePermission> permissions =
7992 i == 0 ? mPermissionTrees : mPermissions;
7993 for (BasePermission bp : permissions.values()) {
7994 if (origPkg.equals(bp.sourcePackage)) {
7995 if (DEBUG_UPGRADE) Log.v(TAG,
7996 "Moving permission " + bp.name
7997 + " from pkg " + bp.sourcePackage
7998 + " to " + newPkg);
7999 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008000 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008001 bp.perm = null;
8002 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008003 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008004 }
8005 bp.uid = 0;
8006 bp.gids = null;
8007 }
8008 }
8009 }
8010 }
8011
8012 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008013 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008014 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 PackageSetting p = mPackages.get(name);
8016 if (p != null) {
8017 if (!p.codePath.equals(codePath)) {
8018 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008019 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008020 // This is an updated system app with versions in both system
8021 // and data partition. Just let the most recent version
8022 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008023 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008024 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008025 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008026 // Just a change in the code path is not an issue, but
8027 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008028 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008029 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008030 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008031 }
8032 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008033 reportSettingsProblem(Log.WARN,
8034 "Package " + name + " shared user changed from "
8035 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8036 + " to "
8037 + (sharedUser != null ? sharedUser.name : "<nothing>")
8038 + "; replacing with new");
8039 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008040 } else {
8041 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8042 // If what we are scanning is a system package, then
8043 // make it so, regardless of whether it was previously
8044 // installed only in the data partition.
8045 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008047 }
8048 }
8049 if (p == null) {
8050 // Create a new PackageSettings entry. this can end up here because
8051 // of code path mismatch or user id mismatch of an updated system partition
8052 if (!create) {
8053 return null;
8054 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008055 if (origPackage != null) {
8056 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008057 p = new PackageSetting(origPackage.name, name, codePath,
8058 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008059 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8060 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008061 // Note that we will retain the new package's signature so
8062 // that we can keep its data.
8063 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008064 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008065 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008066 p.sharedUser = origPackage.sharedUser;
8067 p.userId = origPackage.userId;
8068 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008069 mRenamedPackages.put(name, origPackage.name);
8070 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008071 // Update new package state.
8072 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008073 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008074 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008075 p.setTimeStamp(codePath.lastModified());
8076 p.sharedUser = sharedUser;
8077 if (sharedUser != null) {
8078 p.userId = sharedUser.userId;
8079 } else if (MULTIPLE_APPLICATION_UIDS) {
8080 // Clone the setting here for disabled system packages
8081 PackageSetting dis = mDisabledSysPackages.get(name);
8082 if (dis != null) {
8083 // For disabled packages a new setting is created
8084 // from the existing user id. This still has to be
8085 // added to list of user id's
8086 // Copy signatures from previous setting
8087 if (dis.signatures.mSignatures != null) {
8088 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8089 }
8090 p.userId = dis.userId;
8091 // Clone permissions
8092 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008093 // Clone component info
8094 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8095 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8096 // Add new setting to list of user ids
8097 addUserIdLP(p.userId, p, name);
8098 } else {
8099 // Assign new user id
8100 p.userId = newUserIdLP(p);
8101 }
8102 } else {
8103 p.userId = FIRST_APPLICATION_UID;
8104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008105 }
8106 if (p.userId < 0) {
8107 reportSettingsProblem(Log.WARN,
8108 "Package " + name + " could not be assigned a valid uid");
8109 return null;
8110 }
8111 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008112 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008113 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008114 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008115 }
8116 }
8117 return p;
8118 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008119
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008120 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008121 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008122 String codePath = pkg.applicationInfo.sourceDir;
8123 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008124 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008125 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008126 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008127 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008128 p.codePath = new File(codePath);
8129 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008130 }
8131 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008132 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008133 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008134 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008135 p.resourcePath = new File(resourcePath);
8136 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008137 }
8138 // Update version code if needed
8139 if (pkg.mVersionCode != p.versionCode) {
8140 p.versionCode = pkg.mVersionCode;
8141 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008142 // Update signatures if needed.
8143 if (p.signatures.mSignatures == null) {
8144 p.signatures.assignSignatures(pkg.mSignatures);
8145 }
8146 // If this app defines a shared user id initialize
8147 // the shared user signatures as well.
8148 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8149 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8150 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008151 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8152 }
8153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008154 // Utility method that adds a PackageSetting to mPackages and
8155 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008156 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 SharedUserSetting sharedUser) {
8158 mPackages.put(name, p);
8159 if (sharedUser != null) {
8160 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8161 reportSettingsProblem(Log.ERROR,
8162 "Package " + p.name + " was user "
8163 + p.sharedUser + " but is now " + sharedUser
8164 + "; I am not changing its files so it will probably fail!");
8165 p.sharedUser.packages.remove(p);
8166 } else if (p.userId != sharedUser.userId) {
8167 reportSettingsProblem(Log.ERROR,
8168 "Package " + p.name + " was user id " + p.userId
8169 + " but is now user " + sharedUser
8170 + " with id " + sharedUser.userId
8171 + "; I am not changing its files so it will probably fail!");
8172 }
8173
8174 sharedUser.packages.add(p);
8175 p.sharedUser = sharedUser;
8176 p.userId = sharedUser.userId;
8177 }
8178 }
8179
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008180 /*
8181 * Update the shared user setting when a package using
8182 * specifying the shared user id is removed. The gids
8183 * associated with each permission of the deleted package
8184 * are removed from the shared user's gid list only if its
8185 * not in use by other permissions of packages in the
8186 * shared user setting.
8187 */
8188 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008189 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008190 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008191 return;
8192 }
8193 // No sharedUserId
8194 if (deletedPs.sharedUser == null) {
8195 return;
8196 }
8197 SharedUserSetting sus = deletedPs.sharedUser;
8198 // Update permissions
8199 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8200 boolean used = false;
8201 if (!sus.grantedPermissions.contains (eachPerm)) {
8202 continue;
8203 }
8204 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008205 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008206 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008207 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008208 used = true;
8209 break;
8210 }
8211 }
8212 if (!used) {
8213 // can safely delete this permission from list
8214 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008215 }
8216 }
8217 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008218 int newGids[] = globalGids;
8219 for (String eachPerm : sus.grantedPermissions) {
8220 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008221 if (bp != null) {
8222 newGids = appendInts(newGids, bp.gids);
8223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008224 }
8225 sus.gids = newGids;
8226 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008228 private int removePackageLP(String name) {
8229 PackageSetting p = mPackages.get(name);
8230 if (p != null) {
8231 mPackages.remove(name);
8232 if (p.sharedUser != null) {
8233 p.sharedUser.packages.remove(p);
8234 if (p.sharedUser.packages.size() == 0) {
8235 mSharedUsers.remove(p.sharedUser.name);
8236 removeUserIdLP(p.sharedUser.userId);
8237 return p.sharedUser.userId;
8238 }
8239 } else {
8240 removeUserIdLP(p.userId);
8241 return p.userId;
8242 }
8243 }
8244 return -1;
8245 }
8246
8247 private boolean addUserIdLP(int uid, Object obj, Object name) {
8248 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8249 return false;
8250 }
8251
8252 if (uid >= FIRST_APPLICATION_UID) {
8253 int N = mUserIds.size();
8254 final int index = uid - FIRST_APPLICATION_UID;
8255 while (index >= N) {
8256 mUserIds.add(null);
8257 N++;
8258 }
8259 if (mUserIds.get(index) != null) {
8260 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008261 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008262 + " name=" + name);
8263 return false;
8264 }
8265 mUserIds.set(index, obj);
8266 } else {
8267 if (mOtherUserIds.get(uid) != null) {
8268 reportSettingsProblem(Log.ERROR,
8269 "Adding duplicate shared id: " + uid
8270 + " name=" + name);
8271 return false;
8272 }
8273 mOtherUserIds.put(uid, obj);
8274 }
8275 return true;
8276 }
8277
8278 public Object getUserIdLP(int uid) {
8279 if (uid >= FIRST_APPLICATION_UID) {
8280 int N = mUserIds.size();
8281 final int index = uid - FIRST_APPLICATION_UID;
8282 return index < N ? mUserIds.get(index) : null;
8283 } else {
8284 return mOtherUserIds.get(uid);
8285 }
8286 }
8287
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008288 private Set<String> findPackagesWithFlag(int flag) {
8289 Set<String> ret = new HashSet<String>();
8290 for (PackageSetting ps : mPackages.values()) {
8291 // Has to match atleast all the flag bits set on flag
8292 if ((ps.pkgFlags & flag) == flag) {
8293 ret.add(ps.name);
8294 }
8295 }
8296 return ret;
8297 }
8298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008299 private void removeUserIdLP(int uid) {
8300 if (uid >= FIRST_APPLICATION_UID) {
8301 int N = mUserIds.size();
8302 final int index = uid - FIRST_APPLICATION_UID;
8303 if (index < N) mUserIds.set(index, null);
8304 } else {
8305 mOtherUserIds.remove(uid);
8306 }
8307 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008309 void writeLP() {
8310 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8311
8312 // Keep the old settings around until we know the new ones have
8313 // been successfully written.
8314 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008315 // Presence of backup settings file indicates that we failed
8316 // to persist settings earlier. So preserve the older
8317 // backup for future reference since the current settings
8318 // might have been corrupted.
8319 if (!mBackupSettingsFilename.exists()) {
8320 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008321 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008322 return;
8323 }
8324 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008325 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008326 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008328 }
8329
8330 mPastSignatures.clear();
8331
8332 try {
8333 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8334
8335 //XmlSerializer serializer = XmlUtils.serializerInstance();
8336 XmlSerializer serializer = new FastXmlSerializer();
8337 serializer.setOutput(str, "utf-8");
8338 serializer.startDocument(null, true);
8339 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8340
8341 serializer.startTag(null, "packages");
8342
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008343 serializer.startTag(null, "last-platform-version");
8344 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8345 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8346 serializer.endTag(null, "last-platform-version");
8347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008348 serializer.startTag(null, "permission-trees");
8349 for (BasePermission bp : mPermissionTrees.values()) {
8350 writePermission(serializer, bp);
8351 }
8352 serializer.endTag(null, "permission-trees");
8353
8354 serializer.startTag(null, "permissions");
8355 for (BasePermission bp : mPermissions.values()) {
8356 writePermission(serializer, bp);
8357 }
8358 serializer.endTag(null, "permissions");
8359
8360 for (PackageSetting pkg : mPackages.values()) {
8361 writePackage(serializer, pkg);
8362 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008364 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8365 writeDisabledSysPackage(serializer, pkg);
8366 }
8367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008368 serializer.startTag(null, "preferred-activities");
8369 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8370 serializer.startTag(null, "item");
8371 pa.writeToXml(serializer);
8372 serializer.endTag(null, "item");
8373 }
8374 serializer.endTag(null, "preferred-activities");
8375
8376 for (SharedUserSetting usr : mSharedUsers.values()) {
8377 serializer.startTag(null, "shared-user");
8378 serializer.attribute(null, "name", usr.name);
8379 serializer.attribute(null, "userId",
8380 Integer.toString(usr.userId));
8381 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8382 serializer.startTag(null, "perms");
8383 for (String name : usr.grantedPermissions) {
8384 serializer.startTag(null, "item");
8385 serializer.attribute(null, "name", name);
8386 serializer.endTag(null, "item");
8387 }
8388 serializer.endTag(null, "perms");
8389 serializer.endTag(null, "shared-user");
8390 }
8391
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008392 if (mPackagesToBeCleaned.size() > 0) {
8393 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8394 serializer.startTag(null, "cleaning-package");
8395 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8396 serializer.endTag(null, "cleaning-package");
8397 }
8398 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008399
8400 if (mRenamedPackages.size() > 0) {
8401 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8402 serializer.startTag(null, "renamed-package");
8403 serializer.attribute(null, "new", e.getKey());
8404 serializer.attribute(null, "old", e.getValue());
8405 serializer.endTag(null, "renamed-package");
8406 }
8407 }
8408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 serializer.endTag(null, "packages");
8410
8411 serializer.endDocument();
8412
8413 str.flush();
8414 str.close();
8415
8416 // New settings successfully written, old ones are no longer
8417 // needed.
8418 mBackupSettingsFilename.delete();
8419 FileUtils.setPermissions(mSettingsFilename.toString(),
8420 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8421 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8422 |FileUtils.S_IROTH,
8423 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008424
8425 // Write package list file now, use a JournaledFile.
8426 //
8427 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8428 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8429
8430 str = new FileOutputStream(journal.chooseForWrite());
8431 try {
8432 StringBuilder sb = new StringBuilder();
8433 for (PackageSetting pkg : mPackages.values()) {
8434 ApplicationInfo ai = pkg.pkg.applicationInfo;
8435 String dataPath = ai.dataDir;
8436 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8437
8438 // Avoid any application that has a space in its path
8439 // or that is handled by the system.
8440 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8441 continue;
8442
8443 // we store on each line the following information for now:
8444 //
8445 // pkgName - package name
8446 // userId - application-specific user id
8447 // debugFlag - 0 or 1 if the package is debuggable.
8448 // dataPath - path to package's data path
8449 //
8450 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8451 //
8452 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8453 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8454 // system/core/run-as/run-as.c
8455 //
8456 sb.setLength(0);
8457 sb.append(ai.packageName);
8458 sb.append(" ");
8459 sb.append((int)ai.uid);
8460 sb.append(isDebug ? " 1 " : " 0 ");
8461 sb.append(dataPath);
8462 sb.append("\n");
8463 str.write(sb.toString().getBytes());
8464 }
8465 str.flush();
8466 str.close();
8467 journal.commit();
8468 }
8469 catch (Exception e) {
8470 journal.rollback();
8471 }
8472
8473 FileUtils.setPermissions(mPackageListFilename.toString(),
8474 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8475 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8476 |FileUtils.S_IROTH,
8477 -1, -1);
8478
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008479 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008480
8481 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008482 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 -08008483 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008484 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 -08008485 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008486 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008487 if (mSettingsFilename.exists()) {
8488 if (!mSettingsFilename.delete()) {
8489 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8490 }
8491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008492 //Debug.stopMethodTracing();
8493 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008494
8495 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008496 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008497 serializer.startTag(null, "updated-package");
8498 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008499 if (pkg.realName != null) {
8500 serializer.attribute(null, "realName", pkg.realName);
8501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502 serializer.attribute(null, "codePath", pkg.codePathString);
8503 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008504 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008505 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8506 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8507 }
8508 if (pkg.sharedUser == null) {
8509 serializer.attribute(null, "userId",
8510 Integer.toString(pkg.userId));
8511 } else {
8512 serializer.attribute(null, "sharedUserId",
8513 Integer.toString(pkg.userId));
8514 }
8515 serializer.startTag(null, "perms");
8516 if (pkg.sharedUser == null) {
8517 // If this is a shared user, the permissions will
8518 // be written there. We still need to write an
8519 // empty permissions list so permissionsFixed will
8520 // be set.
8521 for (final String name : pkg.grantedPermissions) {
8522 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008523 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008524 // We only need to write signature or system permissions but this wont
8525 // match the semantics of grantedPermissions. So write all permissions.
8526 serializer.startTag(null, "item");
8527 serializer.attribute(null, "name", name);
8528 serializer.endTag(null, "item");
8529 }
8530 }
8531 }
8532 serializer.endTag(null, "perms");
8533 serializer.endTag(null, "updated-package");
8534 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008535
8536 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008537 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008538 serializer.startTag(null, "package");
8539 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008540 if (pkg.realName != null) {
8541 serializer.attribute(null, "realName", pkg.realName);
8542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008543 serializer.attribute(null, "codePath", pkg.codePathString);
8544 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8545 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8546 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008547 serializer.attribute(null, "flags",
8548 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008549 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008550 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008551 if (pkg.sharedUser == null) {
8552 serializer.attribute(null, "userId",
8553 Integer.toString(pkg.userId));
8554 } else {
8555 serializer.attribute(null, "sharedUserId",
8556 Integer.toString(pkg.userId));
8557 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008558 if (pkg.uidError) {
8559 serializer.attribute(null, "uidError", "true");
8560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008561 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8562 serializer.attribute(null, "enabled",
8563 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8564 ? "true" : "false");
8565 }
8566 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8567 serializer.attribute(null, "installStatus", "false");
8568 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008569 if (pkg.installerPackageName != null) {
8570 serializer.attribute(null, "installer", pkg.installerPackageName);
8571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008572 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8573 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8574 serializer.startTag(null, "perms");
8575 if (pkg.sharedUser == null) {
8576 // If this is a shared user, the permissions will
8577 // be written there. We still need to write an
8578 // empty permissions list so permissionsFixed will
8579 // be set.
8580 for (final String name : pkg.grantedPermissions) {
8581 serializer.startTag(null, "item");
8582 serializer.attribute(null, "name", name);
8583 serializer.endTag(null, "item");
8584 }
8585 }
8586 serializer.endTag(null, "perms");
8587 }
8588 if (pkg.disabledComponents.size() > 0) {
8589 serializer.startTag(null, "disabled-components");
8590 for (final String name : pkg.disabledComponents) {
8591 serializer.startTag(null, "item");
8592 serializer.attribute(null, "name", name);
8593 serializer.endTag(null, "item");
8594 }
8595 serializer.endTag(null, "disabled-components");
8596 }
8597 if (pkg.enabledComponents.size() > 0) {
8598 serializer.startTag(null, "enabled-components");
8599 for (final String name : pkg.enabledComponents) {
8600 serializer.startTag(null, "item");
8601 serializer.attribute(null, "name", name);
8602 serializer.endTag(null, "item");
8603 }
8604 serializer.endTag(null, "enabled-components");
8605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008607 serializer.endTag(null, "package");
8608 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008610 void writePermission(XmlSerializer serializer, BasePermission bp)
8611 throws XmlPullParserException, java.io.IOException {
8612 if (bp.type != BasePermission.TYPE_BUILTIN
8613 && bp.sourcePackage != null) {
8614 serializer.startTag(null, "item");
8615 serializer.attribute(null, "name", bp.name);
8616 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008617 if (bp.protectionLevel !=
8618 PermissionInfo.PROTECTION_NORMAL) {
8619 serializer.attribute(null, "protection",
8620 Integer.toString(bp.protectionLevel));
8621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 if (DEBUG_SETTINGS) Log.v(TAG,
8623 "Writing perm: name=" + bp.name + " type=" + bp.type);
8624 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8625 PermissionInfo pi = bp.perm != null ? bp.perm.info
8626 : bp.pendingInfo;
8627 if (pi != null) {
8628 serializer.attribute(null, "type", "dynamic");
8629 if (pi.icon != 0) {
8630 serializer.attribute(null, "icon",
8631 Integer.toString(pi.icon));
8632 }
8633 if (pi.nonLocalizedLabel != null) {
8634 serializer.attribute(null, "label",
8635 pi.nonLocalizedLabel.toString());
8636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008637 }
8638 }
8639 serializer.endTag(null, "item");
8640 }
8641 }
8642
8643 String getReadMessagesLP() {
8644 return mReadMessages.toString();
8645 }
8646
Oscar Montemayora8529f62009-11-18 10:14:20 -08008647 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008648 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8649 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008650 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008651 while(its.hasNext()) {
8652 String key = its.next();
8653 PackageSetting ps = mPackages.get(key);
8654 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008655 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 }
8657 }
8658 return ret;
8659 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 boolean readLP() {
8662 FileInputStream str = null;
8663 if (mBackupSettingsFilename.exists()) {
8664 try {
8665 str = new FileInputStream(mBackupSettingsFilename);
8666 mReadMessages.append("Reading from backup settings file\n");
8667 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008668 if (mSettingsFilename.exists()) {
8669 // If both the backup and settings file exist, we
8670 // ignore the settings since it might have been
8671 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008672 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008673 mSettingsFilename.delete();
8674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008675 } catch (java.io.IOException e) {
8676 // We'll try for the normal settings file.
8677 }
8678 }
8679
8680 mPastSignatures.clear();
8681
8682 try {
8683 if (str == null) {
8684 if (!mSettingsFilename.exists()) {
8685 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008686 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008687 return false;
8688 }
8689 str = new FileInputStream(mSettingsFilename);
8690 }
8691 XmlPullParser parser = Xml.newPullParser();
8692 parser.setInput(str, null);
8693
8694 int type;
8695 while ((type=parser.next()) != XmlPullParser.START_TAG
8696 && type != XmlPullParser.END_DOCUMENT) {
8697 ;
8698 }
8699
8700 if (type != XmlPullParser.START_TAG) {
8701 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008702 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008703 return false;
8704 }
8705
8706 int outerDepth = parser.getDepth();
8707 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8708 && (type != XmlPullParser.END_TAG
8709 || parser.getDepth() > outerDepth)) {
8710 if (type == XmlPullParser.END_TAG
8711 || type == XmlPullParser.TEXT) {
8712 continue;
8713 }
8714
8715 String tagName = parser.getName();
8716 if (tagName.equals("package")) {
8717 readPackageLP(parser);
8718 } else if (tagName.equals("permissions")) {
8719 readPermissionsLP(mPermissions, parser);
8720 } else if (tagName.equals("permission-trees")) {
8721 readPermissionsLP(mPermissionTrees, parser);
8722 } else if (tagName.equals("shared-user")) {
8723 readSharedUserLP(parser);
8724 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008725 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008726 } else if (tagName.equals("preferred-activities")) {
8727 readPreferredActivitiesLP(parser);
8728 } else if(tagName.equals("updated-package")) {
8729 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008730 } else if (tagName.equals("cleaning-package")) {
8731 String name = parser.getAttributeValue(null, "name");
8732 if (name != null) {
8733 mPackagesToBeCleaned.add(name);
8734 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008735 } else if (tagName.equals("renamed-package")) {
8736 String nname = parser.getAttributeValue(null, "new");
8737 String oname = parser.getAttributeValue(null, "old");
8738 if (nname != null && oname != null) {
8739 mRenamedPackages.put(nname, oname);
8740 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008741 } else if (tagName.equals("last-platform-version")) {
8742 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8743 try {
8744 String internal = parser.getAttributeValue(null, "internal");
8745 if (internal != null) {
8746 mInternalSdkPlatform = Integer.parseInt(internal);
8747 }
8748 String external = parser.getAttributeValue(null, "external");
8749 if (external != null) {
8750 mInternalSdkPlatform = Integer.parseInt(external);
8751 }
8752 } catch (NumberFormatException e) {
8753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008754 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008755 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008756 + parser.getName());
8757 XmlUtils.skipCurrentTag(parser);
8758 }
8759 }
8760
8761 str.close();
8762
8763 } catch(XmlPullParserException e) {
8764 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008765 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766
8767 } catch(java.io.IOException e) {
8768 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008769 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008770
8771 }
8772
8773 int N = mPendingPackages.size();
8774 for (int i=0; i<N; i++) {
8775 final PendingPackage pp = mPendingPackages.get(i);
8776 Object idObj = getUserIdLP(pp.sharedId);
8777 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008778 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008779 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008780 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008781 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008782 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008783 + pp.name);
8784 continue;
8785 }
8786 p.copyFrom(pp);
8787 } else if (idObj != null) {
8788 String msg = "Bad package setting: package " + pp.name
8789 + " has shared uid " + pp.sharedId
8790 + " that is not a shared uid\n";
8791 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008792 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008793 } else {
8794 String msg = "Bad package setting: package " + pp.name
8795 + " has shared uid " + pp.sharedId
8796 + " that is not defined\n";
8797 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008798 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008799 }
8800 }
8801 mPendingPackages.clear();
8802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008803 mReadMessages.append("Read completed successfully: "
8804 + mPackages.size() + " packages, "
8805 + mSharedUsers.size() + " shared uids\n");
8806
8807 return true;
8808 }
8809
8810 private int readInt(XmlPullParser parser, String ns, String name,
8811 int defValue) {
8812 String v = parser.getAttributeValue(ns, name);
8813 try {
8814 if (v == null) {
8815 return defValue;
8816 }
8817 return Integer.parseInt(v);
8818 } catch (NumberFormatException e) {
8819 reportSettingsProblem(Log.WARN,
8820 "Error in package manager settings: attribute " +
8821 name + " has bad integer value " + v + " at "
8822 + parser.getPositionDescription());
8823 }
8824 return defValue;
8825 }
8826
8827 private void readPermissionsLP(HashMap<String, BasePermission> out,
8828 XmlPullParser parser)
8829 throws IOException, XmlPullParserException {
8830 int outerDepth = parser.getDepth();
8831 int type;
8832 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8833 && (type != XmlPullParser.END_TAG
8834 || parser.getDepth() > outerDepth)) {
8835 if (type == XmlPullParser.END_TAG
8836 || type == XmlPullParser.TEXT) {
8837 continue;
8838 }
8839
8840 String tagName = parser.getName();
8841 if (tagName.equals("item")) {
8842 String name = parser.getAttributeValue(null, "name");
8843 String sourcePackage = parser.getAttributeValue(null, "package");
8844 String ptype = parser.getAttributeValue(null, "type");
8845 if (name != null && sourcePackage != null) {
8846 boolean dynamic = "dynamic".equals(ptype);
8847 BasePermission bp = new BasePermission(name, sourcePackage,
8848 dynamic
8849 ? BasePermission.TYPE_DYNAMIC
8850 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008851 bp.protectionLevel = readInt(parser, null, "protection",
8852 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 if (dynamic) {
8854 PermissionInfo pi = new PermissionInfo();
8855 pi.packageName = sourcePackage.intern();
8856 pi.name = name.intern();
8857 pi.icon = readInt(parser, null, "icon", 0);
8858 pi.nonLocalizedLabel = parser.getAttributeValue(
8859 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008860 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008861 bp.pendingInfo = pi;
8862 }
8863 out.put(bp.name, bp);
8864 } else {
8865 reportSettingsProblem(Log.WARN,
8866 "Error in package manager settings: permissions has"
8867 + " no name at " + parser.getPositionDescription());
8868 }
8869 } else {
8870 reportSettingsProblem(Log.WARN,
8871 "Unknown element reading permissions: "
8872 + parser.getName() + " at "
8873 + parser.getPositionDescription());
8874 }
8875 XmlUtils.skipCurrentTag(parser);
8876 }
8877 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008879 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008880 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008881 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008882 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 String codePathStr = parser.getAttributeValue(null, "codePath");
8884 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008885 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008886 resourcePathStr = codePathStr;
8887 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008888 String version = parser.getAttributeValue(null, "version");
8889 int versionCode = 0;
8890 if (version != null) {
8891 try {
8892 versionCode = Integer.parseInt(version);
8893 } catch (NumberFormatException e) {
8894 }
8895 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008897 int pkgFlags = 0;
8898 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008899 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008900 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008901 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008902 String timeStampStr = parser.getAttributeValue(null, "ts");
8903 if (timeStampStr != null) {
8904 try {
8905 long timeStamp = Long.parseLong(timeStampStr);
8906 ps.setTimeStamp(timeStamp, timeStampStr);
8907 } catch (NumberFormatException e) {
8908 }
8909 }
8910 String idStr = parser.getAttributeValue(null, "userId");
8911 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8912 if(ps.userId <= 0) {
8913 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8914 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8915 }
8916 int outerDepth = parser.getDepth();
8917 int type;
8918 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8919 && (type != XmlPullParser.END_TAG
8920 || parser.getDepth() > outerDepth)) {
8921 if (type == XmlPullParser.END_TAG
8922 || type == XmlPullParser.TEXT) {
8923 continue;
8924 }
8925
8926 String tagName = parser.getName();
8927 if (tagName.equals("perms")) {
8928 readGrantedPermissionsLP(parser,
8929 ps.grantedPermissions);
8930 } else {
8931 reportSettingsProblem(Log.WARN,
8932 "Unknown element under <updated-package>: "
8933 + parser.getName());
8934 XmlUtils.skipCurrentTag(parser);
8935 }
8936 }
8937 mDisabledSysPackages.put(name, ps);
8938 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008940 private void readPackageLP(XmlPullParser parser)
8941 throws XmlPullParserException, IOException {
8942 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008943 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 String idStr = null;
8945 String sharedIdStr = null;
8946 String codePathStr = null;
8947 String resourcePathStr = null;
8948 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008949 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008950 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008951 int pkgFlags = 0;
8952 String timeStampStr;
8953 long timeStamp = 0;
8954 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008955 String version = null;
8956 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 try {
8958 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008959 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008961 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008962 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8963 codePathStr = parser.getAttributeValue(null, "codePath");
8964 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008965 version = parser.getAttributeValue(null, "version");
8966 if (version != null) {
8967 try {
8968 versionCode = Integer.parseInt(version);
8969 } catch (NumberFormatException e) {
8970 }
8971 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008972 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008973
8974 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008975 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008976 try {
8977 pkgFlags = Integer.parseInt(systemStr);
8978 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008979 }
8980 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008981 // For backward compatibility
8982 systemStr = parser.getAttributeValue(null, "system");
8983 if (systemStr != null) {
8984 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8985 } else {
8986 // Old settings that don't specify system... just treat
8987 // them as system, good enough.
8988 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008990 }
8991 timeStampStr = parser.getAttributeValue(null, "ts");
8992 if (timeStampStr != null) {
8993 try {
8994 timeStamp = Long.parseLong(timeStampStr);
8995 } catch (NumberFormatException e) {
8996 }
8997 }
8998 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8999 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9000 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9001 if (resourcePathStr == null) {
9002 resourcePathStr = codePathStr;
9003 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009004 if (realName != null) {
9005 realName = realName.intern();
9006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009007 if (name == null) {
9008 reportSettingsProblem(Log.WARN,
9009 "Error in package manager settings: <package> has no name at "
9010 + parser.getPositionDescription());
9011 } else if (codePathStr == null) {
9012 reportSettingsProblem(Log.WARN,
9013 "Error in package manager settings: <package> has no codePath at "
9014 + parser.getPositionDescription());
9015 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009016 packageSetting = addPackageLP(name.intern(), realName,
9017 new File(codePathStr), new File(resourcePathStr),
9018 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009019 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9020 + ": userId=" + userId + " pkg=" + packageSetting);
9021 if (packageSetting == null) {
9022 reportSettingsProblem(Log.ERROR,
9023 "Failure adding uid " + userId
9024 + " while parsing settings at "
9025 + parser.getPositionDescription());
9026 } else {
9027 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9028 }
9029 } else if (sharedIdStr != null) {
9030 userId = sharedIdStr != null
9031 ? Integer.parseInt(sharedIdStr) : 0;
9032 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009033 packageSetting = new PendingPackage(name.intern(), realName,
9034 new File(codePathStr), new File(resourcePathStr),
9035 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009036 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9037 mPendingPackages.add((PendingPackage) packageSetting);
9038 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9039 + ": sharedUserId=" + userId + " pkg="
9040 + packageSetting);
9041 } else {
9042 reportSettingsProblem(Log.WARN,
9043 "Error in package manager settings: package "
9044 + name + " has bad sharedId " + sharedIdStr
9045 + " at " + parser.getPositionDescription());
9046 }
9047 } else {
9048 reportSettingsProblem(Log.WARN,
9049 "Error in package manager settings: package "
9050 + name + " has bad userId " + idStr + " at "
9051 + parser.getPositionDescription());
9052 }
9053 } catch (NumberFormatException e) {
9054 reportSettingsProblem(Log.WARN,
9055 "Error in package manager settings: package "
9056 + name + " has bad userId " + idStr + " at "
9057 + parser.getPositionDescription());
9058 }
9059 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009060 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009061 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009062 final String enabledStr = parser.getAttributeValue(null, "enabled");
9063 if (enabledStr != null) {
9064 if (enabledStr.equalsIgnoreCase("true")) {
9065 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9066 } else if (enabledStr.equalsIgnoreCase("false")) {
9067 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9068 } else if (enabledStr.equalsIgnoreCase("default")) {
9069 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9070 } else {
9071 reportSettingsProblem(Log.WARN,
9072 "Error in package manager settings: package "
9073 + name + " has bad enabled value: " + idStr
9074 + " at " + parser.getPositionDescription());
9075 }
9076 } else {
9077 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9078 }
9079 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9080 if (installStatusStr != null) {
9081 if (installStatusStr.equalsIgnoreCase("false")) {
9082 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9083 } else {
9084 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9085 }
9086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009088 int outerDepth = parser.getDepth();
9089 int type;
9090 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9091 && (type != XmlPullParser.END_TAG
9092 || parser.getDepth() > outerDepth)) {
9093 if (type == XmlPullParser.END_TAG
9094 || type == XmlPullParser.TEXT) {
9095 continue;
9096 }
9097
9098 String tagName = parser.getName();
9099 if (tagName.equals("disabled-components")) {
9100 readDisabledComponentsLP(packageSetting, parser);
9101 } else if (tagName.equals("enabled-components")) {
9102 readEnabledComponentsLP(packageSetting, parser);
9103 } else if (tagName.equals("sigs")) {
9104 packageSetting.signatures.readXml(parser, mPastSignatures);
9105 } else if (tagName.equals("perms")) {
9106 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009107 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009108 packageSetting.permissionsFixed = true;
9109 } else {
9110 reportSettingsProblem(Log.WARN,
9111 "Unknown element under <package>: "
9112 + parser.getName());
9113 XmlUtils.skipCurrentTag(parser);
9114 }
9115 }
9116 } else {
9117 XmlUtils.skipCurrentTag(parser);
9118 }
9119 }
9120
9121 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9122 XmlPullParser parser)
9123 throws IOException, XmlPullParserException {
9124 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("item")) {
9136 String name = parser.getAttributeValue(null, "name");
9137 if (name != null) {
9138 packageSetting.disabledComponents.add(name.intern());
9139 } else {
9140 reportSettingsProblem(Log.WARN,
9141 "Error in package manager settings: <disabled-components> has"
9142 + " no name at " + parser.getPositionDescription());
9143 }
9144 } else {
9145 reportSettingsProblem(Log.WARN,
9146 "Unknown element under <disabled-components>: "
9147 + parser.getName());
9148 }
9149 XmlUtils.skipCurrentTag(parser);
9150 }
9151 }
9152
9153 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9154 XmlPullParser parser)
9155 throws IOException, XmlPullParserException {
9156 int outerDepth = parser.getDepth();
9157 int type;
9158 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9159 && (type != XmlPullParser.END_TAG
9160 || parser.getDepth() > outerDepth)) {
9161 if (type == XmlPullParser.END_TAG
9162 || type == XmlPullParser.TEXT) {
9163 continue;
9164 }
9165
9166 String tagName = parser.getName();
9167 if (tagName.equals("item")) {
9168 String name = parser.getAttributeValue(null, "name");
9169 if (name != null) {
9170 packageSetting.enabledComponents.add(name.intern());
9171 } else {
9172 reportSettingsProblem(Log.WARN,
9173 "Error in package manager settings: <enabled-components> has"
9174 + " no name at " + parser.getPositionDescription());
9175 }
9176 } else {
9177 reportSettingsProblem(Log.WARN,
9178 "Unknown element under <enabled-components>: "
9179 + parser.getName());
9180 }
9181 XmlUtils.skipCurrentTag(parser);
9182 }
9183 }
9184
9185 private void readSharedUserLP(XmlPullParser parser)
9186 throws XmlPullParserException, IOException {
9187 String name = null;
9188 String idStr = null;
9189 int pkgFlags = 0;
9190 SharedUserSetting su = null;
9191 try {
9192 name = parser.getAttributeValue(null, "name");
9193 idStr = parser.getAttributeValue(null, "userId");
9194 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9195 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9196 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9197 }
9198 if (name == null) {
9199 reportSettingsProblem(Log.WARN,
9200 "Error in package manager settings: <shared-user> has no name at "
9201 + parser.getPositionDescription());
9202 } else if (userId == 0) {
9203 reportSettingsProblem(Log.WARN,
9204 "Error in package manager settings: shared-user "
9205 + name + " has bad userId " + idStr + " at "
9206 + parser.getPositionDescription());
9207 } else {
9208 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9209 reportSettingsProblem(Log.ERROR,
9210 "Occurred while parsing settings at "
9211 + parser.getPositionDescription());
9212 }
9213 }
9214 } catch (NumberFormatException e) {
9215 reportSettingsProblem(Log.WARN,
9216 "Error in package manager settings: package "
9217 + name + " has bad userId " + idStr + " at "
9218 + parser.getPositionDescription());
9219 };
9220
9221 if (su != null) {
9222 int outerDepth = parser.getDepth();
9223 int type;
9224 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9225 && (type != XmlPullParser.END_TAG
9226 || parser.getDepth() > outerDepth)) {
9227 if (type == XmlPullParser.END_TAG
9228 || type == XmlPullParser.TEXT) {
9229 continue;
9230 }
9231
9232 String tagName = parser.getName();
9233 if (tagName.equals("sigs")) {
9234 su.signatures.readXml(parser, mPastSignatures);
9235 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009236 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009237 } else {
9238 reportSettingsProblem(Log.WARN,
9239 "Unknown element under <shared-user>: "
9240 + parser.getName());
9241 XmlUtils.skipCurrentTag(parser);
9242 }
9243 }
9244
9245 } else {
9246 XmlUtils.skipCurrentTag(parser);
9247 }
9248 }
9249
9250 private void readGrantedPermissionsLP(XmlPullParser parser,
9251 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9252 int outerDepth = parser.getDepth();
9253 int type;
9254 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9255 && (type != XmlPullParser.END_TAG
9256 || parser.getDepth() > outerDepth)) {
9257 if (type == XmlPullParser.END_TAG
9258 || type == XmlPullParser.TEXT) {
9259 continue;
9260 }
9261
9262 String tagName = parser.getName();
9263 if (tagName.equals("item")) {
9264 String name = parser.getAttributeValue(null, "name");
9265 if (name != null) {
9266 outPerms.add(name.intern());
9267 } else {
9268 reportSettingsProblem(Log.WARN,
9269 "Error in package manager settings: <perms> has"
9270 + " no name at " + parser.getPositionDescription());
9271 }
9272 } else {
9273 reportSettingsProblem(Log.WARN,
9274 "Unknown element under <perms>: "
9275 + parser.getName());
9276 }
9277 XmlUtils.skipCurrentTag(parser);
9278 }
9279 }
9280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009281 private void readPreferredActivitiesLP(XmlPullParser parser)
9282 throws XmlPullParserException, IOException {
9283 int outerDepth = parser.getDepth();
9284 int type;
9285 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9286 && (type != XmlPullParser.END_TAG
9287 || parser.getDepth() > outerDepth)) {
9288 if (type == XmlPullParser.END_TAG
9289 || type == XmlPullParser.TEXT) {
9290 continue;
9291 }
9292
9293 String tagName = parser.getName();
9294 if (tagName.equals("item")) {
9295 PreferredActivity pa = new PreferredActivity(parser);
9296 if (pa.mParseError == null) {
9297 mPreferredActivities.addFilter(pa);
9298 } else {
9299 reportSettingsProblem(Log.WARN,
9300 "Error in package manager settings: <preferred-activity> "
9301 + pa.mParseError + " at "
9302 + parser.getPositionDescription());
9303 }
9304 } else {
9305 reportSettingsProblem(Log.WARN,
9306 "Unknown element under <preferred-activities>: "
9307 + parser.getName());
9308 XmlUtils.skipCurrentTag(parser);
9309 }
9310 }
9311 }
9312
9313 // Returns -1 if we could not find an available UserId to assign
9314 private int newUserIdLP(Object obj) {
9315 // Let's be stupidly inefficient for now...
9316 final int N = mUserIds.size();
9317 for (int i=0; i<N; i++) {
9318 if (mUserIds.get(i) == null) {
9319 mUserIds.set(i, obj);
9320 return FIRST_APPLICATION_UID + i;
9321 }
9322 }
9323
9324 // None left?
9325 if (N >= MAX_APPLICATION_UIDS) {
9326 return -1;
9327 }
9328
9329 mUserIds.add(obj);
9330 return FIRST_APPLICATION_UID + N;
9331 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009333 public PackageSetting getDisabledSystemPkg(String name) {
9334 synchronized(mPackages) {
9335 PackageSetting ps = mDisabledSysPackages.get(name);
9336 return ps;
9337 }
9338 }
9339
9340 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9341 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9342 if (Config.LOGV) {
9343 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9344 + " componentName = " + componentInfo.name);
9345 Log.v(TAG, "enabledComponents: "
9346 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9347 Log.v(TAG, "disabledComponents: "
9348 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9349 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009350 if (packageSettings == null) {
9351 if (false) {
9352 Log.w(TAG, "WAITING FOR DEBUGGER");
9353 Debug.waitForDebugger();
9354 Log.i(TAG, "We will crash!");
9355 }
9356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009357 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9358 || ((componentInfo.enabled
9359 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9360 || (componentInfo.applicationInfo.enabled
9361 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9362 && !packageSettings.disabledComponents.contains(componentInfo.name))
9363 || packageSettings.enabledComponents.contains(componentInfo.name));
9364 }
9365 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009366
9367 // ------- apps on sdcard specific code -------
9368 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009369 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009370 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009371 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009372 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009373
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009374 private String getEncryptKey() {
9375 try {
9376 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9377 if (sdEncKey == null) {
9378 sdEncKey = SystemKeyStore.getInstance().
9379 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9380 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009381 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009382 return null;
9383 }
9384 }
9385 return sdEncKey;
9386 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009387 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009388 return null;
9389 }
9390 }
9391
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009392 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009393 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009394 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009395 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009396 if (list != null) {
9397 int idx = 0;
9398 int idList[] = new int[MAX_CONTAINERS];
9399 boolean neverFound = true;
9400 for (String name : list) {
9401 // Ignore null entries
9402 if (name == null) {
9403 continue;
9404 }
9405 int sidx = name.indexOf(prefix);
9406 if (sidx == -1) {
9407 // Not a temp file. just ignore
9408 continue;
9409 }
9410 String subStr = name.substring(sidx + prefix.length());
9411 idList[idx] = -1;
9412 if (subStr != null) {
9413 try {
9414 int cid = Integer.parseInt(subStr);
9415 idList[idx++] = cid;
9416 neverFound = false;
9417 } catch (NumberFormatException e) {
9418 }
9419 }
9420 }
9421 if (!neverFound) {
9422 // Sort idList
9423 Arrays.sort(idList);
9424 for (int j = 1; j <= idList.length; j++) {
9425 if (idList[j-1] != j) {
9426 tmpIdx = j;
9427 break;
9428 }
9429 }
9430 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009431 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009432 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009433 }
9434
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009435 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009436 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009437 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009438 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9439 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9440 throw new SecurityException("Media status can only be updated by the system");
9441 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009442 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009443 Log.i(TAG, "Updating external media status from " +
9444 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9445 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009446 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9447 mediaStatus+", mMediaMounted=" + mMediaMounted);
9448 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009449 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9450 reportStatus ? 1 : 0, -1);
9451 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009452 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009453 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009454 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009455 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009456 // Queue up an async operation since the package installation may take a little while.
9457 mHandler.post(new Runnable() {
9458 public void run() {
9459 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009460 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009461 }
9462 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009463 }
9464
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009465 /*
9466 * Collect information of applications on external media, map them
9467 * against existing containers and update information based on current
9468 * mount status. Please note that we always have to report status
9469 * if reportStatus has been set to true especially when unloading packages.
9470 */
9471 private void updateExternalMediaStatusInner(boolean mediaStatus,
9472 boolean reportStatus) {
9473 // Collection of uids
9474 int uidArr[] = null;
9475 // Collection of stale containers
9476 HashSet<String> removeCids = new HashSet<String>();
9477 // Collection of packages on external media with valid containers.
9478 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9479 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009480 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009481 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009482 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009483 } else {
9484 // Process list of secure containers and categorize them
9485 // as active or stale based on their package internal state.
9486 int uidList[] = new int[list.length];
9487 int num = 0;
9488 synchronized (mPackages) {
9489 for (String cid : list) {
9490 SdInstallArgs args = new SdInstallArgs(cid);
9491 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009492 String pkgName = args.getPackageName();
9493 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009494 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9495 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009496 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009497 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009498 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9499 PackageSetting ps = mSettings.mPackages.get(pkgName);
9500 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009501 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009502 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9503 " corresponds to pkg : " + pkgName +
9504 " at code path: " + ps.codePathString);
9505 // We do have a valid package installed on sdcard
9506 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009507 int uid = ps.userId;
9508 if (uid != -1) {
9509 uidList[num++] = uid;
9510 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009511 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009512 // Stale container on sdcard. Just delete
9513 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9514 removeCids.add(cid);
9515 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009516 }
9517 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009518
9519 if (num > 0) {
9520 // Sort uid list
9521 Arrays.sort(uidList, 0, num);
9522 // Throw away duplicates
9523 uidArr = new int[num];
9524 uidArr[0] = uidList[0];
9525 int di = 0;
9526 for (int i = 1; i < num; i++) {
9527 if (uidList[i-1] != uidList[i]) {
9528 uidArr[di++] = uidList[i];
9529 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009530 }
9531 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009532 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009533 // Process packages with valid entries.
9534 if (mediaStatus) {
9535 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009536 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009537 startCleaningPackages();
9538 } else {
9539 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009540 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009541 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009542 }
9543
9544 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009545 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009546 int size = pkgList.size();
9547 if (size > 0) {
9548 // Send broadcasts here
9549 Bundle extras = new Bundle();
9550 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9551 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009552 if (uidArr != null) {
9553 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9554 }
9555 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9556 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009557 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009558 }
9559 }
9560
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009561 /*
9562 * Look at potentially valid container ids from processCids
9563 * If package information doesn't match the one on record
9564 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009565 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009566 */
9567 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009568 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009569 ArrayList<String> pkgList = new ArrayList<String>();
9570 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009571 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009572 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009573 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009574 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9575 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009576 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009577 try {
9578 // Make sure there are no container errors first.
9579 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9580 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009581 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009582 " when installing from sdcard");
9583 continue;
9584 }
9585 // Check code path here.
9586 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009587 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009588 " does not match one in settings " + codePath);
9589 continue;
9590 }
9591 // Parse package
9592 int parseFlags = PackageParser.PARSE_CHATTY |
Jeff Brown07330792010-03-30 19:57:08 -07009593 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009594 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009595 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009596 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9597 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009598 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009599 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009600 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009601 retCode = PackageManager.INSTALL_SUCCEEDED;
9602 pkgList.add(pkg.packageName);
9603 // Post process args
9604 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9605 }
9606 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009607 Slog.i(TAG, "Failed to install pkg from " +
9608 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009609 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009610 }
9611
9612 } finally {
9613 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9614 // Don't destroy container here. Wait till gc clears things up.
9615 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009616 }
9617 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009618 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009619 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009620 // If the platform SDK has changed since the last time we booted,
9621 // we need to re-grant app permission to catch any new ones that
9622 // appear. This is really a hack, and means that apps can in some
9623 // cases get permissions that the user didn't initially explicitly
9624 // allow... it would be nice to have some better way to handle
9625 // this situation.
9626 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9627 != mSdkVersion;
9628 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9629 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9630 + "; regranting permissions for external storage");
9631 mSettings.mExternalSdkPlatform = mSdkVersion;
9632
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009633 // Make sure group IDs have been assigned, and any permission
9634 // changes in other apps are accounted for
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009635 updatePermissionsLP(null, null, true, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009636 // Persist settings
9637 mSettings.writeLP();
9638 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009639 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009640 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009641 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009642 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009643 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009644 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009645 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009646 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009647 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009648 if (removeCids != null) {
9649 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009650 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009651 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009652 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009653 }
9654
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009655 /*
9656 * Utility method to unload a list of specified containers
9657 */
9658 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9659 // Just unmount all valid containers.
9660 for (SdInstallArgs arg : cidArgs) {
9661 synchronized (mInstallLock) {
9662 arg.doPostDeleteLI(false);
9663 }
9664 }
9665 }
9666
9667 /*
9668 * Unload packages mounted on external media. This involves deleting
9669 * package data from internal structures, sending broadcasts about
9670 * diabled packages, gc'ing to free up references, unmounting all
9671 * secure containers corresponding to packages on external media, and
9672 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9673 * Please note that we always have to post this message if status has
9674 * been requested no matter what.
9675 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009676 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009677 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009678 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009679 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009680 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009681 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009682 for (SdInstallArgs args : keys) {
9683 String cid = args.cid;
9684 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009685 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009686 // Delete package internally
9687 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9688 synchronized (mInstallLock) {
9689 boolean res = deletePackageLI(pkgName, false,
9690 PackageManager.DONT_DELETE_DATA, outInfo);
9691 if (res) {
9692 pkgList.add(pkgName);
9693 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009694 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009695 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009696 }
9697 }
9698 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009699 // We have to absolutely send UPDATED_MEDIA_STATUS only
9700 // after confirming that all the receivers processed the ordered
9701 // broadcast when packages get disabled, force a gc to clean things up.
9702 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009703 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009704 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9705 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9706 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009707 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9708 reportStatus ? 1 : 0, 1, keys);
9709 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009710 }
9711 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009712 } else {
9713 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9714 reportStatus ? 1 : 0, -1, keys);
9715 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009716 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009717 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009718
9719 public void movePackage(final String packageName,
9720 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009721 mContext.enforceCallingOrSelfPermission(
9722 android.Manifest.permission.MOVE_PACKAGE, null);
9723 int returnCode = PackageManager.MOVE_SUCCEEDED;
9724 int currFlags = 0;
9725 int newFlags = 0;
9726 synchronized (mPackages) {
9727 PackageParser.Package pkg = mPackages.get(packageName);
9728 if (pkg == null) {
9729 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009730 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009731 // Disable moving fwd locked apps and system packages
9732 if (pkg.applicationInfo != null &&
9733 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9734 Slog.w(TAG, "Cannot move system application");
9735 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9736 } else if (pkg.applicationInfo != null &&
9737 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9738 Slog.w(TAG, "Cannot move forward locked app.");
9739 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009740 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009741 // Find install location first
9742 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9743 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9744 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009745 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009746 } else {
9747 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9748 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9749 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9750 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9751 if (newFlags == currFlags) {
9752 Slog.w(TAG, "No move required. Trying to move to same location");
9753 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9754 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009755 }
9756 }
9757 }
9758 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9759 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9760 } else {
9761 Message msg = mHandler.obtainMessage(INIT_COPY);
9762 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9763 pkg.applicationInfo.publicSourceDir);
9764 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9765 packageName);
9766 msg.obj = mp;
9767 mHandler.sendMessage(msg);
9768 }
9769 }
9770 }
9771
9772 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9773 // Queue up an async operation since the package deletion may take a little while.
9774 mHandler.post(new Runnable() {
9775 public void run() {
9776 mHandler.removeCallbacks(this);
9777 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009778 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9779 int uidArr[] = null;
9780 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009781 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009782 PackageParser.Package pkg = mPackages.get(mp.packageName);
9783 if (pkg == null ) {
9784 Slog.w(TAG, " Package " + mp.packageName +
9785 " doesn't exist. Aborting move");
9786 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9787 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9788 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9789 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9790 " Aborting move and returning error");
9791 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9792 } else {
9793 uidArr = new int[] { pkg.applicationInfo.uid };
9794 pkgList = new ArrayList<String>();
9795 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009796 }
9797 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009798 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9799 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009800 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009801 // Update package code and resource paths
9802 synchronized (mInstallLock) {
9803 synchronized (mPackages) {
9804 PackageParser.Package pkg = mPackages.get(mp.packageName);
9805 // Recheck for package again.
9806 if (pkg == null ) {
9807 Slog.w(TAG, " Package " + mp.packageName +
9808 " doesn't exist. Aborting move");
9809 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9810 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9811 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9812 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9813 " Aborting move and returning error");
9814 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9815 } else {
9816 String oldCodePath = pkg.mPath;
9817 String newCodePath = mp.targetArgs.getCodePath();
9818 String newResPath = mp.targetArgs.getResourcePath();
9819 pkg.mPath = newCodePath;
9820 // Move dex files around
9821 if (moveDexFilesLI(pkg)
9822 != PackageManager.INSTALL_SUCCEEDED) {
9823 // Moving of dex files failed. Set
9824 // error code and abort move.
9825 pkg.mPath = pkg.mScanPath;
9826 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9827 } else {
9828 pkg.mScanPath = newCodePath;
9829 pkg.applicationInfo.sourceDir = newCodePath;
9830 pkg.applicationInfo.publicSourceDir = newResPath;
9831 PackageSetting ps = (PackageSetting) pkg.mExtras;
9832 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9833 ps.codePathString = ps.codePath.getPath();
9834 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9835 ps.resourcePathString = ps.resourcePath.getPath();
9836 // Set the application info flag correctly.
9837 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9838 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9839 } else {
9840 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9841 }
9842 ps.setFlags(pkg.applicationInfo.flags);
9843 mAppDirs.remove(oldCodePath);
9844 mAppDirs.put(newCodePath, pkg);
9845 // Persist settings
9846 mSettings.writeLP();
9847 }
9848 }
9849 }
9850 // Send resources available broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009851 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009852 }
9853 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009854 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009855 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009856 // Clean up failed installation
9857 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009858 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009859 }
9860 } else {
9861 // Force a gc to clear things up.
9862 Runtime.getRuntime().gc();
9863 // Delete older code
9864 synchronized (mInstallLock) {
9865 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009866 }
9867 }
9868 IPackageMoveObserver observer = mp.observer;
9869 if (observer != null) {
9870 try {
9871 observer.packageMoved(mp.packageName, returnCode);
9872 } catch (RemoteException e) {
9873 Log.i(TAG, "Observer no longer exists.");
9874 }
9875 }
9876 }
9877 });
9878 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009879
9880 public boolean setInstallLocation(int loc) {
9881 mContext.enforceCallingOrSelfPermission(
9882 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9883 if (getInstallLocation() == loc) {
9884 return true;
9885 }
9886 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9887 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9888 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9889 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9890 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9891 return true;
9892 }
9893 return false;
9894 }
9895
9896 public int getInstallLocation() {
9897 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9898 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009900}
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009901